@tsplc/compiler 0.5.5 → 0.5.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (80) hide show
  1. package/dist/bun-runtime.js +152 -31
  2. package/dist/bun-runtime.js.map +10 -9
  3. package/dist/cli.js +8 -5
  4. package/dist/cli.js.map +3 -3
  5. package/dist/codesys.js +260 -85
  6. package/dist/codesys.js.map +9 -9
  7. package/dist/collections.js +395 -0
  8. package/dist/collections.js.map +10 -0
  9. package/dist/elaborate-capture.js +62 -4
  10. package/dist/elaborate-capture.js.map +4 -4
  11. package/dist/index.js +5322 -1058
  12. package/dist/index.js.map +30 -23
  13. package/dist/ir.js +122 -1
  14. package/dist/ir.js.map +6 -6
  15. package/dist/project.js +8 -5
  16. package/dist/project.js.map +3 -3
  17. package/package.json +14 -9
  18. package/src/codesys/emit.ts +8 -2
  19. package/src/codesys/http.ts +114 -72
  20. package/src/codesys/instrumentation.ts +30 -6
  21. package/src/codesys/numeric.ts +61 -0
  22. package/src/codesys/routines.ts +39 -9
  23. package/src/codesys/st-files.ts +73 -6
  24. package/src/codesys/telemetry.ts +70 -35
  25. package/src/frontend/control-flow.ts +752 -0
  26. package/src/frontend/coroutines.ts +171 -7
  27. package/src/frontend/elaborate/array-searches.ts +216 -0
  28. package/src/frontend/elaborate/assignments.ts +352 -0
  29. package/src/frontend/elaborate/calls.ts +467 -42
  30. package/src/frontend/elaborate/capture-protocol.ts +19 -0
  31. package/src/frontend/elaborate/capture.ts +80 -2
  32. package/src/frontend/elaborate/dialect.ts +116 -2
  33. package/src/frontend/elaborate/expressions.ts +927 -80
  34. package/src/frontend/elaborate/filtered-arrays.ts +607 -0
  35. package/src/frontend/elaborate/frame.ts +44 -1
  36. package/src/frontend/elaborate/generics.ts +137 -0
  37. package/src/frontend/elaborate/graph.ts +91 -0
  38. package/src/frontend/elaborate/index.ts +30 -5
  39. package/src/frontend/elaborate/initializers.ts +15 -1
  40. package/src/frontend/elaborate/iterators.ts +1677 -0
  41. package/src/frontend/elaborate/layouts.ts +41 -19
  42. package/src/frontend/elaborate/model.ts +64 -8
  43. package/src/frontend/elaborate/references.ts +749 -0
  44. package/src/frontend/elaborate/specialize.ts +459 -29
  45. package/src/frontend/elaborate/statements.ts +552 -133
  46. package/src/frontend/elaborate/storage.ts +151 -10
  47. package/src/frontend/elaborate/values.ts +72 -0
  48. package/src/frontend/elaborate/writes.ts +302 -1
  49. package/src/frontend/intrinsics.ts +32 -0
  50. package/src/frontend/module-graph.ts +2 -1
  51. package/src/frontend/positions.ts +12 -5
  52. package/src/frontend/typescript.ts +5 -1
  53. package/src/ir/core-model.ts +2 -6
  54. package/src/ir/fold.ts +30 -1
  55. package/src/ir/index.ts +5 -0
  56. package/src/ir/model.ts +53 -2
  57. package/src/ir/scalars.ts +126 -0
  58. package/src/runtime/.runtime-VaUSOu/server/router.ts +17 -0
  59. package/src/runtime/.runtime-VaUSOu/src/cell.ts +45 -0
  60. package/src/runtime/.runtime-VaUSOu/src/controller.ts +58 -0
  61. package/src/runtime/.runtime-VaUSOu/src/lane.ts +6 -0
  62. package/src/runtime/.runtime-VaUSOu/src/main.ts +11 -0
  63. package/src/runtime/.runtime-VaUSOu/src/services.ts +8 -0
  64. package/src/runtime/.runtime-VaUSOu/tsconfig.json +13 -0
  65. package/src/runtime/.runtime-VaUSOu/tsplc.config.ts +31 -0
  66. package/src/runtime/.runtime-ybIxYh/server/router.ts +17 -0
  67. package/src/runtime/.runtime-ybIxYh/src/cell.ts +45 -0
  68. package/src/runtime/.runtime-ybIxYh/src/controller.ts +58 -0
  69. package/src/runtime/.runtime-ybIxYh/src/lane.ts +6 -0
  70. package/src/runtime/.runtime-ybIxYh/src/main.ts +11 -0
  71. package/src/runtime/.runtime-ybIxYh/src/services.ts +8 -0
  72. package/src/runtime/.runtime-ybIxYh/tsconfig.json +13 -0
  73. package/src/runtime/.runtime-ybIxYh/tsplc.config.ts +31 -0
  74. package/src/runtime/async.ts +15 -12
  75. package/src/runtime/launch.ts +11 -4
  76. package/src/runtime/runtime.ts +26 -23
  77. package/src/runtime/telemetry.ts +14 -6
  78. package/src/runtime/transport.ts +172 -0
  79. package/stdlib/collections.ts +514 -0
  80. package/types/index.d.ts +18 -0
