@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
@@ -8,11 +8,14 @@ import {
8
8
  type RoutineTable,
9
9
  type SpecializeContext,
10
10
  } from "./expressions";
11
- import { Emitter, type Frame } from "./frame";
11
+ import { Emitter, type Frame, type Referents } from "./frame";
12
+ import type { GenericTypes } from "./generics";
12
13
  import { EntryImports } from "./imports";
13
14
  import { Initializers } from "./initializers";
15
+ import { countedKey } from "./iterators";
14
16
  import { Layouts, unusedName } from "./layouts";
15
17
  import { type Model, type ModelNode, type Root, tsPath } from "./model";
18
+ import { referenceLayout, referenceType } from "./references";
16
19
  import { StatementSpecializer } from "./statements";
17
20
  import { Storage } from "./storage";
18
21
  import {
@@ -22,6 +25,7 @@ import {
22
25
  SpecializeError,
23
26
  type Value,
24
27
  } from "./values";
28
+ import { assignsSymbol } from "./writes";
25
29
 
26
30
  /**
27
31
  * Evaluates the program's scan code against the setup graph. Everything setup decided (which
@@ -41,16 +45,29 @@ export class Specializer implements RoutineTable {
41
45
  /** Routines specialized from a class method, by routine name: `Class.method` and the TypeScript path of `this`. */
42
46
  readonly origins = new Map<string, { name: string; instance?: string }>();
43
47
  private readonly specialized = new Map<string, string>();
48
+ /** Routines that return stored state, whose callers get a copy. */
49
+ private readonly returnsStored = new Set<string>();
50
+ /** Each specialized routine's array result layout, by routine name. */
51
+ private readonly resultLayouts = new Map<
52
+ string,
53
+ { layout: string; length: number | undefined }
54
+ >();
44
55
  private readonly routineNames = new Set<string>();
56
+ /** What each finished routine whose result is a reference returns, by routine name. */
57
+ private readonly referents = new Map<string, Referents>();
58
+
59
+ readonly checker: ts.TypeChecker;
45
60
 
46
61
  constructor(
47
62
  readonly model: Model,
48
- readonly checker: ts.TypeChecker,
63
+ private readonly generics: GenericTypes,
49
64
  readonly sdkFile: string,
50
65
  readonly sources: readonly ts.SourceFile[],
51
66
  readonly kept: (file: string) => boolean,
52
67
  readonly rootModule: (root: Root) => string,
53
68
  ) {
69
+ const checker = generics.checker;
70
+ this.checker = checker;
54
71
  this.layouts = new Layouts(
55
72
  model,
56
73
  checker,
@@ -66,6 +83,7 @@ export class Specializer implements RoutineTable {
66
83
  kept,
67
84
  rootModule,
68
85
  );
86
+ this.layouts.instanceState = (node) => this.storage.storageType(node);
69
87
  this.initializers = new Initializers(
70
88
  model,
71
89
  checker,
@@ -95,6 +113,11 @@ export class Specializer implements RoutineTable {
95
113
  this.statements = new StatementSpecializer(context, this.expressions);
96
114
  }
97
115
 
116
+ /** Statements that couldn't be specialized, for the build to report together. */
117
+ get failures(): readonly SpecializeError[] {
118
+ return this.statements.failures;
119
+ }
120
+
98
121
  /** Specializes the entry function, returning its body. */
99
122
  entry(declaration: ts.FunctionDeclaration | ts.ArrowFunction): Mapped[] {
100
123
  const frame: Frame = {
@@ -113,6 +136,20 @@ export class Specializer implements RoutineTable {
113
136
  self: ModelNode | undefined,
114
137
  args: Value[],
115
138
  closure?: Env,
139
+ ): RoutineCall {
140
+ // A generic class's method specializes with its instance's type arguments in scope.
141
+ const owner =
142
+ self?.captured.kind === "instance" ? this.model.classOf(self) : undefined;
143
+ return this.generics.within(owner, self?.type, () =>
144
+ this.specializeRoutine(declaration, self, args, closure),
145
+ );
146
+ }
147
+
148
+ private specializeRoutine(
149
+ declaration: FunctionLike,
150
+ self: ModelNode | undefined,
151
+ args: Value[],
152
+ closure?: Env,
116
153
  ): RoutineCall {
117
154
  const signature = this.checker.getSignatureFromDeclaration(declaration);
118
155
  const returnType =
@@ -131,6 +168,10 @@ export class Specializer implements RoutineTable {
131
168
  returnType &&
132
169
  (isAsync ? this.checker.getAwaitedType(returnType) : returnType),
133
170
  async: isAsync,
171
+ ...(returnType &&
172
+ referenceType(returnType) && {
173
+ referents: { options: new Set<ModelNode>(), optional: false },
174
+ }),
134
175
  };
135
176
  const parameters: string[] = [];
136
177
  const runtimeArgs: (string | Mapped)[] = [];
@@ -139,8 +180,31 @@ export class Specializer implements RoutineTable {
139
180
  ? []
140
181
  : declaration.parameters;
141
182
  parameterList.forEach((parameter, index) => {
142
- const arg = args[index] ?? constant(undefined);
143
183
  const declared = this.checker.getTypeAtLocation(parameter);
184
+ if (parameter.dotDotDotToken) {
185
+ this.bindRest(
186
+ parameter,
187
+ args.slice(index),
188
+ declared,
189
+ frame,
190
+ parameters,
191
+ runtimeArgs,
192
+ keys,
193
+ );
194
+ return;
195
+ }
196
+ const arg = args[index] ?? constant(undefined);
197
+ if (parameter.initializer && this.isUndefined(arg, parameter)) {
198
+ this.bindDefault(
199
+ parameter,
200
+ declared,
201
+ frame,
202
+ parameters,
203
+ runtimeArgs,
204
+ keys,
205
+ );
206
+ return;
207
+ }
144
208
  this.bindParameter(
145
209
  parameter.name,
146
210
  arg,
@@ -151,28 +215,67 @@ export class Specializer implements RoutineTable {
151
215
  keys,
152
216
  );
153
217
  });
154
- // Captured runtime locals become parameters of the specialized routine.
218
+ // Captured runtime locals the routine reads become its parameters; one it writes is borrowed.
219
+ const read = readSymbols(declaration, this.checker);
155
220
  for (const [symbol, value] of closure ?? []) {
221
+ if (!read.has(symbol)) {
222
+ continue;
223
+ }
156
224
  if (value.kind === "code") {
157
225
  const name = frame.emitter.local(symbol.name);
158
- const type = value.declared
159
- ? this.layouts.text(value.declared)
160
- : "number";
161
- parameters.push(`${name}: ${type}`);
162
- runtimeArgs.push(value.text);
226
+ const type =
227
+ value.iec ??
228
+ (value.declared ? this.layouts.text(value.declared) : "number");
229
+ const borrowed =
230
+ value.place &&
231
+ declaration.body !== undefined &&
232
+ assignsSymbol(declaration.body, new Set([symbol]), this.checker);
233
+ if (borrowed) {
234
+ this.imports.addSdk("@tsplc/compiler/types", "ref");
235
+ }
236
+ parameters.push(`${name}: ${borrowed ? `InOut<${type}>` : type}`);
237
+ runtimeArgs.push(borrowed ? mapped`ref(${value.text})` : value.text);
163
238
  frame.env.set(symbol, {
164
239
  kind: "code",
165
240
  text: name,
166
241
  declared: value.declared,
167
242
  place: true,
243
+ iec: value.iec,
168
244
  });
169
- keys.push(`${symbol.name}=code`);
245
+ keys.push(`${symbol.name}=${borrowed ? "ref" : "code"}`);
246
+ } else if (
247
+ value.kind === "choice" ||
248
+ value.kind === "masked" ||
249
+ value.kind === "counted"
250
+ ) {
251
+ // A captured reference is the caller's too: its run-time id is passed as a local's value is.
252
+ const passed = this.lifted(
253
+ value,
254
+ symbol.name,
255
+ frame,
256
+ parameters,
257
+ runtimeArgs,
258
+ );
259
+ frame.env.set(symbol, passed);
260
+ keys.push(`${symbol.name}=${valueKey(passed)}`);
261
+ } else {
262
+ // A value setup fixed specializes the routine, as a known argument does.
263
+ keys.push(`${symbol.name}=${valueKey(value)}`);
170
264
  }
171
265
  }
172
266
  const key = `${declarationKey(declaration)}|${self?.id ?? ""}|${keys.join(",")}`;
173
267
  const known = this.specialized.get(key);
174
268
  if (known) {
175
- return { name: known, args: runtimeArgs, returns: frame.returns };
269
+ return {
270
+ name: known,
271
+ args: runtimeArgs,
272
+ returns: frame.returns,
273
+ iec: this.layouts.iecName(declaration),
274
+ layout: this.resultLayouts.get(known)?.layout,
275
+ length: this.resultLayouts.get(known)?.length,
276
+ returnsStored: this.returnsStored.has(known),
277
+ referents: this.resultReferents(known),
278
+ };
176
279
  }
177
280
  const name = this.routineName(declaration, self);
178
281
  this.specialized.set(key, name);
@@ -183,16 +286,32 @@ export class Specializer implements RoutineTable {
183
286
  frame,
184
287
  frame.returns,
185
288
  );
186
- frame.emitter.line(
187
- mapped`return ${this.dialect.code(result, frame.returns)};`,
188
- );
289
+ this.expressions.references.returned(result, declaration.body, frame);
290
+ // A void arrow's expression runs for its effect.
291
+ if (!frame.returns || frame.returns.flags & ts.TypeFlags.Void) {
292
+ if (result.kind === "code") {
293
+ frame.emitter.line(mapped`${result.text};`);
294
+ }
295
+ } else {
296
+ frame.emitter.line(
297
+ mapped`return ${this.dialect.code(result, frame.returns)};`,
298
+ );
299
+ }
189
300
  } else {
190
301
  this.statements.body(declaration.body!, frame);
191
302
  }
303
+ // An IEC width the declaration names, as `(): UINT` does, is the result's type.
192
304
  const resultText =
193
305
  frame.returns && !(frame.returns.flags & ts.TypeFlags.Void)
194
- ? this.layouts.text(frame.returns)
306
+ ? (frame.resultLayout ??
307
+ this.layouts.iecName(declaration) ??
308
+ (frame.referents
309
+ ? referenceLayout
310
+ : this.layouts.text(frame.returns)))
195
311
  : "void";
312
+ if (frame.referents) {
313
+ this.referents.set(name, frame.referents);
314
+ }
196
315
  const head = `${frame.async ? "async " : ""}function ${name}(${parameters.join(", ")}): ${
197
316
  frame.async ? `Promise<${resultText}>` : resultText
198
317
  } {`;
@@ -217,7 +336,37 @@ export class Specializer implements RoutineTable {
217
336
  "\n",
218
337
  ),
219
338
  );
220
- return { name, args: runtimeArgs, returns: frame.returns };
339
+ if (frame.returnsStored) {
340
+ this.returnsStored.add(name);
341
+ }
342
+ if (frame.resultLayout) {
343
+ this.resultLayouts.set(name, {
344
+ layout: frame.resultLayout,
345
+ length: frame.resultLength,
346
+ });
347
+ }
348
+ return {
349
+ name,
350
+ args: runtimeArgs,
351
+ returns: frame.returns,
352
+ iec: this.layouts.iecName(declaration),
353
+ layout: frame.resultLayout,
354
+ length: frame.resultLength,
355
+ returnsStored: frame.returnsStored,
356
+ referents: this.resultReferents(name),
357
+ };
358
+ }
359
+
360
+ private resultReferents(
361
+ name: string,
362
+ ): { options: ModelNode[]; optional: boolean } | undefined {
363
+ const referents = this.referents.get(name);
364
+ return (
365
+ referents && {
366
+ options: [...referents.options],
367
+ optional: referents.optional,
368
+ }
369
+ );
221
370
  }
222
371
 
223
372
  private routineName(
@@ -273,10 +422,27 @@ export class Specializer implements RoutineTable {
273
422
  return;
274
423
  }
275
424
  if (ts.isArrayBindingPattern(name)) {
276
- throw new SpecializeError(
277
- name,
278
- "Array patterns are not supported in parameters.",
279
- );
425
+ name.elements.forEach((element, index) => {
426
+ if (ts.isOmittedExpression(element)) {
427
+ return;
428
+ }
429
+ if (element.dotDotDotToken) {
430
+ throw new SpecializeError(
431
+ element,
432
+ "Name each element of an array parameter; a rest element has no length here.",
433
+ );
434
+ }
435
+ this.bindParameter(
436
+ element.name,
437
+ this.expressions.element(arg, constant(index), element, frame),
438
+ this.checker.getTypeAtLocation(element),
439
+ frame,
440
+ parameters,
441
+ runtimeArgs,
442
+ keys,
443
+ );
444
+ });
445
+ return;
280
446
  }
281
447
  const symbol = this.checker.getSymbolAtLocation(name)!;
282
448
  if (
@@ -284,9 +450,21 @@ export class Specializer implements RoutineTable {
284
450
  (arg.kind === "virtual" && !this.isKnownShape(arg))
285
451
  ) {
286
452
  const local = frame.emitter.local(name.text);
287
- const iec = this.layouts.iecName(name.parent);
288
- // An array parameter takes the length of the storage passed to it, which its type doesn't name.
289
- const layout = arg.kind === "code" ? arg.layout : undefined;
453
+ // A name destructured from a field keeps that field's width.
454
+ const iec =
455
+ this.layouts.iecName(name.parent) ??
456
+ (arg.kind === "code" ? arg.iec : undefined);
457
+ // An array parameter takes the length of the storage or literal passed to it, which its type doesn't name.
458
+ const element = this.checker.getIndexTypeOfType(
459
+ declared,
460
+ ts.IndexKind.Number,
461
+ );
462
+ const layout =
463
+ arg.kind === "code"
464
+ ? arg.layout
465
+ : arg.items && element
466
+ ? `FixedArray<${this.layouts.text(element)}, ${Math.max(arg.items.length, 1)}>`
467
+ : undefined;
290
468
  parameters.push(
291
469
  `${local}: ${iec ?? layout ?? this.layouts.text(declared)}`,
292
470
  );
@@ -297,6 +475,8 @@ export class Specializer implements RoutineTable {
297
475
  declared,
298
476
  place: true,
299
477
  layout,
478
+ // A copy of stored state stays one in the routine it is passed to.
479
+ copyOf: arg.kind === "code" ? arg.copyOf : undefined,
300
480
  });
301
481
  keys.push(`${name.text}=code${layout ? `:${layout}` : ""}`);
302
482
  return;
@@ -319,16 +499,241 @@ export class Specializer implements RoutineTable {
319
499
  keys.push(`${name.text}=code`);
320
500
  return;
321
501
  }
322
- frame.env.set(symbol, arg);
323
- keys.push(`${name.text}=${valueKey(arg)}`);
502
+ const lifted = this.lifted(arg, name.text, frame, parameters, runtimeArgs);
503
+ frame.env.set(symbol, lifted);
504
+ keys.push(`${name.text}=${valueKey(lifted)}`);
324
505
  }
325
506
 
507
+ /**
508
+ * A literal argument that holds objects setup built is known to the routine, but a runtime value
509
+ * inside it is the caller's: each becomes a parameter of its own, which the caller passes.
510
+ */
511
+ private lifted(
512
+ value: Value,
513
+ base: string,
514
+ frame: Frame,
515
+ parameters: string[],
516
+ runtimeArgs: (string | Mapped)[],
517
+ ): Value {
518
+ if (value.kind === "counted") {
519
+ return this.expressions.iterators.lifted(
520
+ value,
521
+ base,
522
+ frame,
523
+ parameters,
524
+ runtimeArgs,
525
+ (part, name) => this.lifted(part, name, frame, parameters, runtimeArgs),
526
+ );
527
+ }
528
+ // A reference chosen at run time passes its id; the routine specializes on what it can be.
529
+ if (value.kind === "choice") {
530
+ const local = frame.emitter.local(base);
531
+ parameters.push(`${local}: ${referenceLayout}`);
532
+ runtimeArgs.push(value.index);
533
+ return {
534
+ kind: "choice",
535
+ options: value.options,
536
+ index: local,
537
+ optional: value.optional,
538
+ };
539
+ }
540
+ if (value.kind === "masked") {
541
+ return {
542
+ ...value,
543
+ entries: value.entries.map((entry, index) => ({
544
+ item: this.lifted(
545
+ entry.item,
546
+ `${base}_${index}`,
547
+ frame,
548
+ parameters,
549
+ runtimeArgs,
550
+ ),
551
+ present: this.lifted(
552
+ entry.present,
553
+ `${base}_${index}_present`,
554
+ frame,
555
+ parameters,
556
+ runtimeArgs,
557
+ ),
558
+ })),
559
+ };
560
+ }
561
+ if (value.kind === "code") {
562
+ const local = frame.emitter.local(base);
563
+ parameters.push(
564
+ `${local}: ${value.iec ?? (value.declared ? this.layouts.text(value.declared) : "number")}`,
565
+ );
566
+ runtimeArgs.push(value.text);
567
+ return {
568
+ kind: "code",
569
+ text: local,
570
+ declared: value.declared,
571
+ place: true,
572
+ iec: value.iec,
573
+ };
574
+ }
575
+ // A callback passed in carries what it captured from the caller: runtime values among them are passed too.
576
+ if (value.kind === "function" && value.env) {
577
+ const read = readSymbols(value.declaration, this.checker);
578
+ return {
579
+ ...value,
580
+ env: new Map(
581
+ [...value.env]
582
+ .filter(([symbol]) => read.has(symbol))
583
+ .map(([symbol, captured]) => [
584
+ symbol,
585
+ this.lifted(
586
+ captured,
587
+ `${base}_${symbol.name}`,
588
+ frame,
589
+ parameters,
590
+ runtimeArgs,
591
+ ),
592
+ ]),
593
+ ),
594
+ };
595
+ }
596
+ if (value.kind !== "virtual") {
597
+ return value;
598
+ }
599
+ return {
600
+ ...value,
601
+ ...(value.items && {
602
+ items: value.items.map((item, index) =>
603
+ this.lifted(item, `${base}_${index}`, frame, parameters, runtimeArgs),
604
+ ),
605
+ }),
606
+ ...(value.fields && {
607
+ fields: new Map(
608
+ [...value.fields].map(([field, item]) => [
609
+ field,
610
+ this.lifted(
611
+ item,
612
+ `${base}_${field}`,
613
+ frame,
614
+ parameters,
615
+ runtimeArgs,
616
+ ),
617
+ ]),
618
+ ),
619
+ }),
620
+ };
621
+ }
622
+
623
+ /**
624
+ * A missing argument, or one passed as undefined, takes the parameter's default. A default setup
625
+ * fixes is a known argument like any other; one read from scan state or an earlier parameter is
626
+ * worked out when the routine starts, as JavaScript does.
627
+ */
628
+ private isUndefined(arg: Value, parameter: ts.ParameterDeclaration): boolean {
629
+ if (arg.kind === "const") {
630
+ return arg.value === undefined;
631
+ }
632
+ if (
633
+ arg.kind === "code" &&
634
+ arg.declared &&
635
+ arg.declared.flags & ts.TypeFlags.Union
636
+ ) {
637
+ if (this.checker.getNonNullableType(arg.declared) !== arg.declared) {
638
+ throw new SpecializeError(
639
+ parameter,
640
+ "Pass a defined value or leave the argument out: the default applies to a missing argument.",
641
+ );
642
+ }
643
+ }
644
+ return false;
645
+ }
646
+
647
+ private bindDefault(
648
+ parameter: ts.ParameterDeclaration,
649
+ declared: ts.Type,
650
+ frame: Frame,
651
+ parameters: string[],
652
+ runtimeArgs: (string | Mapped)[],
653
+ keys: string[],
654
+ ): void {
655
+ const value = this.expressions.expression(
656
+ parameter.initializer!,
657
+ frame,
658
+ declared,
659
+ );
660
+ // A default read at run time is a local; one known now, such as `[]`, is that value.
661
+ if (value.kind !== "const") {
662
+ this.expressions.bind(
663
+ parameter.name,
664
+ value,
665
+ value.kind === "code",
666
+ frame,
667
+ declared,
668
+ );
669
+ keys.push(`${parameter.name.getText()}=default`);
670
+ return;
671
+ }
672
+ this.bindParameter(
673
+ parameter.name,
674
+ value,
675
+ declared,
676
+ frame,
677
+ parameters,
678
+ runtimeArgs,
679
+ keys,
680
+ );
681
+ }
682
+
683
+ /** A rest parameter is the call's remaining arguments, each a parameter of its own when it is a runtime value. */
684
+ private bindRest(
685
+ parameter: ts.ParameterDeclaration,
686
+ args: readonly Value[],
687
+ declared: ts.Type,
688
+ frame: Frame,
689
+ parameters: string[],
690
+ runtimeArgs: (string | Mapped)[],
691
+ keys: string[],
692
+ ): void {
693
+ if (!ts.isIdentifier(parameter.name)) {
694
+ throw new SpecializeError(
695
+ parameter.name,
696
+ "Name the rest parameter; destructure it in the body.",
697
+ );
698
+ }
699
+ const element =
700
+ this.checker.getIndexTypeOfType(declared, ts.IndexKind.Number) ??
701
+ this.checker.getAnyType();
702
+ const name = parameter.name.text;
703
+ const items = args.map((arg, index): Value => {
704
+ if (arg.kind !== "code" && arg.kind !== "const") {
705
+ keys.push(`${name}[${index}]=${valueKey(arg)}`);
706
+ return arg;
707
+ }
708
+ const local = frame.emitter.local(`${name}_${index}`);
709
+ const iec = arg.kind === "code" ? arg.iec : undefined;
710
+ parameters.push(`${local}: ${iec ?? this.layouts.text(element)}`);
711
+ runtimeArgs.push(this.dialect.assignmentText(arg, element, iec));
712
+ keys.push(`${name}[${index}]=code`);
713
+ return { kind: "code", text: local, declared: element, place: true, iec };
714
+ });
715
+ frame.env.set(this.checker.getSymbolAtLocation(parameter.name)!, {
716
+ kind: "virtual",
717
+ items,
718
+ });
719
+ }
720
+
721
+ /** A literal holding objects setup built, or only values known now: an argument the routine specializes on. */
326
722
  private isKnownShape(value: Value): boolean {
723
+ if (value.kind !== "virtual") {
724
+ return false;
725
+ }
726
+ const inner = [...(value.fields?.values() ?? []), ...(value.items ?? [])];
327
727
  return (
328
- value.kind === "virtual" &&
329
- [...(value.fields?.values() ?? []), ...(value.items ?? [])].some(
330
- (inner) => inner.kind === "static" || inner.kind === "function",
331
- )
728
+ inner.some(
729
+ (item) =>
730
+ item.kind === "static" ||
731
+ item.kind === "function" ||
732
+ item.kind === "choice" ||
733
+ this.isKnownShape(item),
734
+ ) ||
735
+ (value.items !== undefined &&
736
+ inner.every((item) => item.kind === "const"))
332
737
  );
333
738
  }
334
739
  }
@@ -356,5 +761,30 @@ const valueKey = (value: Value): string => {
356
761
  : `{${[...(value.fields ?? [])].map(([name, inner]) => `${name}:${valueKey(inner)}`).join(",")}}`;
357
762
  case "code":
358
763
  return "code";
764
+ case "choice":
765
+ return `ref(${value.options.map((option) => option.id).join(",")})${value.optional ? "?" : ""}`;
766
+ case "masked":
767
+ return `some[${value.entries.map((entry) => `${valueKey(entry.item)}:${valueKey(entry.present)}`).join(",")}]${value.order ? `by ${valueKey(value.order)}` : ""}`;
768
+ case "counted":
769
+ return countedKey(value, valueKey);
359
770
  }
360
771
  };
772
+
773
+ /** The symbols a function's body reads, which are all of its closure it needs. */
774
+ const readSymbols = (
775
+ declaration: ts.Node,
776
+ checker: ts.TypeChecker,
777
+ ): ReadonlySet<ts.Symbol> => {
778
+ const read = new Set<ts.Symbol>();
779
+ const visit = (node: ts.Node): void => {
780
+ if (ts.isIdentifier(node)) {
781
+ const symbol = checker.getSymbolAtLocation(node);
782
+ if (symbol) {
783
+ read.add(symbol);
784
+ }
785
+ }
786
+ ts.forEachChild(node, visit);
787
+ };
788
+ visit(declaration);
789
+ return read;
790
+ };