@tsplc/compiler 0.5.4 → 0.5.6

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 (67) hide show
  1. package/dist/bun-runtime.js +14 -2
  2. package/dist/bun-runtime.js.map +4 -4
  3. package/dist/codesys.js +46 -2
  4. package/dist/codesys.js.map +3 -3
  5. package/dist/collections.js +395 -0
  6. package/dist/collections.js.map +10 -0
  7. package/dist/elaborate-capture.js +64 -5
  8. package/dist/elaborate-capture.js.map +4 -4
  9. package/dist/index.js +5345 -1074
  10. package/dist/index.js.map +32 -25
  11. package/dist/ir.js +122 -1
  12. package/dist/ir.js.map +6 -6
  13. package/package.json +14 -9
  14. package/src/codesys/numeric.ts +61 -0
  15. package/src/frontend/control-flow.ts +752 -0
  16. package/src/frontend/coroutines.ts +171 -7
  17. package/src/frontend/elaborate/array-searches.ts +216 -0
  18. package/src/frontend/elaborate/assignments.ts +352 -0
  19. package/src/frontend/elaborate/calls.ts +488 -49
  20. package/src/frontend/elaborate/capture-protocol.ts +19 -0
  21. package/src/frontend/elaborate/capture.ts +82 -3
  22. package/src/frontend/elaborate/dialect.ts +118 -4
  23. package/src/frontend/elaborate/expressions.ts +927 -80
  24. package/src/frontend/elaborate/filtered-arrays.ts +607 -0
  25. package/src/frontend/elaborate/frame.ts +44 -1
  26. package/src/frontend/elaborate/generics.ts +137 -0
  27. package/src/frontend/elaborate/graph.ts +91 -0
  28. package/src/frontend/elaborate/imports.ts +14 -15
  29. package/src/frontend/elaborate/index.ts +30 -5
  30. package/src/frontend/elaborate/initializers.ts +15 -1
  31. package/src/frontend/elaborate/iterators.ts +1677 -0
  32. package/src/frontend/elaborate/layouts.ts +41 -19
  33. package/src/frontend/elaborate/model.ts +64 -8
  34. package/src/frontend/elaborate/references.ts +749 -0
  35. package/src/frontend/elaborate/specialize.ts +459 -29
  36. package/src/frontend/elaborate/statements.ts +552 -133
  37. package/src/frontend/elaborate/storage.ts +151 -10
  38. package/src/frontend/elaborate/values.ts +72 -0
  39. package/src/frontend/elaborate/writes.ts +302 -1
  40. package/src/frontend/intrinsics.ts +32 -0
  41. package/src/frontend/module-graph.ts +2 -1
  42. package/src/frontend/positions.ts +12 -5
  43. package/src/frontend/sdk.ts +7 -1
  44. package/src/frontend/typescript.ts +5 -1
  45. package/src/ir/core-model.ts +2 -6
  46. package/src/ir/fold.ts +30 -1
  47. package/src/ir/index.ts +5 -0
  48. package/src/ir/model.ts +53 -2
  49. package/src/ir/scalars.ts +126 -0
  50. package/src/runtime/.runtime-VaUSOu/server/router.ts +17 -0
  51. package/src/runtime/.runtime-VaUSOu/src/cell.ts +45 -0
  52. package/src/runtime/.runtime-VaUSOu/src/controller.ts +58 -0
  53. package/src/runtime/.runtime-VaUSOu/src/lane.ts +6 -0
  54. package/src/runtime/.runtime-VaUSOu/src/main.ts +11 -0
  55. package/src/runtime/.runtime-VaUSOu/src/services.ts +8 -0
  56. package/src/runtime/.runtime-VaUSOu/tsconfig.json +13 -0
  57. package/src/runtime/.runtime-VaUSOu/tsplc.config.ts +31 -0
  58. package/src/runtime/.runtime-ybIxYh/server/router.ts +17 -0
  59. package/src/runtime/.runtime-ybIxYh/src/cell.ts +45 -0
  60. package/src/runtime/.runtime-ybIxYh/src/controller.ts +58 -0
  61. package/src/runtime/.runtime-ybIxYh/src/lane.ts +6 -0
  62. package/src/runtime/.runtime-ybIxYh/src/main.ts +11 -0
  63. package/src/runtime/.runtime-ybIxYh/src/services.ts +8 -0
  64. package/src/runtime/.runtime-ybIxYh/tsconfig.json +13 -0
  65. package/src/runtime/.runtime-ybIxYh/tsplc.config.ts +31 -0
  66. package/stdlib/collections.ts +514 -0
  67. package/types/index.d.ts +18 -0