@@ -5,12 +5,41 @@ import type { DialectText } from "./dialect";
5
5
  import type { ExpressionSpecializer, SpecializeContext } from "./expressions";
6
6
  import type { Frame } from "./frame";
7
7
  import type { Initializers } from "./initializers";
8
+ import {
9
+ type GeneratorCall,
10
+ iterationCount,
11
+ type Jumps,
12
+ type Traversal,
13
+ } from "./iterators";
8
14
  import type { Layouts } from "./layouts";
9
- import { SpecializeError, type Value } from "./values";
10
- import { isAssignment, isUpdate } from "./writes";
15
+ import {
16
+ constant,
17
+ type FunctionLike,
18
+ SpecializeError,
19
+ type Value,
20
+ } from "./values";
21
+ import { assignsName, isAssignment, isUpdate } from "./writes";
22
+
23
+ /**
24
+ * A statement break and continue can reach. One emitted as written keeps its user's labels; one setup
25
+ * unrolled or folded is a labelled block, which a jump leaves by its emitted label.
26
+ */
27
+ interface JumpScope {
28
+ kind: "loop" | "switch" | "labelled";
29
+ labels: readonly string[];
30
+ breakLabel?: string;
31
+ continueLabel?: string;
32
+ }
11
33
 
12
34
  /** Specializes one routine's statements; expressions in them go through its ExpressionSpecializer. */
