@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
@@ -12,6 +12,7 @@ import {
12
12
  type Step,
13
13
  tsPath,
14
14
  } from "./model";
15
+ import { referenceLayout, referenceType } from "./references";
15
16
  import { constant, type Value } from "./values";
16
17
  import { ScanWrites } from "./writes";
17
18
 
@@ -45,8 +46,24 @@ export class Storage {
45
46
  private readonly rootModule: (root: Root) => string,
46
47
  ) {
47
48
  this.writes = new ScanWrites(checker, sources);
49
+ this.typeNames = new Set(
50
+ sources.flatMap((source) =>
51
+ source.statements.flatMap((statement) =>
52
+ (ts.isInterfaceDeclaration(statement) ||
53
+ ts.isTypeAliasDeclaration(statement) ||
54
+ ts.isClassDeclaration(statement) ||
55
+ ts.isEnumDeclaration(statement)) &&
56
+ statement.name
57
+ ? [statement.name.text]
58
+ : [],
59
+ ),
60
+ ),
61
+ );
48
62
  }
49
63
 
64
+ /** The program's own type names, which a root's namespace mustn't take: `line` and the `Line` interface. */
65
+ private readonly typeNames: ReadonlySet<string>;
66
+
50
67
  /** The declaration symbol of a captured field, to ask whether scan code writes it. */