@@ -0,0 +1,749 @@
1
+ import ts from "typescript";
2
+ import { type Mapped, mapped, type Part } from "../positions";
3
+ import type { DialectText } from "./dialect";
4
+ import type { ExpressionSpecializer, SpecializeContext } from "./expressions";
5
+ import type { Frame } from "./frame";
6
+ import type { Initializers } from "./initializers";
7
+ import { isAbsent } from "./layouts";
8
+ import type { Model, ModelNode } from "./model";
9
+ import type { Storage } from "./storage";
10
+ import { constant, SpecializeError, type Value } from "./values";
11
+
12
+ type Choice = Extract<Value, { kind: "choice" }>;
13
+
14
+ /** An assignment written through a reference chosen at run time: the place it writes in each object the reference can be. */
15
+ interface PlaceInEach {
16
+ kind: "each";
17
+ choice: Choice;
18
+ place: (option: ModelNode) => Value;
19
+ }
20
+
21
+ /** The PLC type of a reference: the id of the object it refers to, or -1 for undefined. */
22
+ export const referenceLayout = "number";
23
+
24
+ /** Whether a type's values are class instances, or undefined: what scan code holds by reference rather than as a copy. */
25
+ export const referenceType = (type: ts.Type): boolean => {
26
+ const defined = parts(type).filter((part) => !isAbsent(part));
27
+ return defined.length > 0 && defined.every(isInstanceType);
28
+ };
29
+
30
+ const parts = (type: ts.Type): readonly ts.Type[] =>
31
+ type.isUnion() ? type.types : [type];
32
+
33
+ /** A class's instances, not the class itself, which its constructor's type shares a symbol with. */
34
+ const isInstanceType = (type: ts.Type): boolean =>
35
+ Boolean(type.flags & ts.TypeFlags.Object) &&
36
+ type.getConstructSignatures().length === 0 &&
37
+ classesOf(type).length > 0;
38
+
39
+ const classesOf = (type: ts.Type): ts.ClassDeclaration[] =>
40
+ type.getSymbol()?.declarations?.filter(ts.isClassDeclaration) ?? [];
41
+
42
+ /** Objects a reference can refer to: functions and services are called, never held. */
43
+ export const referable = (node: ModelNode): boolean =>
44
+ node.captured.kind === "instance" ||
45
+ node.captured.kind === "object" ||
46
+ node.captured.kind === "array";
47
+
48
+ /**
49
+ * Code for the id a reference holds when it refers to the value: every object setup built has one
50
+ * id, so a reference means the same object wherever it is stored, passed or compared. Undefined
51
+ * for a value that is no reference.
52
+ */
53
+ export const referenceIndex = (value: Value): string | Mapped | undefined => {
54
+ if (value.kind === "choice") {
55
+ return value.index;
56
+ }
57
+ if (value.kind === "static" && referable(value.node)) {
58
+ return String(value.node.id);
59
+ }
60
+ if (value.kind === "const" && value.value === undefined) {
61
+ return "-1";
62
+ }
63
+ return undefined;
64
+ };
65
+
66
+ /** The objects a reference to the value can be. */
67
+ const optionsOf = (value: Value): readonly ModelNode[] => {
68
+ if (value.kind === "choice") {
69
+ return value.options;
70
+ }
71
+ return value.kind === "static" ? [value.node] : [];
72
+ };
73
+
74
+ /** Whether a reference to the value can be undefined. */
75
+ const absentOf = (value: Value): boolean =>
76
+ value.kind === "choice" ? value.optional : value.kind === "const";
77
+
78
+ /** Objects without repeats, in the order setup built them, so the code over them is the same every build. */
79
+ export const union = (nodes: readonly ModelNode[]): ModelNode[] =>
80
+ [...new Set(nodes)].sort((left, right) => left.id - right.id);
81
+
82
+ const maybeAbsent = (type: ts.Type): boolean => parts(type).some(isAbsent);
83
+
84
+ const unparenthesized = (node: ts.Expression): ts.Expression =>
85
+ ts.isParenthesizedExpression(node) || ts.isNonNullExpression(node)
86
+ ? unparenthesized(node.expression)
87
+ : node;
88
+
89
+ /** An if…else if chain, one arm for each test. */
90
+ export const chain = (
91
+ frame: Frame,
92
+ arms: readonly { test: Part; body: VoidFunction }[],
93
+ ): void => {
94
+ arms.forEach((arm, index) => {
95
+ if (index === 0) {
96
+ frame.emitter.open(mapped`if (${arm.test}) {`);
97
+ } else {
98
+ frame.emitter.reopen(mapped`} else if (${arm.test}) {`);
99
+ }
100
+ arm.body();
101
+ });
102
+ if (arms.length > 0) {
103
+ frame.emitter.close();
104
+ }
105
+ };
106
+
107
+ /** A reference that can only be one object is that object, and one that can be none is undefined. */
108
+ export const settled = (choice: Choice): Value => {
109
+ const [only, ...others] = choice.options;
110
+ if (!only) {
111
+ return constant(undefined);
112
+ }
113
+ return others.length === 0 && !choice.optional && !choice.place
114
+ ? { kind: "static", node: only }
115
+ : choice;
116
+ };
117
+
118
+ /**
119
+ * References scan code chooses at run time. Setup built every object, so a reference is the id of
120
+ * one of them: reading or calling through it runs the code of whichever object it holds, and a
121
+ * filter decided at run time is its candidates with a flag each.
122
+ */
123
+ export class References {
124
+ private readonly model: Model;
125
+ private readonly checker: ts.TypeChecker;
126
+ private readonly dialect: DialectText;
127
+ private readonly storage: Storage;
128
+ private readonly initializers: Initializers;
129
+ private readonly instances = new Map<string, ModelNode[]>();
130
+
131
+ constructor(
132
+ context: SpecializeContext,
133
+ private readonly expressions: ExpressionSpecializer,
134
+ ) {
135
+ this.model = context.model;
136
+ this.checker = context.checker;
137
+ this.dialect = context.dialect;
138
+ this.storage = context.storage;
139
+ this.initializers = context.initializers;
140
+ }
141
+
142
+ /** Every instance setup built of the classes a type names, or of their subclasses: what a reference of that type can hold. */
143
+ candidates(type: ts.Type): ModelNode[] {
144
+ const classes = parts(type).flatMap(classesOf);
145
+ const key = classes
146
+ .map((owner) => `${owner.getSourceFile().fileName}:${owner.pos}`)
147
+ .join("|");
148
+ const known = this.instances.get(key);
149
+ if (known) {
150
+ return known;
151
+ }
152
+ // An instance nothing owns has no storage, so scan code can't reach it.
153
+ const found = this.model.nodes.filter(
154
+ (node) =>
155
+ node.captured.kind === "instance" &&
156
+ node.owner !== undefined &&
157
+ this.model
158
+ .ancestry(this.model.classOf(node))
159
+ .some((owner) => classes.includes(owner)),
160
+ );
161
+ this.instances.set(key, found);
162
+ return found;
163
+ }
164
+
165
+ /** A field read from an instance: one that stores a reference reads as the choice it holds. */
166
+ field(read: Value, holder: ModelNode, name: string): Value {
167
+ if (read.kind !== "code" || !this.storage.referenceField(holder, name)) {
168
+ return read;
169
+ }
170
+ const declared = read.declared;
171
+ return {
172
+ kind: "choice",
173
+ options: declared ? this.candidates(declared) : [],
174
+ index: read.text,
175
+ optional: declared ? maybeAbsent(declared) : true,
176
+ place: true,
177
+ ...(read.setter && { setter: read.setter }),
178
+ };
179
+ }
180
+
181
+ /** A reference as a condition: whether it holds an object. */
182
+ present(choice: Choice): Value {
183
+ return choice.optional
184
+ ? {
185
+ kind: "code",
186
+ text: mapped`(${choice.index} >= 0)`,
187
+ declared: this.checker.getBooleanType(),
188
+ }
189
+ : constant(true);
190
+ }
191
+
192
+ /** `===` with a reference on either side compares ids; undefined when neither side is one. */
193
+ equality(
194
+ left: Value,
195
+ right: Value,
196
+ { negate }: { negate: boolean },
197
+ ): Value | undefined {
198
+ const [choice, other] =
199
+ left.kind === "choice" ? [left, right] : [right, left];
200
+ if (choice.kind !== "choice") {
201
+ return undefined;
202
+ }
203
+ const test = this.same(choice, other);
204
+ if (test === undefined) {
205
+ return undefined;
206
+ }
207
+ if (typeof test === "boolean") {
208
+ return constant(negate ? !test : test);
209
+ }
210
+ return {
211
+ kind: "code",
212
+ text: negate ? mapped`!${test}` : test,
213
+ declared: this.checker.getBooleanType(),
214
+ };
215
+ }
216
+
217
+ private same(choice: Choice, other: Value): boolean | Mapped | undefined {
218
+ switch (other.kind) {
219
+ case "choice":
220
+ return mapped`(${choice.index} === ${other.index})`;
221
+ case "static":
222
+ return choice.options.includes(other.node)
223
+ ? mapped`(${choice.index} === ${other.node.id})`
224
+ : false;
225
+ case "const":
226
+ return other.value === undefined && choice.optional
227
+ ? mapped`(${choice.index} < 0)`
228
+ : false;
229
+ case "code":
230
+ return undefined;
231
+ default:
232
+ return false;
233
+ }
234
+ }
235
+
236
+ /**
237
+ * Rejects `===` between two records the PLC holds as copied values: no identity survives the
238
+ * copy, and comparing their contents would answer a different question than TypeScript's.
239
+ */
240
+ identities(left: Value, right: Value, at: ts.Node): void {
241
+ if (this.copied(left) && this.copied(right)) {
242
+ throw new SpecializeError(
243
+ at,
244
+ "=== asks whether two records are the same object, which the PLC can't tell: it holds a record as a copied value. Compare a field that identifies them, such as a key or an id.",
245
+ );
246
+ }
247
+ }
248
+
249
+ private copied(value: Value): boolean {
250
+ if (value.kind === "virtual") {
251
+ return true;
252
+ }
253
+ return (
254
+ value.kind === "code" &&
255
+ value.declared !== undefined &&
256
+ Boolean(
257
+ this.checker.getNonNullableType(value.declared).flags &
258
+ ts.TypeFlags.Object,
259
+ )
260
+ );
261
+ }
262
+
263
+ /** A reference whose storage a later write could change, held in a const as it is now. */
264
+ held(choice: Choice, frame: Frame): Value {
265
+ if (!choice.place) {
266
+ return choice;
267
+ }
268
+ const local = frame.emitter.temporary();
269
+ frame.emitter.line(
270
+ mapped`const ${local}: ${referenceLayout} = ${choice.index};`,
271
+ );
272
+ return {
273
+ kind: "choice",
274
+ options: choice.options,
275
+ index: local,
276
+ optional: choice.optional,
277
+ };
278
+ }
279
+
280
+ /**
281
+ * What a local holding a reference is bound to: a let stores the id, so it can be assigned any
282
+ * object of its type, and a const keeps the choice it was given. Undefined for other locals.
283
+ */
284
+ local(
285
+ name: string,
286
+ value: Value,
287
+ declared: ts.Type,
288
+ frame: Frame,
289
+ { mutable }: { mutable: boolean },
290
+ ): Value | undefined {
291
+ // An array filtered at run time has no storage a let could hold: the name means the array.
292
+ if (value.kind === "masked") {
293
+ return value;
294
+ }
295
+ const index = referenceIndex(value);
296
+ if (!mutable) {
297
+ return value.kind === "choice" ? this.held(value, frame) : undefined;
298
+ }
299
+ const typed = referenceType(declared);
300
+ if (index === undefined || (value.kind !== "choice" && !typed)) {
301
+ return undefined;
302
+ }
303
+ const local = frame.emitter.local(name);
304
+ frame.emitter.line(mapped`let ${local}: ${referenceLayout} = ${index};`);
305
+ return {
306
+ kind: "choice",
307
+ options: typed
308
+ ? union([...this.candidates(declared), ...optionsOf(value)])
309
+ : optionsOf(value),
310
+ index: local,
311
+ optional: typed ? maybeAbsent(declared) : absentOf(value),
312
+ place: true,
313
+ };
314
+ }
315
+
316
+ /** `target = value` and `target ??= value` on a reference field or let. */
317
+ assign(target: Choice, node: ts.BinaryExpression, frame: Frame): Value {
318
+ if (!target.place) {
319
+ throw new SpecializeError(
320
+ node.left,
321
+ "Assign a reference to a field or a let; this name keeps the object it was given.",
322
+ );
323
+ }
324
+ const operator = node.operatorToken.kind;
325
+ const store = (): void => {
326
+ const value = this.expressions.expression(node.right, frame);
327
+ const index = referenceIndex(value);
328
+ if (
329
+ index === undefined ||
330
+ optionsOf(value).some((option) => !target.options.includes(option))
331
+ ) {
332
+ throw new SpecializeError(
333
+ node.right,
334
+ "Assign an object setup built that this reference can hold, or undefined.",
335
+ );
336
+ }
337
+ frame.emitter.line(
338
+ target.setter
339
+ ? mapped`${target.setter}(${index});`
340
+ : mapped`${target.index} = ${index};`,
341
+ );
342
+ };
343
+ if (operator === ts.SyntaxKind.EqualsToken) {
344
+ store();
345
+ return target;
346
+ }
347
+ if (operator === ts.SyntaxKind.QuestionQuestionEqualsToken) {
348
+ frame.emitter.open(mapped`if (${target.index} < 0) {`);
349
+ store();
350
+ frame.emitter.close();
351
+ return target;
352
+ }
353
+ throw new SpecializeError(
354
+ node,
355
+ `${node.operatorToken.getText()} is not supported on a reference.`,
356
+ );
357
+ }
358
+
359
+ /**
360
+ * The place an assignment's target names. A field reached through a reference chosen at run time
361
+ * is a different place in each object the reference can be, so the caller writes each.
362
+ */
363
+ target(node: ts.Expression, frame: Frame): Value | PlaceInEach {
364
+ const place = unparenthesized(node);
365
+ // Only an object of a class is reached by reference; `this` is the instance being specialized.
366
+ if (
367
+ !ts.isPropertyAccessExpression(place) ||
368
+ place.expression.kind === ts.SyntaxKind.ThisKeyword ||
369
+ place.expression.kind === ts.SyntaxKind.SuperKeyword ||
370
+ !referenceType(this.checker.getTypeAtLocation(place.expression))
371
+ ) {
372
+ return this.expressions.expression(node, frame);
373
+ }
374
+ const object = this.expressions.expression(place.expression, frame);
375
+ if (object.kind !== "choice") {
376
+ return this.expressions.property(object, place, frame);
377
+ }
378
+ return {
379
+ kind: "each",
380
+ choice: object,
381
+ place: (option) =>
382
+ this.expressions.property(
383
+ { kind: "static", node: option },
384
+ place,
385
+ frame,
386
+ ),
387
+ };
388
+ }
389
+
390
+ /** Runs `write` on the object a reference holds: a branch for each object it can be. */
391
+ each(choice: Choice, frame: Frame, write: (option: ModelNode) => void): void {
392
+ const arms = choice.options.map((option) => ({
393
+ option,
394
+ lines: frame.emitter.detached({ nested: true }, () => write(option))
395
+ .lines,
396
+ }));
397
+ chain(
398
+ frame,
399
+ arms
400
+ .filter((arm) => arm.lines.length > 0)
401
+ .map((arm) => ({
402
+ test: mapped`${choice.index} === ${arm.option.id}`,
403
+ body: () => frame.emitter.append(arm.lines),
404
+ })),
405
+ );
406
+ }
407
+
408
+ /** `object.name` through a reference: the member of whichever object it holds. */
409
+ member(choice: Choice, name: string, at: ts.Node, frame: Frame): Value {
410
+ const [sample] = choice.options;
411
+ return this.dispatch(
412
+ choice,
413
+ frame,
414
+ at,
415
+ sample && this.memberType(sample, name),
416
+ (option) =>
417
+ this.expressions.member(
418
+ { kind: "static", node: option },
419
+ name,
420
+ at,
421
+ frame,
422
+ ),
423
+ );
424
+ }
425
+
426
+ /** `array[index]` through a reference to one of several arrays. */
427
+ element(choice: Choice, index: Value, at: ts.Node, frame: Frame): Value {
428
+ return this.dispatch(choice, frame, at, undefined, (option) =>
429
+ this.expressions.element(
430
+ { kind: "static", node: option },
431
+ index,
432
+ at,
433
+ frame,
434
+ ),
435
+ );
436
+ }
437
+
438
+ /** The declared type of a member every object of a reference has, from one of them. */
439
+ private memberType(option: ModelNode, name: string): ts.Type | undefined {
440
+ if (option.captured.kind === "instance") {
441
+ const accessor = this.model
442
+ .members(this.model.classOf(option))
443
+ .find(
444
+ (member): member is ts.GetAccessorDeclaration =>
445
+ ts.isGetAccessorDeclaration(member) &&
446
+ member.name.getText() === name,
447
+ );
448
+ const signature =
449
+ accessor && this.checker.getSignatureFromDeclaration(accessor);
450
+ if (signature) {
451
+ return this.checker.getReturnTypeOfSignature(signature);
452
+ }
453
+ }
454
+ return option.captured.kind === "array"
455
+ ? undefined
456
+ : this.model.capturedFieldType(option, name);
457
+ }
458
+
459
+ /**
460
+ * A value read through a reference: each object's value is worked out in its own branch, so
461
+ * only the chosen object's code runs. The result is a reference again when every object gives
462
+ * one, and otherwise a local of the value's type.
463
+ */
464
+ private dispatch(
465
+ choice: Choice,
466
+ frame: Frame,
467
+ at: ts.Node,
468
+ type: ts.Type | undefined,
469
+ read: (option: ModelNode) => Value,
470
+ ): Value {
471
+ const arms = choice.options.map((option) => {
472
+ const { result, lines } = frame.emitter.detached({ nested: true }, () =>
473
+ read(option),
474
+ );
475
+ return { option, value: result, lines };
476
+ });
477
+ const [first] = arms;
478
+ if (!first) {
479
+ return constant(undefined);
480
+ }
481
+ const test = (option: ModelNode): Mapped =>
482
+ mapped`${choice.index} === ${option.id}`;
483
+ const known = first.value;
484
+ if (
485
+ known.kind === "const" &&
486
+ arms.every(
487
+ (arm) => arm.value.kind === "const" && arm.value.value === known.value,
488
+ )
489
+ ) {
490
+ chain(
491
+ frame,
492
+ arms
493
+ .filter((arm) => arm.lines.length > 0)
494
+ .map((arm) => ({
495
+ test: test(arm.option),
496
+ body: () => frame.emitter.append(arm.lines),
497
+ })),
498
+ );
499
+ return known;
500
+ }
501
+ const result = frame.emitter.temporary();
502
+ if (arms.every((arm) => referenceIndex(arm.value) !== undefined)) {
503
+ frame.emitter.line(`let ${result}: ${referenceLayout} = -1;`);
504
+ chain(
505
+ frame,
506
+ arms.map((arm) => ({
507
+ test: test(arm.option),
508
+ body: () => {
509
+ frame.emitter.append(arm.lines);
510
+ frame.emitter.line(
511
+ mapped`${result} = ${referenceIndex(arm.value) ?? "-1"};`,
512
+ );
513
+ },
514
+ })),
515
+ );
516
+ return settled({
517
+ kind: "choice",
518
+ options: union(arms.flatMap((arm) => optionsOf(arm.value))),
519
+ index: result,
520
+ optional: choice.optional || arms.some((arm) => absentOf(arm.value)),
521
+ });
522
+ }
523
+ const sample = arms
524
+ .map((arm) => arm.value)
525
+ .find((value) => value.kind === "code");
526
+ const declared =
527
+ type ??
528
+ (sample?.kind === "code" ? sample.declared : undefined) ??
529
+ (ts.isExpression(at) ? this.checker.getTypeAtLocation(at) : undefined);
530
+ if (
531
+ !declared ||
532
+ arms.some(
533
+ (arm) => arm.value.kind !== "const" && arm.value.kind !== "code",
534
+ )
535
+ ) {
536
+ throw new SpecializeError(
537
+ at,
538
+ "This can't be read through a reference chosen at run time: read a value, or call the method where it is named.",
539
+ );
540
+ }
541
+ const iec = sample?.kind === "code" ? sample.iec : undefined;
542
+ const layout = sample?.kind === "code" ? sample.layout : undefined;
543
+ const text = iec ?? layout ?? this.expressions.localType(declared);
544
+ frame.emitter.line(
545
+ `let ${result}: ${text} = ${iec || layout ? `defaultValue<${text}>()` : this.initializers.defaultOf(declared)};`,
546
+ );
547
+ chain(
548
+ frame,
549
+ arms.map((arm) => ({
550
+ test: test(arm.option),
551
+ body: () => {
552
+ frame.emitter.append(arm.lines);
553
+ frame.emitter.line(
554
+ mapped`${result} = ${this.dialect.assignmentText(arm.value, declared, iec)};`,
555
+ );
556
+ },
557
+ })),
558
+ );
559
+ // A copy of what the chosen object holds: writing it would change no object, so it is no place.
560
+ return {
561
+ kind: "code",
562
+ text: result,
563
+ declared,
564
+ ...(iec && { iec }),
565
+ ...(layout && { layout }),
566
+ ...(sample?.kind === "code" &&
567
+ sample.length !== undefined && { length: sample.length }),
568
+ };
569
+ }
570
+
571
+ /** The reference a routine call returns, held in a const: the call runs once however often the reference is read. */
572
+ result(
573
+ call: Mapped,
574
+ referents: { options: readonly ModelNode[]; optional: boolean } | undefined,
575
+ returns: ts.Type,
576
+ frame: Frame,
577
+ ): Value {
578
+ const local = frame.emitter.temporary();
579
+ frame.emitter.line(mapped`const ${local}: ${referenceLayout} = ${call};`);
580
+ // A routine still being specialized, as one that calls itself, has not said what it returns.
581
+ return settled({
582
+ kind: "choice",
583
+ options: referents ? union(referents.options) : this.candidates(returns),
584
+ index: local,
585
+ optional: referents ? referents.optional : maybeAbsent(returns),
586
+ });
587
+ }
588
+
589
+ /** Notes what a return statement returns, in a routine whose result is a reference. */
590
+ returned(value: Value, at: ts.Node, frame: Frame): void {
591
+ const referents = frame.referents;
592
+ if (!referents) {
593
+ return;
594
+ }
595
+ if (referenceIndex(value) === undefined) {
596
+ throw new SpecializeError(
597
+ at,
598
+ "Return an object setup built, or undefined: the routine's result is a reference.",
599
+ );
600
+ }
601
+ for (const option of optionsOf(value)) {
602
+ referents.options.add(option);
603
+ }
604
+ referents.optional ||= absentOf(value);
605
+ }
606
+
607
+ /**
608
+ * `condition ? yes : no` between references. Each side is worked out in its own branch, so a
609
+ * call that chooses one runs only when its side is taken.
610
+ */
611
+ branch(
612
+ condition: Part,
613
+ sides: readonly [() => Value, () => Value],
614
+ at: ts.Node,
615
+ frame: Frame,
616
+ ): Value {
617
+ const result = frame.emitter.temporary();
618
+ frame.emitter.line(`let ${result}: ${referenceLayout} = -1;`);
619
+ const store = (side: () => Value): Value => {
620
+ const value = side();
621
+ frame.emitter.line(mapped`${result} = ${this.index(value, at)};`);
622
+ return value;
623
+ };
624
+ frame.emitter.open(mapped`if (${condition}) {`);
625
+ const yes = store(sides[0]);
626
+ frame.emitter.reopen("} else {");
627
+ const no = store(sides[1]);
628
+ frame.emitter.close();
629
+ return settled({
630
+ kind: "choice",
631
+ options: union([...optionsOf(yes), ...optionsOf(no)]),
632
+ index: result,
633
+ optional: absentOf(yes) || absentOf(no),
634
+ });
635
+ }
636
+
637
+ /** `reference ?? other` and `reference || other`: the other side is worked out only when the reference is undefined. */
638
+ fallback(left: Choice, right: () => Value, at: ts.Node, frame: Frame): Value {
639
+ if (!left.optional) {
640
+ return left;
641
+ }
642
+ const result = frame.emitter.temporary();
643
+ frame.emitter.line(
644
+ mapped`let ${result}: ${referenceLayout} = ${left.index};`,
645
+ );
646
+ frame.emitter.open(`if (${result} < 0) {`);
647
+ const value = right();
648
+ frame.emitter.line(mapped`${result} = ${this.index(value, at)};`);
649
+ frame.emitter.close();
650
+ return settled({
651
+ kind: "choice",
652
+ options: union([...left.options, ...optionsOf(value)]),
653
+ index: result,
654
+ optional: absentOf(value),
655
+ });
656
+ }
657
+
658
+ private index(value: Value, at: ts.Node): string | Mapped {
659
+ const index = referenceIndex(value);
660
+ if (index === undefined) {
661
+ throw new SpecializeError(
662
+ at,
663
+ "Only an object setup built, or undefined, can be chosen here.",
664
+ );
665
+ }
666
+ return index;
667
+ }
668
+
669
+ /**
670
+ * A call on a reference chosen at run time, or on an array whose elements scan code picks from:
671
+ * a method call through the reference, or an array method that picks an object or keeps some.
672
+ * Undefined for a call setup decides, which unrolls as any other.
673
+ */
674
+ call(
675
+ name: string,
676
+ receiver: Value,
677
+ items: readonly Value[] | undefined,
678
+ node: ts.CallExpression,
679
+ frame: Frame,
680
+ expected: ts.Type | undefined,
681
+ ): Value | undefined {
682
+ return receiver.kind === "choice"
683
+ ? this.method(receiver, name, node, frame, expected)
684
+ : this.expressions.filteredArrays.call(
685
+ name,
686
+ receiver,
687
+ items,
688
+ node,
689
+ frame,
690
+ );
691
+ }
692
+
693
+ /** A method call through a reference: the method of whichever object it holds, the arguments worked out once. */
694
+ private method(
695
+ choice: Choice,
696
+ name: string,
697
+ node: ts.CallExpression,
698
+ frame: Frame,
699
+ expected: ts.Type | undefined,
700
+ ): Value {
701
+ const [sample] = choice.options;
702
+ const declaration =
703
+ sample?.captured.kind === "instance"
704
+ ? this.model
705
+ .members(this.model.classOf(sample))
706
+ .find(
707
+ (member): member is ts.MethodDeclaration =>
708
+ ts.isMethodDeclaration(member) &&
709
+ member.name.getText() === name,
710
+ )
711
+ : undefined;
712
+ const args = this.expressions.inOrder(
713
+ node.arguments,
714
+ (argument, index) => {
715
+ const parameter = declaration?.parameters[index];
716
+ return this.expressions.expression(
717
+ argument,
718
+ frame,
719
+ parameter && this.checker.getTypeAtLocation(parameter),
720
+ );
721
+ },
722
+ frame,
723
+ );
724
+ return this.dispatch(choice, frame, node, undefined, (option) => {
725
+ const method = this.expressions.member(
726
+ { kind: "static", node: option },
727
+ name,
728
+ node.expression,
729
+ frame,
730
+ );
731
+ const result = this.expressions.invoke(
732
+ method,
733
+ args,
734
+ node,
735
+ frame,
736
+ expected,
737
+ );
738
+ // A call for its effect alone is a statement of its branch.
739
+ if (
740
+ result.kind === "code" &&
741
+ (!result.declared || result.declared.flags & ts.TypeFlags.Void)
742
+ ) {
743
+ frame.emitter.line(mapped`${result.text};`);
744
+ return constant(undefined);
745
+ }
746
+ return result;
747
+ });
748
+ }
749
+ }