13
35
  export class StatementSpecializer {
36
+ private readonly scopes: JumpScope[] = [];
37
+ /** Statements that couldn't be specialized, each once, so one run reports every one. */
38
+ readonly failures: SpecializeError[] = [];
39
+ /** The generators running in place, outermost first, so one can't recurse into itself. */
40
+ private readonly generators: FunctionLike[] = [];
41
+ /** Labels written on the statement being specialized, for the loop or switch it turns out to be. */
42
+ private labels: readonly string[] = [];
14
43
  private readonly checker: ts.TypeChecker;
15
44
  private readonly dialect: DialectText;
16
45
  private readonly layouts: Layouts;
@@ -24,6 +53,10 @@ export class StatementSpecializer {
24
53
  this.dialect = context.dialect;
25
54
  this.layouts = context.layouts;
26
55
  this.initializers = context.initializers;
56
+ expressions.iterators.attach({
57
+ run: (generator, frame, at, each) =>
58
+ this.runGenerator(generator, frame, [], at, each),
59
+ });
27
60
  }
28
61
 
29
62
  body(node: ts.ConciseBody, frame: Frame): void {
@@ -54,9 +87,29 @@ export class StatementSpecializer {
54
87
  private statement(node: ts.Statement, frame: Frame): boolean {
55
88
  const enclosing = frame.emitter.origin;
56
89
  frame.emitter.origin = node;
57
- const returns = this.specializeStatement(node, frame);
58
- frame.emitter.origin = enclosing;
59
- return returns;
90
+ try {
91
+ return this.specializeStatement(node, frame);
92
+ } catch (cause) {
93
+ // A failure is recorded and the statement skipped; the build stops after reporting them all.
94
+ if (
95
+ !(cause instanceof SpecializeError) ||
96
+ ts.isBlock(node) ||
97
+ node.getChildren().some((child) => ts.isBlock(child))
98
+ ) {
99
+ throw cause;
100
+ }
101
+ if (
102
+ !this.failures.some(
103
+ (failure) =>
104
+ failure.node === cause.node && failure.message === cause.message,
105
+ )
106
+ ) {
107
+ this.failures.push(cause);
108
+ }
109
+ return false;
110
+ } finally {
111
+ frame.emitter.origin = enclosing;
112
+ }
60
113
  }
61
114
 
62
115
  private specializeStatement(node: ts.Statement, frame: Frame): boolean {
@@ -75,6 +128,10 @@ export class StatementSpecializer {
75
128
  return false;
76
129
  }
77
130
  if (ts.isExpressionStatement(node)) {
131
+ if (ts.isYieldExpression(node.expression)) {
132
+ this.yieldStatement(node.expression, frame);
133
+ return false;
134
+ }
78
135
  this.effect(node.expression, frame);
79
136
  return false;
80
137
  }
@@ -97,6 +154,14 @@ export class StatementSpecializer {
97
154
  this.forLoop(node, frame);
98
155
  return false;
99
156
  }
157
+ if (
158
+ (ts.isWhileStatement(node) || ts.isDoStatement(node)) &&
159
+ frame.async &&
160
+ containsAwait(node.statement)
161
+ ) {
162
+ this.suspendingLoop(node, frame);
163
+ return false;
164
+ }
100
165
  if (ts.isWhileStatement(node)) {
101
166
  throw new SpecializeError(
102
167
  node,
@@ -108,18 +173,77 @@ export class StatementSpecializer {
108
173
  return false;
109
174
  }
110
175
  if (ts.isBreakStatement(node) || ts.isContinueStatement(node)) {
111
- emitter.line(copied(node));
176
+ emitter.line(this.jumpText(node));
177
+ return false;
178
+ }
179
+ if (ts.isLabeledStatement(node)) {
180
+ this.labelled(node, frame);
112
181
  return false;
113
182
  }
114
183
  if (ts.isEmptyStatement(node)) {
115
184
  return false;
116
185
  }
186
+ if (ts.isThrowStatement(node) && frame.async) {
187
+ // An async routine fails with an error code, which its caller's catch block receives.
188
+ const code = this.expressions.expression(node.expression, frame);
189
+ emitter.line(mapped`throw ${this.dialect.code(code, undefined)};`);
190
+ return true;
191
+ }
117
192
  throw new SpecializeError(
118
193
  node,
119
194
  `${ts.SyntaxKind[node.kind]} is not supported in scan code.`,
120
195
  );
121
196
  }
122
197
 
198
+ /** A jump as written, or out of the labelled block standing for a loop or switch setup unrolled or folded. */
199
+ private jumpText(node: ts.BreakStatement | ts.ContinueStatement): Part {
200
+ const label = node.label?.text;
201
+ const scope = [...this.scopes].reverse().find((item) => {
202
+ if (label !== undefined) {
203
+ return item.labels.includes(label);
204
+ }
205
+ return (
206
+ item.kind === "loop" ||
207
+ (ts.isBreakStatement(node) && item.kind === "switch")
208
+ );
209
+ });
210
+ const emitted = ts.isBreakStatement(node)
211
+ ? scope?.breakLabel
212
+ : scope?.continueLabel;
213
+ return emitted ? `break ${emitted};` : copied(node);
214
+ }
215
+
216
+ /** Takes the labels on the statement for the loop or switch it labels; a labelled block keeps them as written. */
217
+ private labelled(node: ts.LabeledStatement, frame: Frame): void {
218
+ const labels: string[] = [];
219
+ const inner = innermostLabelled(node, labels);
220
+ if (ts.isIterationStatement(inner, false) || ts.isSwitchStatement(inner)) {
221
+ this.labels = labels;
222
+ this.statement(inner, frame);
223
+ this.labels = [];
224
+ return;
225
+ }
226
+ frame.emitter.open(`${labels.map((label) => `${label}: `).join("")}{`);
227
+ this.scoped({ kind: "labelled", labels }, () => this.inner(inner, frame));
228
+ frame.emitter.close();
229
+ }
230
+
231
+ /** The labels on the loop or switch about to be specialized, which it takes. */
232
+ private takeLabels(): readonly string[] {
233
+ const labels = this.labels;
234
+ this.labels = [];
235
+ return labels;
236
+ }
237
+
238
+ private scoped<T>(scope: JumpScope, run: () => T): T {
239
+ this.scopes.push(scope);
240
+ try {
241
+ return run();
242
+ } finally {
243
+ this.scopes.pop();
244
+ }
245
+ }
246
+
123
247
  /** An if on a value setup fixed keeps only the branch it takes. */
124
248
  private ifStatement(node: ts.IfStatement, frame: Frame): boolean {
125
249
  const condition = this.expressions.expression(node.expression, frame);
@@ -152,6 +276,11 @@ export class StatementSpecializer {
152
276
 
153
277
  /** `return x satisfies never` marks an unreachable end, which returns the result type's default. */
154
278
  private returnStatement(node: ts.ReturnStatement, frame: Frame): void {
279
+ // A generator run in place ends by leaving its block.
280
+ if (frame.generator) {
281
+ frame.emitter.line(`break ${frame.generator.exit};`);
282
+ return;
283
+ }
155
284
  if (!node.expression) {
156
285
  frame.emitter.line("return;");
157
286
  return;
@@ -170,11 +299,42 @@ export class StatementSpecializer {
170
299
  frame,
171
300
  frame.returns,
172
301
  );
302
+ this.expressions.references.returned(value, node.expression, frame);
303
+ if (
304
+ value.kind === "code" &&
305
+ ((value.place &&
306
+ value.declared &&
307
+ value.declared.flags & ts.TypeFlags.Object) ||
308
+ value.copyOf)
309
+ ) {
310
+ frame.returnsStored = true;
311
+ }
312
+ // An array's length is what is returned, as its type names none.
313
+ const element =
314
+ frame.returns &&
315
+ this.checker.getIndexTypeOfType(frame.returns, ts.IndexKind.Number);
316
+ if (element && value.kind === "virtual" && value.items) {
317
+ frame.resultLayout = `FixedArray<${this.layouts.text(element, undefined)}, ${Math.max(value.items.length, 1)}>`;
318
+ frame.resultLength = value.items.length;
319
+ } else if (element && value.kind === "code" && value.layout) {
320
+ frame.resultLayout = value.layout;
321
+ frame.resultLength = value.length;
322
+ }
323
+ // A return stores into the result as an assignment does: wrapped as an optional, converted to its width.
173
324
  frame.emitter.line(
174
- mapped`return ${this.dialect.code(value, frame.returns)};`,
325
+ mapped`return ${this.dialect.returnText(value, frame.returns, this.resultIec(frame))};`,
175
326
  );
176
327
  }
177
328
 
329
+ /** The IEC width a routine's result is declared with, as `(): UINT` gives it. */
330
+ private resultIec(frame: Frame): string | undefined {
331
+ const declaration = frame.emitter.origin;
332
+ const routine = ts.findAncestor(declaration, ts.isFunctionLike);
333
+ return routine && "type" in routine && routine.type
334
+ ? this.layouts.iecName(routine)
335
+ : undefined;
336
+ }
337
+
178
338
  /** A try keeps its blocks, for the service calls in it. */
179
339
  private tryStatement(node: ts.TryStatement, frame: Frame): void {
180
340
  frame.emitter.open("try {");
@@ -199,6 +359,12 @@ export class StatementSpecializer {
199
359
  this.statement(statement, frame);
200
360
  }
201
361
  }
362
+ if (node.finallyBlock) {
363
+ frame.emitter.reopen("} finally {");
364
+ for (const statement of node.finallyBlock.statements) {
365
+ this.statement(statement, frame);
366
+ }
367
+ }
202
368
  frame.emitter.close();
203
369
  }
204
370
 
@@ -219,27 +385,51 @@ export class StatementSpecializer {
219
385
  frame: Frame,
220
386
  ): void {
221
387
  const initializer = declaration.initializer;
222
- if (!initializer) {
223
- throw new SpecializeError(
224
- declaration,
225
- "Initialize locals where they are declared.",
226
- );
227
- }
228
- const value = this.expressions.expression(
229
- initializer,
230
- frame,
231
- declaration.type && this.checker.getTypeAtLocation(declaration.type),
232
- );
388
+ const declared = this.checker.getTypeAtLocation(declaration.name);
389
+ // TypeScript proves a local assigned before it is read, so one declared bare starts at its type's default.
390
+ const value = initializer
391
+ ? this.expressions.expression(
392
+ initializer,
393
+ frame,
394
+ declaration.type && this.checker.getTypeAtLocation(declaration.type),
395
+ )
396
+ : this.bareValue(declared);
233
397
  this.expressions.bind(
234
398
  declaration.name,
235
399
  value,
236
400
  mutable,
237
401
  frame,
238
402
  this.checker.getTypeAtLocation(declaration.name),
403
+ this.layouts.iecName(declaration),
239
404
  );
240
405
  }
241
406
 
407
+ /** What a local declared without a value holds until it is assigned. */
408
+ private bareValue(declared: ts.Type): Value {
409
+ if (this.checker.getNonNullableType(declared) !== declared) {
410
+ return constant(undefined);
411
+ }
412
+ return {
413
+ kind: "code",
414
+ text: this.initializers.defaultOf(declared),
415
+ declared,
416
+ };
417
+ }
418
+
242
419
  private forOf(node: ts.ForOfStatement, frame: Frame): void {
420
+ const generator = this.expressions.generator(node.expression, frame);
421
+ if (generator) {
422
+ this.inlineGenerator(node, generator, this.takeLabels(), frame);
423
+ return;
424
+ }
425
+ const iterated = this.expressions.iterators.iterated(
426
+ node.expression,
427
+ frame,
428
+ );
429
+ if (iterated) {
430
+ this.overTraversal(node, iterated, frame);
431
+ return;
432
+ }
243
433
  const call = node.expression;
244
434
  if (
245
435
  ts.isCallExpression(call) &&
@@ -257,6 +447,14 @@ export class StatementSpecializer {
257
447
  }
258
448
  }
259
449
  const iterable = this.expressions.expression(node.expression, frame);
450
+ if (iterable.kind === "counted") {
451
+ this.overTraversal(
452
+ node,
453
+ this.expressions.iterators.over(iterable),
454
+ frame,
455
+ );
456
+ return;
457
+ }
260
458
  const items = this.expressions.items(iterable);
261
459
  const declaration = onlyDeclaration(node.initializer);
262
460
  if (!declaration) {
@@ -267,13 +465,11 @@ export class StatementSpecializer {
267
465
  }
268
466
  const name = declaration.name;
269
467
  const declared = this.checker.getTypeAtLocation(name);
468
+ const labels = this.takeLabels();
270
469
  if (items) {
271
- for (const item of items) {
272
- frame.emitter.open("{");
273
- this.expressions.bind(name, item, false, frame, declared);
274
- this.inner(node.statement, frame);
275
- frame.emitter.close();
276
- }
470
+ this.unrolled(node.statement, labels, items.length, frame, (index) =>
471
+ this.expressions.bind(name, items[index]!, false, frame, declared),
472
+ );
277
473
  return;
278
474
  }
279
475
  if (iterable.kind !== "code") {
@@ -286,17 +482,216 @@ export class StatementSpecializer {
286
482
  );
287
483
  }
288
484
  const local = frame.emitter.local(name.text);
289
- frame.emitter.open(mapped`for (const ${local} of ${iterable.text}) {`);
485
+ frame.emitter.open(
486
+ mapped`${labelText(labels)}for (const ${local} of ${iterable.text}) {`,
487
+ );
290
488
  frame.env.set(this.checker.getSymbolAtLocation(name)!, {
291
489
  kind: "code",
292
490
  text: local,
293
491
  declared,
294
492
  place: true,
295
493
  });
296
- this.inner(node.statement, frame);
494
+ this.expressions.iterators.looping(undefined, () =>
495
+ this.scoped({ kind: "loop", labels }, () =>
496
+ this.inner(node.statement, frame),
497
+ ),
498
+ );
297
499
  frame.emitter.close();
298
500
  }
299
501
 
502
+ /**
503
+ * A for…of over a generator runs the generator's body in place: each yield runs the loop's body
504
+ * on the value, in a labelled block its continue leaves, and break or the generator's return leave
505
+ * the block around the whole generator.
506
+ */
507
+ private inlineGenerator(
508
+ node: ts.ForOfStatement,
509
+ generator: GeneratorCall,
510
+ labels: readonly string[],
511
+ frame: Frame,
512
+ ): void {
513
+ this.runGenerator(
514
+ generator,
515
+ frame,
516
+ labels,
517
+ node,
518
+ this.loopBody(node, labels, frame),
519
+ );
520
+ }
521
+
522
+ /** A for…of over an iterator read through helpers, or over an array whose length is decided at run time. */
523
+ private overTraversal(
524
+ node: ts.ForOfStatement,
525
+ traversal: Traversal,
526
+ frame: Frame,
527
+ ): void {
528
+ const body = this.loopBody(node, this.takeLabels(), frame);
529
+ traversal.run(frame, (element) => body(element.value, element));
530
+ }
531
+
532
+ /**
533
+ * What a for…of does with each value it is given where the value is produced: binds its name
534
+ * and runs its body, whose break and continue leave the labelled statements around it.
535
+ */
536
+ private loopBody(
537
+ node: ts.ForOfStatement,
538
+ labels: readonly string[],
539
+ frame: Frame,
540
+ ): (value: Value, jumps: Jumps) => void {
541
+ const declaration = onlyDeclaration(node.initializer);
542
+ if (!declaration) {
543
+ throw new SpecializeError(
544
+ node.initializer,
545
+ "Declare one const in for…of.",
546
+ );
547
+ }
548
+ const declared = this.checker.getTypeAtLocation(declaration.name);
549
+ const loop: Frame = { ...frame, env: new Map(frame.env) };
550
+ return (value, jumps) => {
551
+ this.expressions.bind(declaration.name, value, false, loop, declared);
552
+ this.scoped(
553
+ {
554
+ kind: "loop",
555
+ labels,
556
+ breakLabel: jumps.whole,
557
+ continueLabel: jumps.label,
558
+ },
559
+ () => this.inner(node.statement, loop),
560
+ );
561
+ };
562
+ }
563
+
564
+ /** Runs a generator's body in place, calling `each` for every value it yields. */
565
+ private runGenerator(
566
+ generator: GeneratorCall,
567
+ frame: Frame,
568
+ labels: readonly string[],
569
+ at: ts.Node,
570
+ each: (value: Value, jumps: Jumps) => void,
571
+ ): void {
572
+ const { declaration } = generator;
573
+ if (this.generators.includes(declaration)) {
574
+ throw new SpecializeError(
575
+ at,
576
+ "A generator runs in place, so it can't yield from itself.",
577
+ );
578
+ }
579
+ const body = declaration.body;
580
+ if (!body || !ts.isBlock(body)) {
581
+ throw new SpecializeError(at, "A generator needs a body.");
582
+ }
583
+ const whole = frame.emitter.local("tsplcGenerator");
584
+ const outside = this.generators.length;
585
+ const inner: Frame = {
586
+ ...frame,
587
+ env: new Map(),
588
+ self: generator.self,
589
+ returns: undefined,
590
+ generator: {
591
+ exit: whole,
592
+ yields: (value) => {
593
+ const label = frame.emitter.local("tsplcStep");
594
+ frame.emitter.open(`${label}: {`);
595
+ // What reads the value is outside this generator, so it may run the same generator itself.
596
+ const running = this.generators.splice(outside);
597
+ try {
598
+ each(value, { whole, label });
599
+ } finally {
600
+ this.generators.push(...running);
601
+ }
602
+ frame.emitter.close();
603
+ },
604
+ },
605
+ };
606
+ if (!ts.isGetAccessorDeclaration(declaration)) {
607
+ declaration.parameters.forEach((parameter, index) => {
608
+ const given = generator.args[index] ?? constant(undefined);
609
+ const value =
610
+ given.kind === "const" &&
611
+ given.value === undefined &&
612
+ parameter.initializer
613
+ ? this.expressions.expression(parameter.initializer, inner)
614
+ : given;
615
+ // A parameter the generator never assigns keeps what was passed, which can be known now.
616
+ this.expressions.bind(
617
+ parameter.name,
618
+ value,
619
+ assignsName(body, parameter.name, this.checker),
620
+ inner,
621
+ this.checker.getTypeAtLocation(parameter),
622
+ );
623
+ });
624
+ }
625
+ frame.emitter.open(`${labelText(labels)}${whole}: {`);
626
+ this.generators.push(declaration);
627
+ try {
628
+ this.statements(body.statements, inner);
629
+ } finally {
630
+ this.generators.pop();
631
+ }
632
+ frame.emitter.close();
633
+ }
634
+
635
+ /** A yield statement runs the loop over the generator on its value; `yield*` runs another generator in place. */
636
+ private yieldStatement(node: ts.YieldExpression, frame: Frame): void {
637
+ const generator = frame.generator;
638
+ if (!generator) {
639
+ throw new SpecializeError(
640
+ node,
641
+ "A generator runs only where a for…of or an iterator helper reads it.",
642
+ );
643
+ }
644
+ if (!node.expression) {
645
+ generator.yields(constant(undefined));
646
+ return;
647
+ }
648
+ if (node.asteriskToken) {
649
+ const delegated = this.expressions.generator(node.expression, frame);
650
+ if (!delegated) {
651
+ throw new SpecializeError(
652
+ node.expression,
653
+ "yield* runs another generator in place; pass it a generator call.",
654
+ );
655
+ }
656
+ this.runGenerator(delegated, frame, [], node, (value) =>
657
+ generator.yields(value),
658
+ );
659
+ return;
660
+ }
661
+ generator.yields(this.expressions.expression(node.expression, frame));
662
+ }
663
+
664
+ /**
665
+ * A loop over what setup built runs its body once per item. A body that breaks or continues runs
666
+ * inside labelled blocks, the whole loop's and each step's, which its jumps leave.
667
+ */
668
+ private unrolled(
669
+ body: ts.Statement,
670
+ labels: readonly string[],
671
+ count: number,
672
+ frame: Frame,
673
+ bindStep: (index: number) => void,
674
+ ): void {
675
+ const jumps = containsJump(body);
676
+ const whole = jumps ? frame.emitter.local("tsplcLoop") : undefined;
677
+ if (whole) {
678
+ frame.emitter.open(`${whole}: {`);
679
+ }
680
+ for (let index = 0; index < count; index++) {
681
+ const step = jumps ? frame.emitter.local("tsplcStep") : undefined;
682
+ frame.emitter.open(step ? `${step}: {` : "{");
683
+ bindStep(index);
684
+ this.scoped(
685
+ { kind: "loop", labels, breakLabel: whole, continueLabel: step },
686
+ () => this.inner(body, frame),
687
+ );
688
+ frame.emitter.close();
689
+ }
690
+ if (whole) {
691
+ frame.emitter.close();
692
+ }
693
+ }
694
+
300
695
  /** `for (const [index, item] of array.entries())` over a runtime array stays a loop, as the backend lowers it. */
301
696
  private forEntries(
302
697
  node: ts.ForOfStatement,
@@ -329,13 +724,49 @@ export class StatementSpecializer {
329
724
  });
330
725
  return local;
331
726
  });
727
+ const labels = this.takeLabels();
332
728
  frame.emitter.open(
333
- mapped`for (const [${[index, item].join(", ")}] of ${array}.entries()) {`,
729
+ mapped`${labelText(labels)}for (const [${[index, item].join(", ")}] of ${array}.entries()) {`,
730
+ );
731
+ this.expressions.iterators.looping(undefined, () =>
732
+ this.scoped({ kind: "loop", labels }, () =>
733
+ this.inner(node.statement, frame),
734
+ ),
334
735
  );
335
- this.inner(node.statement, frame);
336
736
  frame.emitter.close();
337
737
  }
338
738
 
739
+ /**
740
+ * A while or do loop that awaits, in an async routine: each wait ends a scan's share of it, so it
741
+ * needs no bound for a scan to finish.
742
+ */
743
+ private suspendingLoop(
744
+ node: ts.WhileStatement | ts.DoStatement,
745
+ frame: Frame,
746
+ ): void {
747
+ const labels = this.takeLabels();
748
+ const test = () =>
749
+ this.dialect.condition(
750
+ this.expressions.expression(node.expression, frame),
751
+ node.expression,
752
+ );
753
+ if (ts.isWhileStatement(node)) {
754
+ frame.emitter.open(mapped`${labelText(labels)}while (${test()}) {`);
755
+ } else {
756
+ frame.emitter.open(`${labelText(labels)}do {`);
757
+ }
758
+ this.expressions.iterators.looping(undefined, () =>
759
+ this.scoped({ kind: "loop", labels }, () =>
760
+ this.inner(node.statement, frame),
761
+ ),
762
+ );
763
+ if (ts.isWhileStatement(node)) {
764
+ frame.emitter.close();
765
+ return;
766
+ }
767
+ frame.emitter.close(mapped`} while (${test()});`);
768
+ }
769
+
339
770
  /** A counted loop stays a loop, in the header shape the backend proves bounded: `let i = start; i < bound; i++`. */
340
771
  private forLoop(node: ts.ForStatement, frame: Frame): void {
341
772
  const { condition, incrementor, initializer } = node;
@@ -359,10 +790,12 @@ export class StatementSpecializer {
359
790
  const declared = this.checker.getTypeAtLocation(name);
360
791
  // An annotation such as UINT keeps the counter's width, to index alongside unsigned fields.
361
792
  const iec = this.layouts.iecName(declaration);
362
- const start = this.dialect.code(
363
- this.expressions.expression(declaration.initializer, frame, declared),
793
+ const first = this.expressions.expression(
794
+ declaration.initializer,
795
+ frame,
364
796
  declared,
365
797
  );
798
+ const start = this.dialect.code(first, declared);
366
799
  const local = frame.emitter.local(name.text);
367
800
  frame.env.set(this.checker.getSymbolAtLocation(name)!, {
368
801
  kind: "code",
@@ -371,12 +804,29 @@ export class StatementSpecializer {
371
804
  place: true,
372
805
  iec,
373
806
  });
374
- const test = mapped`${this.dialect.code(this.expressions.expression(condition.left, frame), declared)} ${condition.operatorToken.getText()} ${this.dialect.code(this.expressions.expression(condition.right, frame), declared)}`;
807
+ const compared = this.expressions.expression(condition.left, frame);
808
+ const limit = this.expressions.expression(condition.right, frame);
809
+ const test = mapped`${this.dialect.code(compared, declared)} ${condition.operatorToken.getText()} ${this.dialect.code(limit, declared)}`;
375
810
  const step = this.loopStep(incrementor, local, declared, frame);
811
+ const labels = this.takeLabels();
376
812
  frame.emitter.open(
377
- mapped`for (let ${local}: ${iec ?? this.expressions.localType(declared)} = ${start}; ${test}; ${step}) {`,
813
+ mapped`${labelText(labels)}for (let ${local}: ${iec ?? this.expressions.localType(declared)} = ${start}; ${test}; ${step}) {`,
814
+ );
815
+ // How often the body runs is known when the header compares the counter itself with a bound setup fixed.
816
+ const runs =
817
+ compared.kind === "code" && String(compared.text) === local
818
+ ? iterationCount(
819
+ first,
820
+ condition.operatorToken.kind,
821
+ limit,
822
+ incrementor,
823
+ )
824
+ : undefined;
825
+ this.expressions.iterators.looping(runs, () =>
826
+ this.scoped({ kind: "loop", labels }, () =>
827
+ this.inner(node.statement, frame),
828
+ ),
378
829
  );
379
- this.inner(node.statement, frame);
380
830
  frame.emitter.close();
381
831
  }
382
832
 
@@ -405,13 +855,25 @@ export class StatementSpecializer {
405
855
  private switch(node: ts.SwitchStatement, frame: Frame): void {
406
856
  const subject = this.expressions.expression(node.expression, frame);
407
857
  const declared = subject.kind === "code" ? subject.declared : undefined;
858
+ const labels = this.takeLabels();
408
859
  if (subject.kind === "const") {
409
- this.constantSwitch(node, subject, frame);
860
+ this.constantSwitch(node, subject, labels, frame);
410
861
  return;
411
862
  }
412
863
  frame.emitter.open(
413
- mapped`switch (${this.dialect.code(subject, declared)}) {`,
864
+ mapped`${labelText(labels)}switch (${this.dialect.code(subject, declared)}) {`,
865
+ );
866
+ this.scoped({ kind: "switch", labels }, () =>
867
+ this.switchClauses(node, declared, frame),
414
868
  );
869
+ frame.emitter.close();
870
+ }
871
+
872
+ private switchClauses(
873
+ node: ts.SwitchStatement,
874
+ declared: ts.Type | undefined,
875
+ frame: Frame,
876
+ ): void {
415
877
  for (const clause of node.caseBlock.clauses) {
416
878
  if (ts.isDefaultClause(clause)) {
417
879
  const unreachable = clause.statements.some(
@@ -447,11 +909,37 @@ export class StatementSpecializer {
447
909
  }
448
910
  frame.emitter.close();
449
911
  }
450
- frame.emitter.close();
451
912
  }
452
913
 
453
- /** A switch on a value setup fixed runs the clause it matches, falling through as JavaScript does. */
914
+ /**
915
+ * A switch on a value setup fixed runs the clause it matches, falling through as JavaScript does. A
916
+ * break nested in it leaves the labelled block standing for the switch.
917
+ */
454
918
  private constantSwitch(
919
+ node: ts.SwitchStatement,
920
+ subject: Value & { kind: "const" },
921
+ labels: readonly string[],
922
+ frame: Frame,
923
+ ): void {
924
+ const nested = node.caseBlock.clauses.some((clause) =>
925
+ clause.statements.some(
926
+ (statement) =>
927
+ !ts.isBreakStatement(statement) && containsJump(statement),
928
+ ),
929
+ );
930
+ const label = nested ? frame.emitter.local("tsplcSwitch") : undefined;
931
+ if (label) {
932
+ frame.emitter.open(`${label}: {`);
933
+ }
934
+ this.scoped({ kind: "switch", labels, breakLabel: label }, () =>
935
+ this.matchedClauses(node, subject, frame),
936
+ );
937
+ if (label) {
938
+ frame.emitter.close();
939
+ }
940
+ }
941
+
942
+ private matchedClauses(
455
943
  node: ts.SwitchStatement,
456
944
  subject: Value & { kind: "const" },
457
945
  frame: Frame,
@@ -492,18 +980,11 @@ export class StatementSpecializer {
492
980
  return;
493
981
  }
494
982
  if (ts.isBinaryExpression(node) && isAssignment(node.operatorToken.kind)) {
495
- this.assign(node, frame);
983
+ this.expressions.assignments.assign(node, frame);
496
984
  return;
497
985
  }
498
986
  if (isUpdate(node)) {
499
- const target = this.expressions.expression(node.operand, frame);
500
- const text = this.placeText(target, node.operand);
501
- frame.emitter.line(
502
- this.store(
503
- target,
504
- mapped`${text} ${node.operator === ts.SyntaxKind.PlusPlusToken ? "+" : "-"} 1`,
505
- ),
506
- );
987
+ this.expressions.assignments.step(node, frame, { used: false });
507
988
  return;
508
989
  }
509
990
  const value = this.expressions.expression(node, frame);
@@ -511,95 +992,8 @@ export class StatementSpecializer {
511
992
  frame.emitter.line(mapped`${value.text};`);
512
993
  }
513
994
  }
514
-
515
- private assign(node: ts.BinaryExpression, frame: Frame): void {
516
- const target = this.expressions.expression(node.left, frame);
517
- const text = this.placeText(target, node.left);
518
- const declared = target.kind === "code" ? target.declared : undefined;
519
- const operator = node.operatorToken.kind;
520
- if (operator === ts.SyntaxKind.QuestionQuestionEqualsToken) {
521
- const value = this.expressions.expression(
522
- node.right,
523
- frame,
524
- declared && this.checker.getNonNullableType(declared),
525
- );
526
- frame.emitter.open(
527
- mapped`if (${this.dialect.isUndefinedText(text, declared)}) {`,
528
- );
529
- frame.emitter.line(
530
- this.store(
531
- target,
532
- this.dialect.wrapDefined(
533
- this.dialect.code(
534
- value,
535
- declared && this.checker.getNonNullableType(declared),
536
- ),
537
- declared,
538
- ),
539
- ),
540
- );
541
- frame.emitter.close();
542
- return;
543
- }
544
- const value = this.expressions.expression(node.right, frame, declared);
545
- if (operator === ts.SyntaxKind.EqualsToken) {
546
- frame.emitter.line(
547
- this.store(
548
- target,
549
- this.dialect.assignmentText(
550
- value,
551
- declared,
552
- target.kind === "code" ? target.iec : undefined,
553
- ),
554
- ),
555
- );
556
- return;
557
- }
558
- const binary = compoundOperators.get(operator);
559
- if (!binary) {
560
- throw new SpecializeError(
561
- node,
562
- `${node.operatorToken.getText()} is not supported.`,
563
- );
564
- }
565
- frame.emitter.line(
566
- this.store(
567
- target,
568
- mapped`${text} ${binary} ${this.dialect.code(value, declared)}`,
569
- ),
570
- );
571
- }
572
-
573
- /** A statement storing `text` into a place, through its module's setter when it has one. */
574
- private store(target: Value, text: Part): Mapped {
575
- if (target.kind !== "code") {
576
- throw new Error("Not a place.");
577
- }
578
- return target.setter
579
- ? mapped`${target.setter}(${text});`
580
- : mapped`${target.text} = ${text};`;
581
- }
582
-
583
- private placeText(value: Value, node: ts.Node): string | Mapped {
584
- if (value.kind === "code" && value.place) {
585
- return value.text;
586
- }
587
- throw new SpecializeError(
588
- node,
589
- "Assign to stored state: a field scan code owns, or a let.",
590
- );
591
- }
592
995
  }
593
996
 
594
- /** The operator each compound assignment applies. */
595
- const compoundOperators = new Map<ts.SyntaxKind, string>([
596
- [ts.SyntaxKind.PlusEqualsToken, "+"],
597
- [ts.SyntaxKind.MinusEqualsToken, "-"],
598
- [ts.SyntaxKind.AsteriskEqualsToken, "*"],
599
- [ts.SyntaxKind.BarEqualsToken, "|"],
600
- [ts.SyntaxKind.AmpersandEqualsToken, "&"],
601
- ]);
602
-
603
997
  /** The one variable a loop header declares; undefined when it declares none or several. */
604
998
  const onlyDeclaration = (
605
999
  initializer: ts.ForInitializer | undefined,
@@ -610,3 +1004,28 @@ const onlyDeclaration = (
610
1004
  const [declaration, ...others] = initializer.declarations;
611
1005
  return others.length ? undefined : declaration;
612
1006
  };
1007
+
1008
+ const labelText = (labels: readonly string[]): string =>
1009
+ labels.map((label) => `${label}: `).join("");
1010
+
1011
+ /** The statement under a run of labels, collecting them. */
1012
+ const innermostLabelled = (
1013
+ node: ts.LabeledStatement,
1014
+ labels: string[],
1015
+ ): ts.Statement => {
1016
+ labels.push(node.label.text);
1017
+ return ts.isLabeledStatement(node.statement)
1018
+ ? innermostLabelled(node.statement, labels)
1019
+ : node.statement;
1020
+ };
1021
+
1022
+ /** Whether a break or continue sits in the statement, outside functions it declares. */
1023
+ const containsJump = (node: ts.Node): boolean =>
1024
+ ts.isBreakStatement(node) ||
1025
+ ts.isContinueStatement(node) ||
1026
+ (!ts.isFunctionLike(node) && (ts.forEachChild(node, containsJump) ?? false));
1027
+
1028
+ /** Whether the statement awaits, outside functions it declares. */
1029
+ const containsAwait = (node: ts.Node): boolean =>
1030
+ ts.isAwaitExpression(node) ||
1031
+ (!ts.isFunctionLike(node) && (ts.forEachChild(node, containsAwait) ?? false));