51
68
  private fieldSymbol(holder: ModelNode, name: string): ts.Symbol | undefined {
52
69
  if (holder.captured.kind === "instance") {
@@ -76,6 +93,29 @@ export class Storage {
76
93
  return symbol !== undefined && this.writes.includes(symbol);
77
94
  }
78
95
 
96
+ /**
97
+ * Whether an instance's field stores a reference: one of a class's type that scan code assigns.
98
+ * The PLC keeps the id of the object it refers to, not a copy of the object.
99
+ */
100
+ referenceField(holder: ModelNode, name: string): boolean {
101
+ const key = `${holder.id}.${name}`;
102
+ const known = this.referenceFields.get(key);
103
+ if (known !== undefined) {
104
+ return known;
105
+ }
106
+ const type =
107
+ holder.captured.kind === "instance"
108
+ ? this.model.capturedFieldType(holder, name)
109
+ : undefined;
110
+ const found =
111
+ type !== undefined && referenceType(type) && this.written(holder, name);
112
+ this.referenceFields.set(key, found);
113
+ return found;
114
+ }
115
+
116
+ /** Asked of every field each time an instance's layout is, so answered once. */
117
+ private readonly referenceFields = new Map<string, boolean>();
118
+
79
119
  /** Array elements are stored when the field holding the array is, or its root is exported. */
80
120
  private storedArray(array: ModelNode): boolean {
81
121
  const owner = array.owner;
@@ -120,7 +160,9 @@ export class Storage {
120
160
  /** Dialect text for one step down from `holder`: a `Record<Enum, T>` key indexes by its enum member. */
121
161
  private placeStep(holder: ModelNode | undefined, step: Step): string {
122
162
  if (step.kind === "index") {
123
- return `[${step.index}]`;
163
+ return holder && this.mixedStates(holder)
164
+ ? `.${mixedItem(step.index)}`
165
+ : `[${step.index}]`;
124
166
  }
125
167
  if (/^\d+$/.test(step.name) && holder?.type) {
126
168
  return `[${this.keyText(holder.type, step.name)}]`;
@@ -147,7 +189,8 @@ export class Storage {
147
189
  }
148
190
 
149
191
  private namespace(root: Root): string {
150
- const name = pascalCase(root.name);
192
+ const pascal = pascalCase(root.name);
193
+ const name = this.typeNames.has(pascal) ? `${pascal}Root` : pascal;
151
194
  this.imports.namespaces.set(name, this.rootModule(root));
152
195
  return name;
153
196
  }
@@ -217,13 +260,27 @@ export class Storage {
217
260
  }
218
261
  if (captured.kind === "array") {
219
262
  const first = captured.items[0] && this.model.node(captured.items[0]);
220
- if (first?.captured.kind === "instance") {
221
- const states = captured.items.map((item) =>
222
- this.storageType(this.model.node(item)!),
263
+ const states = this.itemLayouts(node);
264
+ // Elements whose states differ, as instances of different subclasses do, are kept side by side.
265
+ if (states && new Set(states).size > 1) {
266
+ return this.layoutName(
267
+ "MixedStates",
268
+ states
269
+ .map(
270
+ (state, index) => `${mixedItem(index)}: ${state ?? "boolean"};`,
271
+ )
272
+ .join(" "),
223
273
  );
274
+ }
275
+ if (first?.captured.kind === "instance" && states) {
224
276
  if (new Set(states).size !== 1) {
225
- throw new Error(
226
- "Instances in one array must hold the same kinds of state.",
277
+ return this.layoutName(
278
+ "MixedStates",
279
+ states
280
+ .map(
281
+ (state, index) => `${mixedItem(index)}: ${state ?? "boolean"};`,
282
+ )
283
+ .join(" "),
227
284
  );
228
285
  }
229
286
  return `FixedArray<${states[0]}, ${captured.items.length}>`;
@@ -235,6 +292,61 @@ export class Storage {
235
292
  return this.layouts.text(node.type, { kind: "node", id: node.id });
236
293
  }
237
294
 
295
+ /**
296
+ * Whether an array holds instances whose states differ, so it is stored as a record with a field
297
+ * per element; scan code reaches each element by an index known when it compiles.
298
+ */
299
+ mixedStates(node: ModelNode): boolean {
300
+ const known = this.mixed.get(node);
301
+ if (known !== undefined) {
302
+ return known;
303
+ }
304
+ const found = this.statesDiffer(node);
305
+ this.mixed.set(node, found);
306
+ return found;
307
+ }
308
+
309
+ /**
310
+ * Every path through an array asks this, and the answer walks all the array holds; setup and the
311
+ * fields scan code writes fix it, so it is worked out once.
312
+ */
313
+ private readonly mixed = new Map<ModelNode, boolean>();
314
+
315
+ private statesDiffer(node: ModelNode): boolean {
316
+ if (!this.hasState(node)) {
317
+ return false;
318
+ }
319
+ const layouts = this.itemLayouts(node);
320
+ return layouts !== undefined && new Set(layouts).size > 1;
321
+ }
322
+
323
+ /**
324
+ * Each element's stored layout, for an array of instances or of records: records holding instances
325
+ * can differ too, as when one instance owns objects the others only refer to.
326
+ */
327
+ private itemLayouts(node: ModelNode): (string | undefined)[] | undefined {
328
+ const captured = node.captured;
329
+ if (captured.kind !== "array") {
330
+ return undefined;
331
+ }
332
+ const items = captured.items.map((item) => this.model.node(item));
333
+ if (items.some((item) => !item)) {
334
+ return undefined;
335
+ }
336
+ const element = node.type && this.model.elementType(node.type);
337
+ return items.map((item) => {
338
+ if (!item) {
339
+ return undefined;
340
+ }
341
+ if (item.captured.kind === "instance") {
342
+ return this.storageType(item);
343
+ }
344
+ return element
345
+ ? this.layouts.text(element, { kind: "node", id: item.id })
346
+ : undefined;
347
+ });
348
+ }
349
+
238
350
  /** Records stored as a whole: anything in them is state. */
239
351
  private storedWhole(node: ModelNode): boolean {
240
352
  return node.captured.kind !== "instance" && this.hasState(node);
@@ -251,10 +363,23 @@ export class Storage {
251
363
  const name = member.name.getText();
252
364
  const value = captured.fields[name] ?? { kind: "undefined" };
253
365
  const inner = this.model.node(value);
254
- const type = this.checker.getTypeAtLocation(member.name);
366
+ // A generic class's instance stores its fields at its own type arguments.
367
+ const type =
368
+ this.model.capturedFieldType(node, name) ??
369
+ this.checker.getTypeAtLocation(member.name);
370
+ if (this.referenceField(node, name)) {
371
+ // The object setup put there is stored through this field, which a reference would replace.
372
+ if (inner && isChild(inner, node, name)) {
373
+ throw new Error(
374
+ `${captured.name}.${name} is assigned in scan code, but it is where setup first put the object it starts with, so that object is stored there. Give the object another owner: a module constant, or a readonly field setup assigns before this one.`,
375
+ );
376
+ }
377
+ return [[name, referenceLayout]];
378
+ }
255
379
  if (inner) {
256
380
  if (
257
381
  inner.captured.kind === "function" ||
382
+ inner.captured.kind === "closure" ||
258
383
  inner.captured.kind === "service"
259
384
  ) {
260
385
  return [];
@@ -306,7 +431,7 @@ export class Storage {
306
431
  }
307
432
  if (
308
433
  this.kept(root.file) ||
309
- root.declaration.parent.flags & ts.NodeFlags.Const
434
+ ts.getCombinedNodeFlags(root.declaration) & ts.NodeFlags.Const
310
435
  ) {
311
436
  return primitive(value);
312
437
  }
@@ -330,7 +455,7 @@ export class Storage {
330
455
  kind: "code",
331
456
  text: root.name,
332
457
  declared: this.checker.getTypeAtLocation(root.declaration.name),
333
- place: !(root.declaration.parent.flags & ts.NodeFlags.Const),
458
+ place: !(ts.getCombinedNodeFlags(root.declaration) & ts.NodeFlags.Const),
334
459
  };
335
460
  }
336
461
 
@@ -338,6 +463,10 @@ export class Storage {
338
463
  fromCaptured(value: CapturedValue, holder: ModelNode, step: Step): Value {
339
464
  if (value.kind === "node") {
340
465
  const node = this.model.node(value);
466
+ // A reference field is a place too, though it starts as an object: it holds that object's id.
467
+ if (step.kind === "field" && this.referenceField(holder, step.name)) {
468
+ return this.storedField(holder, step);
469
+ }
341
470
  // A field scan code assigns as a whole is a place, holding its own copy of what setup gave it.
342
471
  if (
343
472
  (node.captured.kind === "object" || node.captured.kind === "array") &&
@@ -507,10 +636,19 @@ export class Storage {
507
636
  declared,
508
637
  array,
509
638
  ),
639
+ length: this.capturedLength(array),
510
640
  }),
511
641
  };
512
642
  }
513
643
 
644
+ private capturedLength(array: CapturedValue): number | undefined {
645
+ if (array.kind !== "node") {
646
+ return undefined;
647
+ }
648
+ const captured = this.model.node(array).captured;
649
+ return captured.kind === "array" ? captured.items.length : undefined;
650
+ }
651
+
514
652
  storedNode(node: ModelNode): boolean {
515
653
  return node.captured.kind === "array"
516
654
  ? this.storedArray(node)
@@ -559,3 +697,6 @@ const isChild = (
559
697
 
560
698
  const stepText = (step: Step): string =>
561
699
  step.kind === "index" ? `[${step.index}]` : `.${step.name}`;
700
+
701
+ /** The field of a mixed-state array's record that holds element `index`. */
702
+ const mixedItem = (index: number): string => `item${index}`;
@@ -1,5 +1,6 @@
1
1
  import type ts from "typescript";
2
2
  import type { Mapped } from "../positions";
3
+ import type { Frame } from "./frame";
3
4
  import type { ModelNode } from "./model";
4
5
 
5
6
  export type FunctionLike =
@@ -30,10 +31,81 @@ export type Value =
30
31
  elementIec?: string;
31
32
  /** For an array place, its layout with the length setup gave it, such as `FixedArray<BYTE, 32>`. */
32
33
  layout?: string;
34
+ /** For an array place, the length setup gave it, so scan code can visit each element. */
35
+ length?: number;
33
36
  /** A module global another module stores into through its setter; an import is read-only. */
34
37
  setter?: string;
38
+ /**
39
+ * For a place reached through a runtime index, the same place with its indexes held in
40
+ * consts, so a name for it keeps meaning the element it named when it was bound.
41
+ */
42
+ pinned?: (frame: Frame) => Value;
43
+ /**
44
+ * A copy of stored state a routine returned, named for the error: TypeScript would hand back
45
+ * the stored object, so writing it here would change nothing the PLC keeps.
46
+ */
47
+ copyOf?: string;
48
+ /** What an `await` gives, typed by the call it awaited. */
49
+ awaited?: boolean;
50
+ }
51
+ /**
52
+ * A reference scan code chooses at run time, among objects setup built. `index` is code for the
53
+ * id of the object it holds, one of `options`, or -1 for undefined.
54
+ */
55
+ | {
56
+ kind: "choice";
57
+ options: readonly ModelNode[];
58
+ index: string | Mapped;
59
+ optional: boolean;
60
+ /** Whether `index` is storage scan code can assign: a reference field, or a let. */
61
+ place?: boolean;
62
+ /** A module global's setter, as a code place has. */
63
+ setter?: string;
64
+ }
65
+ /**
66
+ * An array of known values a filter decided at run time: every candidate, each with whether the
67
+ * array holds it. `order` is the comparator of a `toSorted` over it, which nothing has run yet.
68
+ */
69
+ | {
70
+ kind: "masked";
71
+ entries: readonly { item: Value; present: Value }[];
72
+ order?: Value;
73
+ }
74
+ /**
75
+ * An array whose length is decided at run time: a `toArray()` snapshot, or a slice with runtime
76
+ * bounds. Its storage is fixed, and the elements from `start` up to `end` are the ones it has.
77
+ */
78
+ | {
79
+ kind: "counted";
80
+ source: CountedSource;
81
+ /** Indexes into the storage, known now or held in consts: 0 <= start <= end <= its length. */
82
+ start: Value;
83
+ end: Value;
35
84
  };
36
85
 
86
+ /**
87
+ * Where a counted array's elements are read from: elements setup fixed, each known by itself, or an
88
+ * array the PLC stores whole, which is a snapshot's local or a runtime array a routine was passed.
89
+ */
90
+ export type CountedSource =
91
+ | { kind: "items"; items: readonly Value[] }
92
+ | {
93
+ kind: "array";
94
+ text: string | Mapped;
95
+ /** The array's PLC type, as a routine it is passed to declares it. */
96
+ layout: string;
97
+ /** How many elements the array has room for. */
98
+ bound: number;
99
+ /** One element of the array, given the code that indexes it. */
100
+ element: (index: string | Mapped) => Value;
101
+ /** Whether the array is a copy nothing else writes, so a slice of it can be kept. */
102
+ snapshot: boolean;
103
+ /** For a snapshot, how many slots it stored into; the rest still hold the element type's empty value. */
104
+ filled?: Value;
105
+ };
106
+
107
+ export type Counted = Extract<Value, { kind: "counted" }>;
108
+
37
109
  export type Env = Map<ts.Symbol, Value>;
38
110
 
39
111
  export const constant = (
@@ -29,10 +29,37 @@ export class ScanWrites {
29
29
  }
30
30
 
31
31
  private collectAssignments(node: ts.Node, inConstructor: boolean): void {
32
- const constructing = inConstructor || ts.isConstructorDeclaration(node);
32
+ // A closure made in a constructor runs later, as scan code, so its writes are state.
33
+ const constructing =
34
+ ts.isConstructorDeclaration(node) ||
35
+ (inConstructor &&
36
+ !ts.isArrowFunction(node) &&
37
+ !ts.isFunctionExpression(node));
33
38
  if (!constructing) {
34
39
  const write = (target: ts.Expression): void => {
35
40
  const place = unwrapped(target);
41
+ // A destructuring assignment writes each of its pattern's targets.
42
+ if (ts.isArrayLiteralExpression(place)) {
43
+ for (const element of place.elements) {
44
+ write(ts.isSpreadElement(element) ? element.expression : element);
45
+ }
46
+ return;
47
+ }
48
+ if (ts.isObjectLiteralExpression(place)) {
49
+ for (const property of place.properties) {
50
+ if (ts.isPropertyAssignment(property)) {
51
+ write(property.initializer);
52
+ }
53
+ }
54
+ return;
55
+ }
56
+ if (
57
+ ts.isBinaryExpression(place) &&
58
+ place.operatorToken.kind === ts.SyntaxKind.EqualsToken
59
+ ) {
60
+ write(place.left);
61
+ return;
62
+ }
36
63
  if (ts.isPropertyAccessExpression(place)) {
37
64
  this.markAssigned(place.name);
38
65
  } else if (ts.isElementAccessExpression(place)) {
@@ -98,3 +125,277 @@ export const isUpdate = (
98
125
  /** Whether an operator assigns its left operand: `=`, a compound assignment or `??=`. */
99
126
  export const isAssignment = (kind: ts.SyntaxKind): boolean =>
100
127
  kind >= ts.SyntaxKind.FirstAssignment && kind <= ts.SyntaxKind.LastAssignment;
128
+
129
+ /** Whether the body assigns or steps any name the binding declares. */
130
+ export const assignsName = (
131
+ body: ts.Node,
132
+ binding: ts.BindingName,
133
+ checker: ts.TypeChecker,
134
+ ): boolean => {
135
+ const declared = new Set<ts.Symbol>();
136
+ const collect = (name: ts.BindingName): void => {
137
+ if (ts.isIdentifier(name)) {
138
+ const symbol = checker.getSymbolAtLocation(name);
139
+ if (symbol) {
140
+ declared.add(symbol);
141
+ }
142
+ return;
143
+ }
144
+ for (const element of name.elements) {
145
+ if (!ts.isOmittedExpression(element)) {
146
+ collect(element.name);
147
+ }
148
+ }
149
+ };
150
+ collect(binding);
151
+ return assignsSymbol(body, declared, checker);
152
+ };
153
+
154
+ /** Whether the body assigns or steps a name that refers to one of the symbols. */
155
+ export const assignsSymbol = (
156
+ body: ts.Node,
157
+ declared: ReadonlySet<ts.Symbol>,
158
+ checker: ts.TypeChecker,
159
+ ): boolean => {
160
+ const target = (node: ts.Expression): boolean => {
161
+ const symbol = ts.isIdentifier(node)
162
+ ? checker.getSymbolAtLocation(node)
163
+ : undefined;
164
+ return symbol !== undefined && declared.has(symbol);
165
+ };
166
+ const visit = (node: ts.Node): boolean =>
167
+ (ts.isBinaryExpression(node) &&
168
+ isAssignment(node.operatorToken.kind) &&
169
+ target(node.left)) ||
170
+ (isUpdate(node) && target(node.operand)) ||
171
+ (ts.forEachChild(node, visit) ?? false);
172
+ return visit(body);
173
+ };
174
+
175
+ /**
176
+ * Whether the body changes what a local holds through it, by writing one of its fields or elements,
177
+ * or lends it to a call, which can.
178
+ */
179
+ export const writesThrough = (
180
+ body: ts.Node,
181
+ symbol: ts.Symbol,
182
+ checker: ts.TypeChecker,
183
+ ): boolean => {
184
+ const root = (node: ts.Expression): ts.Expression =>
185
+ ts.isPropertyAccessExpression(node) ||
186
+ ts.isElementAccessExpression(node) ||
187
+ ts.isParenthesizedExpression(node) ||
188
+ ts.isNonNullExpression(node)
189
+ ? root(node.expression)
190
+ : node;
191
+ const named = (node: ts.Expression): boolean =>
192
+ ts.isIdentifier(node) && checker.getSymbolAtLocation(node) === symbol;
193
+ const throughIt = (target: ts.Expression): boolean =>
194
+ target !== root(target) && named(root(target));
195
+ const visit = (node: ts.Node): boolean =>
196
+ (ts.isBinaryExpression(node) &&
197
+ isAssignment(node.operatorToken.kind) &&
198
+ throughIt(node.left)) ||
199
+ (isUpdate(node) && throughIt(node.operand)) ||
200
+ (ts.isCallExpression(node) && node.arguments.some(named)) ||
201
+ (ts.forEachChild(node, visit) ?? false);
202
+ return visit(body);
203
+ };
204
+
205
+ /** Where an alias is live: from its declaration to its last use, or its scope's end when a use can run again after a later write. */
206
+ interface AliasWindow {
207
+ scope: ts.Node;
208
+ /** What the alias was declared from: its initializer, or for `const { name } = value`, that property of the value. */
209
+ source: ts.Expression;
210
+ /** The property a destructured alias reads from `source`. */
211
+ property: string | undefined;
212
+ from: number;
213
+ until: number;
214
+ }
215
+
216
+ const aliasWindow = (
217
+ name: ts.Identifier,
218
+ checker: ts.TypeChecker,
219
+ ): AliasWindow | undefined => {
220
+ const symbol = checker.getSymbolAtLocation(name);
221
+ const scope = enclosingScope(name);
222
+ const binding = ts.isBindingElement(name.parent) ? name.parent : undefined;
223
+ const declaration = binding
224
+ ? ts.findAncestor(binding, ts.isVariableDeclaration)
225
+ : name.parent;
226
+ if (
227
+ !symbol ||
228
+ !scope ||
229
+ !declaration ||
230
+ !ts.isVariableDeclaration(declaration) ||
231
+ !declaration.initializer ||
232
+ // A nested pattern reads through more than one property.
233
+ (binding && !ts.isVariableDeclaration(binding.parent.parent))
234
+ ) {
235
+ return undefined;
236
+ }
237
+ const uses: ts.Identifier[] = [];
238
+ const collect = (node: ts.Node): void => {
239
+ if (
240
+ ts.isIdentifier(node) &&
241
+ node !== name &&
242
+ checker.getSymbolAtLocation(node) === symbol
243
+ ) {
244
+ uses.push(node);
245
+ }
246
+ ts.forEachChild(node, collect);
247
+ };
248
+ collect(scope);
249
+ const contains = (outer: ts.Node, inner: ts.Node): boolean =>
250
+ outer.pos <= inner.pos && inner.end <= outer.end;
251
+ const reentered = (use: ts.Node): boolean => {
252
+ for (let node = use.parent; node && node !== scope; node = node.parent) {
253
+ if (
254
+ (ts.isIterationStatement(node, false) || ts.isFunctionLike(node)) &&
255
+ !contains(node, declaration)
256
+ ) {
257
+ return true;
258
+ }
259
+ }
260
+ return false;
261
+ };
262
+ const from = declaration.end;
263
+ return {
264
+ scope,
265
+ source: declaration.initializer,
266
+ property: binding && (binding.propertyName ?? binding.name).getText(),
267
+ from,
268
+ until: uses.some(reentered)
269
+ ? scope.end
270
+ : Math.max(from, ...uses.map((use) => use.getStart())),
271
+ };
272
+ };
273
+
274
+ /** Whether any node of `scope` that runs wholly inside the window matches. */
275
+ const runsBetween = (
276
+ { scope, from, until }: AliasWindow,
277
+ matches: (node: ts.Node) => boolean,
278
+ ): boolean => {
279
+ const visit = (node: ts.Node): boolean =>
280
+ (node.getStart() >= from && node.end <= until && matches(node)) ||
281
+ (ts.forEachChild(node, visit) ?? false);
282
+ return visit(scope);
283
+ };
284
+
285
+ /** The names along a place's path, root first, past `this`; element indexes are left out. */
286
+ const pathNames = (place: ts.Expression): string[] | undefined => {
287
+ const node = unwrapped(place);
288
+ if (ts.isIdentifier(node)) {
289
+ return [node.text];
290
+ }
291
+ if (node.kind === ts.SyntaxKind.ThisKeyword) {
292
+ return [];
293
+ }
294
+ if (ts.isPropertyAccessExpression(node)) {
295
+ const base = pathNames(node.expression);
296
+ return base && [...base, node.name.text];
297
+ }
298
+ if (ts.isElementAccessExpression(node)) {
299
+ return pathNames(node.expression);
300
+ }
301
+ return undefined;
302
+ };
303
+
304
+ /** Each assignment or step in the window, by the place it writes. */
305
+ const writesIn = (window: AliasWindow): ts.Expression[] => {
306
+ const targets: ts.Expression[] = [];
307
+ runsBetween(window, (node) => {
308
+ if (isUpdate(node)) {
309
+ targets.push(node.operand);
310
+ } else if (
311
+ ts.isBinaryExpression(node) &&
312
+ isAssignment(node.operatorToken.kind)
313
+ ) {
314
+ targets.push(node.left);
315
+ }
316
+ return false;
317
+ });
318
+ return targets;
319
+ };
320
+
321
+ /**
322
+ * Whether nothing can change what an alias's indexes read between its declaration and its last use: no
323
+ * assignment, step, call, await or yield finishes in between, and it is read in no loop or closure it was
324
+ * declared outside of, which could run after something did. Its element is then the same at each use.
325
+ */
326
+ export const stableAlias = (
327
+ name: ts.Identifier,
328
+ checker: ts.TypeChecker,
329
+ ): boolean => {
330
+ const window = aliasWindow(name, checker);
331
+ if (!window || window.property !== undefined) {
332
+ return false;
333
+ }
334
+ // What the alias's place reads, by name: a write to a place none of them name can't move it.
335
+ const read = new Set<string>();
336
+ const readNames = (node: ts.Node): void => {
337
+ if (ts.isIdentifier(node) || ts.isPrivateIdentifier(node)) {
338
+ read.add(node.text);
339
+ }
340
+ ts.forEachChild(node, readNames);
341
+ };
342
+ readNames(window.source);
343
+ const writesRead = (target: ts.Expression): boolean => {
344
+ const names = pathNames(target);
345
+ return names === undefined || names.some((written) => read.has(written));
346
+ };
347
+ return (
348
+ !writesIn(window).some(writesRead) &&
349
+ !runsBetween(
350
+ window,
351
+ (node) =>
352
+ ts.isCallExpression(node) ||
353
+ ts.isNewExpression(node) ||
354
+ ts.isAwaitExpression(node) ||
355
+ ts.isYieldExpression(node) ||
356
+ ts.isTaggedTemplateExpression(node) ||
357
+ ts.isDeleteExpression(node),
358
+ )
359
+ );
360
+ };
361
+
362
+ /**
363
+ * Whether the place an alias names is assigned anew while the alias is still read, as
364
+ * `const { pending } = this; this.pending = undefined; use(pending)` does. TypeScript's alias keeps the
365
+ * object it named; the PLC's would read the new value, so it needs a snapshot. A write into the place's
366
+ * fields, such as `this.pending.travel += 1`, is one the alias sees in both.
367
+ */
368
+ export const replacedWhileAliased = (
369
+ name: ts.Identifier,
370
+ checker: ts.TypeChecker,
371
+ ): boolean => {
372
+ const window = aliasWindow(name, checker);
373
+ const base = window && pathNames(window.source);
374
+ if (!window || !base) {
375
+ return false;
376
+ }
377
+ const path =
378
+ window.property === undefined ? base : [...base, window.property];
379
+ // Writing the place, or anything on its path, replaces what it holds.
380
+ return writesIn(window).some((target) => {
381
+ const written = pathNames(target);
382
+ const last = written?.at(-1);
383
+ return last !== undefined && path.includes(last);
384
+ });
385
+ };
386
+
387
+ /** The block, clause or source a declaration's name is scoped to. */
388
+ const enclosingScope = (node: ts.Node): ts.Node | undefined => {
389
+ for (let parent = node.parent; parent; parent = parent.parent) {
390
+ if (
391
+ ts.isBlock(parent) ||
392
+ ts.isSourceFile(parent) ||
393
+ ts.isCaseClause(parent) ||
394
+ ts.isDefaultClause(parent) ||
395
+ ts.isFunctionLike(parent)
396
+ ) {
397
+ return parent;
398
+ }
399
+ }
400
+ return undefined;
401
+ };