@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
@@ -9,11 +9,12 @@ import {
9
9
  type Part,
10
10
  } from "../positions";
11
11
  import { declaredBySdk, inSdk, sdkModule, symbolAt } from "../sdk";
12
+ import { ArraySearches } from "./array-searches";
12
13
  import type { DialectText } from "./dialect";
13
14
  import type { ExpressionSpecializer, SpecializeContext } from "./expressions";
14
15
  import type { Frame } from "./frame";
15
16
  import type { EntryImports } from "./imports";
16
- import type { Model } from "./model";
17
+ import type { Model, ModelNode } from "./model";
17
18
  import type { Storage } from "./storage";
18
19
  import {
19
20
  constant,
@@ -33,10 +34,13 @@ export class CallSpecializer {
33
34
  private readonly sdkFile: string;
34
35
  private readonly sources: readonly ts.SourceFile[];
35
36
 
37
+ private readonly searches: ArraySearches;
38
+
36
39
  constructor(
37
40
  context: SpecializeContext,
38
41
  private readonly expressions: ExpressionSpecializer,
39
42
  ) {
43
+ this.searches = new ArraySearches(context, expressions);
40
44
  this.model = context.model;
41
45
  this.checker = context.checker;
42
46
  this.dialect = context.dialect;
@@ -54,6 +58,27 @@ export class CallSpecializer {
54
58
  ts.isPropertyAccessChain(callee)
55
59
  ) {
56
60
  const name = callee.name.text;
61
+ if (
62
+ ts.isIdentifier(callee.expression) &&
63
+ callee.expression.text === "Array" &&
64
+ name === "from"
65
+ ) {
66
+ return this.arrayFrom(node, frame);
67
+ }
68
+ if (callee.expression.kind === ts.SyntaxKind.SuperKeyword) {
69
+ const method = this.expressions.superMember(callee, frame);
70
+ return this.expressions.invoke(
71
+ method,
72
+ this.expressions.inOrder(
73
+ node.arguments,
74
+ (argument, index) => this.argument(argument, method, index, frame),
75
+ frame,
76
+ ),
77
+ node,
78
+ frame,
79
+ expected,
80
+ );
81
+ }
57
82
  if (
58
83
  ts.isIdentifier(callee.expression) &&
59
84
  callee.expression.text === "Math"
@@ -94,10 +119,29 @@ export class CallSpecializer {
94
119
  declared: this.checker.getTypeAtLocation(node),
95
120
  };
96
121
  }
122
+ const iterated = this.expressions.iterators.call(node, frame);
123
+ if (iterated) {
124
+ return iterated;
125
+ }
97
126
  const receiver = this.expressions.expression(callee.expression, frame);
127
+ const counted = this.expressions.iterators.receiver(receiver, name);
128
+ if (counted) {
129
+ return this.expressions.iterators.method(name, counted, node, frame);
130
+ }
98
131
  const items = this.expressions.items(receiver);
132
+ const referred = this.expressions.references.call(
133
+ name,
134
+ receiver,
135
+ items,
136
+ node,
137
+ frame,
138
+ expected,
139
+ );
140
+ if (referred) {
141
+ return referred;
142
+ }
99
143
  if (items && arrayMethods.has(name)) {
100
- return this.arrayMethod(name, items, node, frame);
144
+ return this.arrayMethod(name, receiver, items, node, frame);
101
145
  }
102
146
  if (
103
147
  receiver.kind === "static" &&
@@ -114,14 +158,19 @@ export class CallSpecializer {
114
158
  }
115
159
  return this.expressions.invoke(
116
160
  method,
117
- node.arguments.map((argument, index) =>
118
- this.argument(argument, method, index, frame),
161
+ this.expressions.inOrder(
162
+ node.arguments,
163
+ (argument, index) => this.argument(argument, method, index, frame),
164
+ frame,
119
165
  ),
120
166
  node,
121
167
  frame,
122
168
  expected,
123
169
  );
124
170
  }
171
+ if (ts.isIdentifier(callee) && callee.text === "structuredClone") {
172
+ return this.cloned(node, frame);
173
+ }
125
174
  const target = this.expressions.expression(callee, frame);
126
175
  if (target.kind === "static" && target.node.captured.kind === "service") {
127
176
  return this.serviceCall(target.node.captured.path, node, frame);
@@ -133,13 +182,16 @@ export class CallSpecializer {
133
182
  );
134
183
  return this.expressions.invoke(
135
184
  { kind: "function", declaration: fn },
136
- node.arguments.map((argument, index) =>
137
- this.argument(
138
- argument,
139
- { kind: "function", declaration: fn },
140
- index,
141
- frame,
142
- ),
185
+ this.expressions.inOrder(
186
+ node.arguments,
187
+ (argument, index) =>
188
+ this.argument(
189
+ argument,
190
+ { kind: "function", declaration: fn },
191
+ index,
192
+ frame,
193
+ ),
194
+ frame,
143
195
  ),
144
196
  node,
145
197
  frame,
@@ -152,8 +204,10 @@ export class CallSpecializer {
152
204
  }
153
205
  return this.expressions.invoke(
154
206
  target,
155
- node.arguments.map((argument, index) =>
156
- this.argument(argument, target, index, frame),
207
+ this.expressions.inOrder(
208
+ node.arguments,
209
+ (argument, index) => this.argument(argument, target, index, frame),
210
+ frame,
157
211
  ),
158
212
  node,
159
213
  frame,
@@ -257,17 +311,50 @@ export class CallSpecializer {
257
311
  ) {
258
312
  return copied(argument);
259
313
  }
314
+ // Properties held in a record are sent field by field, as an object literal's are.
315
+ const argumentType = this.checker.getTypeAtLocation(argument);
316
+ if (
317
+ !ts.isObjectLiteralExpression(argument) &&
318
+ argumentType.flags & ts.TypeFlags.Object &&
319
+ !this.checker.isArrayType(argumentType)
320
+ ) {
321
+ const fields = this.expressions
322
+ .recordFields(argument, frame)
323
+ .map(
324
+ ([name, field]) =>
325
+ mapped`${name}: ${this.dialect.code(field, undefined)}`,
326
+ );
327
+ return mapped`{ ${joined(fields, ", ")} }`;
328
+ }
260
329
  if (!ts.isObjectLiteralExpression(argument)) {
261
330
  return value(argument);
262
331
  }
263
- const properties = argument.properties.map((property) => {
332
+ const properties = argument.properties.flatMap((property): Part[] => {
264
333
  if (ts.isShorthandPropertyAssignment(property)) {
265
- return mapped`${copied(property.name)}: ${value(property.name)}`;
334
+ // The name reads the local it names, not the property it declares.
335
+ const symbol =
336
+ this.checker.getShorthandAssignmentValueSymbol(property);
337
+ const local = symbol && frame.env.get(symbol);
338
+ return [
339
+ local
340
+ ? mapped`${copied(property.name)}: ${this.dialect.code(local, this.checker.getTypeAtLocation(property.name))}`
341
+ : mapped`${copied(property.name)}: ${value(property.name)}`,
342
+ ];
343
+ }
344
+ if (ts.isSpreadAssignment(property)) {
345
+ return this.expressions
346
+ .spreadFields(property, frame)
347
+ .map(
348
+ ([name, field]) =>
349
+ mapped`${name}: ${this.dialect.code(field, undefined)}`,
350
+ );
266
351
  }
267
352
  if (!ts.isPropertyAssignment(property)) {
268
353
  throw new SpecializeError(property, "Name each telemetry property.");
269
354
  }
270
- return mapped`${copied(property.name)}: ${value(property.initializer)}`;
355
+ return [
356
+ mapped`${copied(property.name)}: ${value(property.initializer)}`,
357
+ ];
271
358
  });
272
359
  return mapped`{ ${joined(properties, ", ")} }`;
273
360
  });
@@ -338,7 +425,7 @@ export class CallSpecializer {
338
425
  };
339
426
  }
340
427
  default:
341
- throw new SpecializeError(node, `Math.${name} is not supported.`);
428
+ return this.floatMath(name, args, node, frame);
342
429
  }
343
430
  }
344
431
 
@@ -377,6 +464,7 @@ export class CallSpecializer {
377
464
 
378
465
  private arrayMethod(
379
466
  name: string,
467
+ receiver: Value,
380
468
  items: Value[],
381
469
  node: ts.CallExpression,
382
470
  frame: Frame,
@@ -407,7 +495,12 @@ export class CallSpecializer {
407
495
  (start && start.kind !== "const") ||
408
496
  (end && end.kind !== "const")
409
497
  ) {
410
- throw new SpecializeError(node, "slice needs constant bounds.");
498
+ return this.expressions.iterators.sliced(
499
+ items,
500
+ { start, end },
501
+ node,
502
+ frame,
503
+ );
411
504
  }
412
505
  return {
413
506
  kind: "virtual",
@@ -488,38 +581,342 @@ export class CallSpecializer {
488
581
  }
489
582
  return accumulator;
490
583
  }
491
- case "find": {
492
- for (const [index, item] of items.entries()) {
493
- const test = apply([item, constant(index)]);
494
- if (test.kind !== "const") {
495
- throw new SpecializeError(
584
+ case "find":
585
+ // A reference to an object setup built is chosen now; a value can be chosen at run time.
586
+ return items.some(
587
+ (item) => item.kind === "static" || item.kind === "function",
588
+ )
589
+ ? this.decidedFind(items, node, apply)
590
+ : this.searches.find(items, node, frame, { last: false }, apply);
591
+ case "findLast":
592
+ return this.searches.find(items, node, frame, { last: true }, apply);
593
+ case "findIndex":
594
+ case "findLastIndex":
595
+ return this.searches.findIndex(
596
+ items,
597
+ frame,
598
+ { last: name === "findLastIndex" },
599
+ apply,
600
+ );
601
+ case "indexOf":
602
+ case "lastIndexOf":
603
+ return this.searches.indexOf(items, node, frame, {
604
+ last: name === "lastIndexOf",
605
+ });
606
+ case "includes":
607
+ return this.searches.includes(items, node, frame);
608
+ case "fill":
609
+ return this.searches.fill(receiver, items, node, frame);
610
+ case "at":
611
+ return this.searches.at(items, node, frame);
612
+ case "concat":
613
+ return {
614
+ kind: "virtual",
615
+ items: [
616
+ ...items,
617
+ ...node.arguments.flatMap((argument) => {
618
+ const value = this.expressions.expression(argument, frame);
619
+ return this.expressions.items(value) ?? [value];
620
+ }),
621
+ ],
622
+ };
623
+ default:
624
+ throw new SpecializeError(node, `${name} is not supported.`);
625
+ }
626
+ }
627
+
628
+ /** A call to a generator, as a for…of runs it: its body, the object it runs on and its arguments. */
629
+ generator(
630
+ node: ts.Expression,
631
+ frame: Frame,
632
+ ):
633
+ | { declaration: FunctionLike; self?: ModelNode; args: Value[] }
634
+ | undefined {
635
+ if (!ts.isCallExpression(node)) {
636
+ return undefined;
637
+ }
638
+ const declaration = this.checker.getResolvedSignature(node)?.declaration;
639
+ if (
640
+ !declaration ||
641
+ !(
642
+ ts.isFunctionDeclaration(declaration) ||
643
+ ts.isMethodDeclaration(declaration) ||
644
+ ts.isFunctionExpression(declaration)
645
+ ) ||
646
+ !declaration.asteriskToken ||
647
+ !declaration.body
648
+ ) {
649
+ return undefined;
650
+ }
651
+ const callee = node.expression;
652
+ const target = ts.isPropertyAccessExpression(callee)
653
+ ? this.expressions.member(
654
+ this.expressions.expression(callee.expression, frame),
655
+ callee.name.text,
656
+ callee,
657
+ frame,
658
+ )
659
+ : this.expressions.expression(callee, frame);
660
+ const self = target.kind === "function" ? target.self : undefined;
661
+ const args = this.expressions.inOrder(
662
+ node.arguments,
663
+ (argument) => this.expressions.expression(argument, frame),
664
+ frame,
665
+ );
666
+ return { declaration, self, args };
667
+ }
668
+
669
+ /**
670
+ * Math on floating values, through the SDK's math functions. An integer argument becomes LREAL
671
+ * exactly, so its proved range carries over; the result is floating, and converts as IEC assignment
672
+ * does where it is stored as a number.
673
+ */
674
+ private floatMath(
675
+ name: string,
676
+ args: readonly Value[],
677
+ node: ts.Expression,
678
+ frame: Frame,
679
+ ): Value {
680
+ const declared = this.checker.getTypeAtLocation(node);
681
+ const [first, second] = args;
682
+ if (!first) {
683
+ throw new SpecializeError(node, `Math.${name} needs a value.`);
684
+ }
685
+ const type = floatIec(first) ?? (second && floatIec(second)) ?? "LREAL";
686
+ const float = (value: Value) => this.asFloat(value, type);
687
+ const sdk = (fn: string, ...operands: readonly Part[]): Value => {
688
+ this.imports.addSdk("@tsplc/compiler/types", fn);
689
+ return {
690
+ kind: "code",
691
+ text: mapped`${fn}<${type}>(${joined(operands, ", ")})`,
692
+ declared,
693
+ iec: type,
694
+ };
695
+ };
696
+ const elementary = elementaryNames.get(name);
697
+ if (elementary) {
698
+ return sdk(elementary, float(first));
699
+ }
700
+ if (name === "pow" && second) {
701
+ return sdk("expt", float(first), float(second));
702
+ }
703
+ if (["floor", "ceil", "round", "trunc"].includes(name)) {
704
+ if (!floatIec(first)) {
705
+ return first;
706
+ }
707
+ return this.rounded(name, first, type, frame, declared);
708
+ }
709
+ if (name === "sign") {
710
+ const held = this.expressions.held(first, frame);
711
+ const zero = floatIec(first) ? "0.0" : "0";
712
+ const text = this.dialect.code(held, undefined);
713
+ return {
714
+ kind: "code",
715
+ text: mapped`(${text} > ${zero} ? 1 : (${text} < ${zero} ? -1 : 0))`,
716
+ declared,
717
+ };
718
+ }
719
+ throw new SpecializeError(
720
+ node,
721
+ `Math.${name} has no PLC function whose result can be proved finite.`,
722
+ );
723
+ }
724
+
725
+ /** `base ** exponent`, as Math.pow is. */
726
+ power(
727
+ base: Value,
728
+ exponent: Value,
729
+ node: ts.BinaryExpression,
730
+ frame: Frame,
731
+ ): Value {
732
+ return this.floatMath("pow", [base, exponent], node, frame);
733
+ }
734
+
735
+ /** A floating value toward zero, down, up or to the nearest whole value, as floating. */
736
+ private rounded(
737
+ name: string,
738
+ value: Value,
739
+ type: string,
740
+ frame: Frame,
741
+ declared: ts.Type,
742
+ ): Value {
743
+ this.imports.addSdk("@tsplc/compiler/types", "trunc");
744
+ // Math.round takes halves up: the nearest whole value is the floor of the value plus a half.
745
+ const source =
746
+ name === "round"
747
+ ? mapped`(${this.dialect.code(value, undefined)} + 0.5)`
748
+ : this.dialect.code(value, undefined);
749
+ const held = frame.emitter.temporary();
750
+ frame.emitter.line(mapped`const ${held}: ${type} = ${source};`);
751
+ const whole = frame.emitter.temporary();
752
+ frame.emitter.line(`const ${whole}: ${type} = trunc<${type}>(${held});`);
753
+ const text = (() => {
754
+ switch (name) {
755
+ case "floor":
756
+ case "round":
757
+ return `(${whole} > ${held} ? ${whole} - 1.0 : ${whole})`;
758
+ case "ceil":
759
+ return `(${whole} < ${held} ? ${whole} + 1.0 : ${whole})`;
760
+ default:
761
+ return whole;
762
+ }
763
+ })();
764
+ return { kind: "code", text, declared, iec: type };
765
+ }
766
+
767
+ /** A value as the floating type: as it is when it already is, else converted exactly. */
768
+ private asFloat(value: Value, type: string): Part {
769
+ if (floatIec(value) || value.kind === "const") {
770
+ return this.dialect.code(value, undefined);
771
+ }
772
+ this.imports.addSdk("@tsplc/compiler/types", "exact");
773
+ return mapped`exact<${type}>(${this.dialect.code(value, undefined)})`;
774
+ }
775
+
776
+ /**
777
+ * `Array.from({ length }, make)` with a length known now: an array of that many values, as setup
778
+ * builds one. Its length is fixed, so it needs no storage beyond its own.
779
+ */
780
+ private arrayFrom(node: ts.CallExpression, frame: Frame): Value {
781
+ const [shape, make] = node.arguments;
782
+ const length =
783
+ shape &&
784
+ ts.isObjectLiteralExpression(shape) &&
785
+ this.expressions.member(
786
+ this.expressions.expression(shape, frame),
787
+ "length",
788
+ shape,
789
+ frame,
790
+ );
791
+ if (
792
+ !length ||
793
+ length.kind !== "const" ||
794
+ typeof length.value !== "number"
795
+ ) {
796
+ throw new SpecializeError(
797
+ node,
798
+ "Array.from needs a length known when the program compiles.",
799
+ );
800
+ }
801
+ const maker = make && this.expressions.expression(make, frame);
802
+ return {
803
+ kind: "virtual",
804
+ items: Array.from({ length: length.value }, (_, index) =>
805
+ maker
806
+ ? this.expressions.invoke(
807
+ maker,
808
+ [constant(undefined), constant(index)],
496
809
  node,
497
- "find must decide from what setup built.",
498
- );
499
- }
500
- if (test.value) {
501
- return item;
502
- }
810
+ frame,
811
+ )
812
+ : constant(undefined),
813
+ ),
814
+ };
815
+ }
816
+
817
+ /**
818
+ * `structuredClone(value)`: a record or array of its own, as the dialect's `copy` makes one, for
819
+ * code that changes it and stores it back.
820
+ */
821
+ private cloned(node: ts.CallExpression, frame: Frame): Value {
822
+ const [argument] = node.arguments;
823
+ if (!argument) {
824
+ throw new SpecializeError(node, "structuredClone needs a value.");
825
+ }
826
+ const value = this.expressions.expression(argument, frame);
827
+ if (value.kind !== "code") {
828
+ return value;
829
+ }
830
+ this.imports.addSdk("@tsplc/compiler/types", "copy");
831
+ return {
832
+ kind: "code",
833
+ text: mapped`copy(${value.text})`,
834
+ declared: value.declared,
835
+ iec: value.iec,
836
+ layout: value.layout,
837
+ length: value.length,
838
+ };
839
+ }
840
+
841
+ /** Whether the expression is `array.filter(test)`, whose length counts the elements that pass. */
842
+ isFilter(node: ts.Expression): node is ts.CallExpression {
843
+ return (
844
+ ts.isCallExpression(node) &&
845
+ ts.isPropertyAccessExpression(node.expression) &&
846
+ node.expression.name.text === "filter" &&
847
+ node.arguments.length === 1
848
+ );
849
+ }
850
+
851
+ /**
852
+ * `array.filter(test).length`: how many elements pass. A filter decided at run time has no array
853
+ * to build, since its length isn't fixed, but its count is a number.
854
+ */
855
+ count(node: ts.CallExpression, frame: Frame): Value {
856
+ const callee = node.expression;
857
+ if (!ts.isPropertyAccessExpression(callee)) {
858
+ throw new SpecializeError(node, "Not a filter.");
859
+ }
860
+ const items = this.expressions.items(
861
+ this.expressions.expression(callee.expression, frame),
862
+ );
863
+ const [testNode] = node.arguments;
864
+ if (!items || !testNode) {
865
+ throw new SpecializeError(
866
+ node,
867
+ "filter needs an array setup built and a test.",
868
+ );
869
+ }
870
+ const test = this.expressions.expression(testNode, frame);
871
+ const results = items.map((item, index) =>
872
+ this.expressions.invoke(test, [item, constant(index)], node, frame),
873
+ );
874
+ if (results.every((result) => result.kind === "const")) {
875
+ return constant(
876
+ results.filter((result) => result.kind === "const" && result.value)
877
+ .length,
878
+ );
879
+ }
880
+ const total = frame.emitter.temporary();
881
+ frame.emitter.line(`let ${total}: number = 0;`);
882
+ for (const result of results) {
883
+ if (result.kind === "const") {
884
+ if (result.value) {
885
+ frame.emitter.line(`${total} = ${total} + 1;`);
503
886
  }
504
- return constant(undefined);
887
+ continue;
505
888
  }
506
- case "includes": {
507
- const target = this.expressions.expression(node.arguments[0]!, frame);
508
- const tests = items.map((item) => this.expressions.equal(item, target));
509
- if (tests.some((test) => test === true)) {
510
- return constant(true);
511
- }
512
- if (tests.every((test) => test === false)) {
513
- return constant(false);
514
- }
889
+ frame.emitter.line(
890
+ mapped`if (${this.dialect.condition(result, testNode)}) { ${total} = ${total} + 1; }`,
891
+ );
892
+ }
893
+ return {
894
+ kind: "code",
895
+ text: total,
896
+ declared: this.checker.getNumberType(),
897
+ place: true,
898
+ };
899
+ }
900
+
901
+ /** find over objects setup built, whose tests are known now: the object that passes, or undefined. */
902
+ private decidedFind(
903
+ items: readonly Value[],
904
+ node: ts.CallExpression,
905
+ apply: (args: Value[]) => Value,
906
+ ): Value {
907
+ for (const [index, item] of items.entries()) {
908
+ const test = apply([item, constant(index)]);
909
+ if (test.kind !== "const") {
515
910
  throw new SpecializeError(
516
911
  node,
517
- "includes must decide from what setup built.",
912
+ "find picks one of the objects setup built, which scan code can't hold; use findIndex and index the array.",
518
913
  );
519
914
  }
520
- default:
521
- throw new SpecializeError(node, `${name} is not supported.`);
915
+ if (test.value) {
916
+ return item;
917
+ }
522
918
  }
919
+ return constant(undefined);
523
920
  }
524
921
 
525
922
  /** Keeps a runtime result in a local, so later code reads it rather than repeating it. */
@@ -547,5 +944,33 @@ const arrayMethods = new Set([
547
944
  "reduce",
548
945
  "reduceRight",
549
946
  "find",
947
+ "findLast",
948
+ "findIndex",
949
+ "findLastIndex",
950
+ "indexOf",
951
+ "lastIndexOf",
550
952
  "includes",
953
+ "fill",
954
+ "at",
955
+ "concat",
956
+ ]);
957
+
958
+ /** The SDK function each of JavaScript's Math functions is, among those whose result can be proved finite. */
959
+ const elementaryNames = new Map<string, string>([
960
+ ["sqrt", "sqrt"],
961
+ ["log", "ln"],
962
+ ["log10", "log10"],
963
+ ["exp", "exp"],
964
+ ["sin", "sin"],
965
+ ["cos", "cos"],
966
+ ["tan", "tan"],
967
+ ["asin", "asin"],
968
+ ["acos", "acos"],
969
+ ["atan", "atan"],
551
970
  ]);
971
+
972
+ /** The floating IEC type a value has, if it is floating. */
973
+ const floatIec = (value: Value): string | undefined =>
974
+ value.kind === "code" && (value.iec === "REAL" || value.iec === "LREAL")
975
+ ? value.iec
976
+ : undefined;
@@ -4,9 +4,19 @@ import { z } from "zod";
4
4
  * The files the compiler and its setup subprocess (capture.ts) exchange: the request names the
5
5
  * program's runtime files and the bindings each declares; the graph is what setup built.
6
6
  */
7
+ /** An arrow or function expression setup may store, and the names it captures from around it. */
8
+ const closureSiteSchema = z.strictObject({
9
+ start: z.number().int().nonnegative(),
10
+ end: z.number().int().nonnegative(),
11
+ captures: z.array(z.string()),
12
+ });
13
+ export type ClosureSite = z.infer<typeof closureSiteSchema>;
14
+
7
15
  export const captureRequestSchema = z.strictObject({
8
16
  entry: z.string().nonempty(),
9
17
  files: z.array(z.string().nonempty()),
18
+ /** By file, each closure whose creation setup notes, with what it captured. */
19
+ closures: z.record(z.string(), z.array(closureSiteSchema)),
10
20
  bindings: z.record(
11
21
  z.string(),
12
22
  z.strictObject({
@@ -76,6 +86,15 @@ const capturedNodeSchema = z.discriminatedUnion("kind", [
76
86
  name: z.string(),
77
87
  }),
78
88
  z.strictObject({ kind: z.literal("service"), path: z.string() }),
89
+ /** A function setup made inside another, by where it is written, with the values it captured. */
90
+ z.strictObject({
91
+ kind: z.literal("closure"),
92
+ file: z.string(),
93
+ start: z.number().int().nonnegative(),
94
+ captures: z.array(
95
+ z.strictObject({ name: z.string(), value: capturedValueSchema }),
96
+ ),
97
+ }),
79
98
  ]);
80
99
  export type CapturedNode = z.infer<typeof capturedNodeSchema>;
81
100