@tsplc/compiler 0.2.17 → 0.2.18

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 (157) hide show
  1. package/README.md +2 -2
  2. package/dist/cli.js +920 -943
  3. package/dist/cli.js.map +13 -10
  4. package/dist/codesys.js +3893 -3352
  5. package/dist/codesys.js.map +29 -20
  6. package/dist/elaborate-capture.js +33 -17
  7. package/dist/elaborate-capture.js.map +3 -3
  8. package/dist/index.js +8787 -6855
  9. package/dist/index.js.map +40 -20
  10. package/dist/ir.js +1575 -1072
  11. package/dist/ir.js.map +21 -17
  12. package/dist/math.js.map +2 -2
  13. package/dist/project.js +154 -60
  14. package/dist/project.js.map +5 -5
  15. package/dist/telemetry.js +27 -9
  16. package/dist/telemetry.js.map +5 -5
  17. package/package.json +112 -112
  18. package/src/codesys/config.ts +50 -0
  19. package/src/codesys/debug.ts +670 -0
  20. package/src/codesys/emit.ts +142 -0
  21. package/src/codesys/engineering.ts +109 -0
  22. package/src/codesys/expressions.ts +92 -0
  23. package/src/codesys/global-lists.ts +250 -0
  24. package/src/codesys/global-names.ts +68 -0
  25. package/src/codesys/http.ts +890 -0
  26. package/src/codesys/index.ts +30 -0
  27. package/src/codesys/instrumentation.ts +430 -0
  28. package/src/codesys/io-paths.ts +140 -0
  29. package/src/codesys/manifest.ts +643 -0
  30. package/src/codesys/names.ts +81 -0
  31. package/src/codesys/numeric.ts +409 -0
  32. package/src/codesys/operands.ts +62 -0
  33. package/src/codesys/plan.ts +605 -0
  34. package/src/codesys/programs.ts +53 -0
  35. package/src/codesys/publication.ts +171 -0
  36. package/src/codesys/routines.ts +603 -0
  37. package/src/codesys/sources.ts +71 -0
  38. package/src/codesys/st-files.ts +115 -0
  39. package/src/codesys/storage.ts +97 -0
  40. package/src/codesys/symbols.ts +220 -0
  41. package/src/codesys/task-access.ts +320 -0
  42. package/src/codesys/telemetry.ts +732 -0
  43. package/src/codesys/types.ts +250 -0
  44. package/src/codesys/vendor.ts +150 -0
  45. package/src/frontend/analyzer.ts +794 -0
  46. package/src/frontend/async.ts +317 -1137
  47. package/src/frontend/blocks.ts +537 -403
  48. package/src/frontend/configuration.ts +176 -144
  49. package/src/frontend/const-functions.ts +183 -148
  50. package/src/frontend/cooperative.ts +73 -43
  51. package/src/frontend/coroutines.ts +1032 -0
  52. package/src/frontend/elaborate/calls.ts +535 -0
  53. package/src/frontend/elaborate/capture.ts +157 -101
  54. package/src/frontend/elaborate/dialect.ts +257 -0
  55. package/src/frontend/elaborate/expressions.ts +992 -0
  56. package/src/frontend/elaborate/frame.ts +53 -0
  57. package/src/frontend/elaborate/graph.ts +116 -71
  58. package/src/frontend/elaborate/imports.ts +70 -0
  59. package/src/frontend/elaborate/index.ts +435 -331
  60. package/src/frontend/elaborate/initializers.ts +198 -0
  61. package/src/frontend/elaborate/layouts.ts +591 -384
  62. package/src/frontend/elaborate/model.ts +264 -169
  63. package/src/frontend/elaborate/specialize.ts +343 -2586
  64. package/src/frontend/elaborate/statements.ts +606 -0
  65. package/src/frontend/elaborate/storage.ts +546 -0
  66. package/src/frontend/elaborate/values.ts +58 -0
  67. package/src/frontend/elaborate/writes.ts +100 -0
  68. package/src/frontend/exposure.ts +172 -140
  69. package/src/frontend/expressions.ts +1383 -0
  70. package/src/frontend/intrinsics.ts +337 -0
  71. package/src/frontend/module-graph.ts +89 -59
  72. package/src/frontend/positions.ts +271 -200
  73. package/src/frontend/promise-chains.ts +897 -0
  74. package/src/frontend/promises.ts +390 -747
  75. package/src/frontend/routines.ts +181 -0
  76. package/src/frontend/sdk.ts +82 -0
  77. package/src/frontend/services.ts +506 -372
  78. package/src/frontend/statements.ts +855 -0
  79. package/src/frontend/tasks.ts +471 -0
  80. package/src/frontend/telemetry.ts +174 -0
  81. package/src/frontend/types.ts +845 -551
  82. package/src/frontend/typescript.ts +323 -2543
  83. package/src/index.ts +5 -5
  84. package/src/ir/aggregates.ts +275 -0
  85. package/src/ir/allocation.ts +84 -0
  86. package/src/ir/core-model.ts +146 -0
  87. package/src/ir/declarations.ts +295 -0
  88. package/src/ir/diagnostics.ts +61 -0
  89. package/src/ir/domains.ts +152 -0
  90. package/src/ir/fold.ts +342 -0
  91. package/src/ir/index.ts +90 -0
  92. package/{ir/errors.ts → src/ir/job-errors.ts} +12 -10
  93. package/src/ir/layouts.ts +181 -0
  94. package/src/ir/link.ts +354 -0
  95. package/src/ir/model.ts +386 -0
  96. package/{ir → src/ir}/normalization-error.ts +4 -4
  97. package/src/ir/normalize.ts +70 -0
  98. package/src/ir/numeric.ts +171 -0
  99. package/src/ir/ranges.ts +256 -0
  100. package/src/ir/routine.ts +1163 -0
  101. package/src/ir/scalars.ts +321 -0
  102. package/src/ir/types.ts +127 -0
  103. package/src/project/artifacts.ts +342 -0
  104. package/src/project/cli.ts +177 -0
  105. package/src/project/debugger.ts +82 -0
  106. package/src/project/index.ts +6 -0
  107. package/src/project/plant.ts +467 -0
  108. package/src/project/project-commands.ts +372 -0
  109. package/src/project/project.ts +457 -0
  110. package/src/project/release.ts +153 -0
  111. package/src/project/server.ts +150 -0
  112. package/src/project/terminal.ts +32 -0
  113. package/stdlib/math.ts +14 -10
  114. package/stdlib/telemetry.ts +71 -47
  115. package/types/async.d.ts +46 -40
  116. package/types/data-types.d.ts +26 -26
  117. package/types/globals.d.ts +41 -38
  118. package/types/index.d.ts +96 -51
  119. package/types/plc.d.ts +3 -4
  120. package/types/telemetry.d.ts +14 -14
  121. package/backends/codesys/config.ts +0 -54
  122. package/backends/codesys/debug.ts +0 -509
  123. package/backends/codesys/emit.ts +0 -1738
  124. package/backends/codesys/engineering.ts +0 -88
  125. package/backends/codesys/global-names.ts +0 -49
  126. package/backends/codesys/http.ts +0 -675
  127. package/backends/codesys/index.ts +0 -13
  128. package/backends/codesys/io-paths.ts +0 -105
  129. package/backends/codesys/manifest.ts +0 -312
  130. package/backends/codesys/names.ts +0 -76
  131. package/backends/codesys/numeric.ts +0 -356
  132. package/backends/codesys/plan.ts +0 -457
  133. package/backends/codesys/publication.ts +0 -59
  134. package/backends/codesys/storage.ts +0 -70
  135. package/backends/codesys/task-access.ts +0 -293
  136. package/backends/codesys/telemetry.ts +0 -593
  137. package/backends/codesys/types.ts +0 -179
  138. package/backends/codesys/vendor.ts +0 -108
  139. package/ir/aggregates.ts +0 -333
  140. package/ir/allocation.ts +0 -74
  141. package/ir/core-model.ts +0 -129
  142. package/ir/core.ts +0 -64
  143. package/ir/declarations.ts +0 -208
  144. package/ir/diagnostics.ts +0 -43
  145. package/ir/domains.ts +0 -96
  146. package/ir/index.ts +0 -8
  147. package/ir/link.ts +0 -185
  148. package/ir/model.ts +0 -346
  149. package/ir/routine.ts +0 -859
  150. package/ir/scalars.ts +0 -675
  151. package/ir/types.ts +0 -76
  152. package/project/artifacts.ts +0 -277
  153. package/project/cli.ts +0 -395
  154. package/project/index.ts +0 -1
  155. package/project/plant.ts +0 -509
  156. package/project/project.ts +0 -358
  157. package/project/server.ts +0 -113
@@ -0,0 +1,1383 @@
1
+ import ts from "typescript";
2
+ import {
3
+ instancedBlock,
4
+ error,
5
+ parseInteger,
6
+ roundFloat,
7
+ fold,
8
+ canAssign,
9
+ aggregate,
10
+ expressionIssue,
11
+ defaultValue,
12
+ placeType,
13
+ narrowRanges,
14
+ interval,
15
+ valueRange,
16
+ comparisonOperators,
17
+ type BinaryOperator,
18
+ type IntegerInterval,
19
+ type Constant,
20
+ type Expression,
21
+ type PlcFunction,
22
+ type PlcType,
23
+ type SourceSpan,
24
+ type Statement,
25
+ type Variable,
26
+ type Place,
27
+ } from "@tsplc/compiler/ir";
28
+ import type { Positions } from "./positions.ts";
29
+ import { intrinsicExpression } from "./intrinsics.ts";
30
+ import type { BlockResolver, BlockSource } from "./blocks.ts";
31
+ import type { RoutineTable } from "./routines.ts";
32
+ import {
33
+ SemanticError,
34
+ numericLiteral,
35
+ calleeName,
36
+ namedProperty,
37
+ numericLiteralType,
38
+ unparenthesized,
39
+ type Fail,
40
+ type TypeEnvironment,
41
+ type TypeResolver,
42
+ type ResolvedType,
43
+ } from "./types.ts";
44
+
45
+ type UnaryOperator = Extract<Expression, { kind: "unary" }>["operator"];
46
+ type ArrayLayout = Extract<PlcType, { kind: "array" }>;
47
+ type RecordLayout = Extract<PlcType, { kind: "record" }>;
48
+
49
+ const unaryOperators = new Map<ts.SyntaxKind, UnaryOperator>([
50
+ [ts.SyntaxKind.ExclamationToken, "not"],
51
+ [ts.SyntaxKind.MinusToken, "negate"],
52
+ [ts.SyntaxKind.TildeToken, "bitNot"],
53
+ ]);
54
+ const operators = new Map<ts.SyntaxKind, BinaryOperator>([
55
+ [ts.SyntaxKind.AmpersandAmpersandToken, "and"],
56
+ [ts.SyntaxKind.BarBarToken, "or"],
57
+ [ts.SyntaxKind.EqualsEqualsEqualsToken, "equal"],
58
+ [ts.SyntaxKind.ExclamationEqualsEqualsToken, "notEqual"],
59
+ [ts.SyntaxKind.LessThanToken, "less"],
60
+ [ts.SyntaxKind.LessThanEqualsToken, "lessEqual"],
61
+ [ts.SyntaxKind.GreaterThanToken, "greater"],
62
+ [ts.SyntaxKind.GreaterThanEqualsToken, "greaterEqual"],
63
+ [ts.SyntaxKind.PlusToken, "add"],
64
+ [ts.SyntaxKind.MinusToken, "subtract"],
65
+ [ts.SyntaxKind.AsteriskToken, "multiply"],
66
+ [ts.SyntaxKind.SlashToken, "divide"],
67
+ [ts.SyntaxKind.PercentToken, "remainder"],
68
+ [ts.SyntaxKind.AmpersandToken, "bitAnd"],
69
+ [ts.SyntaxKind.BarToken, "bitOr"],
70
+ [ts.SyntaxKind.CaretToken, "bitXor"],
71
+ [ts.SyntaxKind.LessThanLessThanToken, "shiftLeft"],
72
+ [ts.SyntaxKind.GreaterThanGreaterThanToken, "shiftRight"],
73
+ ]);
74
+
75
+ /** What every lowering scope shares with the analyzer. */
76
+ export interface AnalysisContext {
77
+ checker: ts.TypeChecker;
78
+ resolver: TypeResolver;
79
+ blocks: BlockResolver;
80
+ routines: RoutineTable;
81
+ positions: Positions;
82
+ fail: Fail;
83
+ }
84
+
85
+ /** A routine body, or the module's static initializers when `fn` is undefined. */
86
+ export interface LoweringScope {
87
+ fn: PlcFunction | undefined;
88
+ block: BlockSource | undefined;
89
+ environment: TypeEnvironment;
90
+ /** Module storage, with the routine's parameters or block fields over it. */
91
+ variables: Map<ts.Symbol, Variable>;
92
+ }
93
+
94
+ /** A call to a helper or block method, with its instance receiver if it has one. */
95
+ interface RoutineCall {
96
+ fn: PlcFunction;
97
+ arguments: Expression[];
98
+ instance?: string;
99
+ index?: Expression;
100
+ }
101
+
102
+ /**
103
+ * Lowers the expressions of one scope to the PLC model, and holds the facts
104
+ * that scope has proved so far: ranges, aliases, loop counters and copy sources.
105
+ */
106
+ export class ExpressionLowering {
107
+ private readonly checker: ts.TypeChecker;
108
+ readonly resolver: TypeResolver;
109
+ private readonly blocks: BlockResolver;
110
+ private readonly routines: RoutineTable;
111
+ readonly positions: Positions;
112
+ readonly fail: Fail;
113
+ private readonly variables: Map<ts.Symbol, Variable>;
114
+ private readonly environment: TypeEnvironment;
115
+ private readonly activeBlock: BlockSource | undefined;
116
+ private readonly activeFunction: PlcFunction | undefined;
117
+ private readonly ranges = new Map<string, IntegerInterval>();
118
+ private readonly loopCounters = new Set<string>();
119
+ private readonly aliases = new Map<ts.Symbol, Place>();
120
+ private readonly copySources: Place[] = [];
121
+
122
+ constructor(context: AnalysisContext, scope: LoweringScope) {
123
+ this.checker = context.checker;
124
+ this.resolver = context.resolver;
125
+ this.blocks = context.blocks;
126
+ this.routines = context.routines;
127
+ this.positions = context.positions;
128
+ this.fail = context.fail;
129
+ this.variables = scope.variables;
130
+ this.environment = scope.environment;
131
+ this.activeBlock = scope.block;
132
+ this.activeFunction = scope.fn;
133
+ }
134
+
135
+ /** Brings a local, loop counter or loop key into scope. */
136
+ bind(symbol: ts.Symbol, variable: Variable): void {
137
+ this.variables.set(symbol, variable);
138
+ }
139
+
140
+ /** Brings a const alias into scope; each use re-reads `place`. */
141
+ alias(symbol: ts.Symbol, place: Place): void {
142
+ this.aliases.set(symbol, place);
143
+ }
144
+
145
+ /** A const is assigned once, so its initializer's range holds wherever it is read. */
146
+ holdRange(id: string, value: Expression): void {
147
+ const bound = valueRange(
148
+ value,
149
+ this.resolver.types,
150
+ this.byId(),
151
+ this.ranges,
152
+ this.routines.instances,
153
+ );
154
+ if (bound) {
155
+ this.ranges.set(id, bound);
156
+ }
157
+ }
158
+
159
+ /** Lowers a branch with the ranges `condition` proves when it is `truth`, then restores them. */
160
+ narrowed<T>(condition: Expression, truth: boolean, lower: () => T): T {
161
+ const original = new Map(this.ranges);
162
+ this.ranges.clear();
163
+ for (const [root, range] of narrowRanges(
164
+ condition,
165
+ truth,
166
+ this.resolver.types,
167
+ this.byId(),
168
+ original,
169
+ )) {
170
+ this.ranges.set(root, range);
171
+ }
172
+ try {
173
+ return lower();
174
+ } finally {
175
+ this.ranges.clear();
176
+ for (const [root, range] of original) {
177
+ this.ranges.set(root, range);
178
+ }
179
+ }
180
+ }
181
+
182
+ /** Lowers a loop body with `counters` read-only and `counter` proved to lie in `range`. */
183
+ counting<T>(
184
+ counters: readonly string[],
185
+ counter: string,
186
+ range: IntegerInterval,
187
+ lower: () => T,
188
+ ): T {
189
+ for (const id of counters) {
190
+ this.loopCounters.add(id);
191
+ }
192
+ this.ranges.set(counter, range);
193
+ try {
194
+ return lower();
195
+ } finally {
196
+ for (const id of counters) {
197
+ this.loopCounters.delete(id);
198
+ }
199
+ this.ranges.delete(counter);
200
+ }
201
+ }
202
+
203
+ /** The range `expression` is proved to lie in, if it has one. */
204
+ interval(expression: Expression): IntegerInterval | undefined {
205
+ return interval(expression, this.resolver.types, this.byId(), this.ranges);
206
+ }
207
+
208
+ placeType(place: Place): ReturnType<typeof placeType> {
209
+ return placeType(place, this.resolver.types, this.byId(), this.ranges);
210
+ }
211
+
212
+ private writablePlaceType(place: Place): ReturnType<typeof placeType> {
213
+ return placeType(
214
+ place,
215
+ this.resolver.types,
216
+ this.byId(),
217
+ this.ranges,
218
+ true,
219
+ );
220
+ }
221
+
222
+ type(node: ts.TypeNode): ResolvedType {
223
+ return this.resolver.resolve(node, this.environment);
224
+ }
225
+
226
+ storageId(node: ts.Node, name: string): string {
227
+ return `${this.resolver.id(node, name)}${this.activeFunction ? `@${this.activeFunction.id}` : ""}`;
228
+ }
229
+
230
+ /** The scope's storage by id, including the enclosing block's inputs and outputs. */
231
+ byId(): Map<string, Variable> {
232
+ return new Map(
233
+ [
234
+ ...this.variables.values(),
235
+ ...(this.activeBlock
236
+ ? [
237
+ ...this.activeBlock.block.inputs,
238
+ ...this.activeBlock.block.outputs,
239
+ ]
240
+ : []),
241
+ ].map((variable) => [variable.id, variable]),
242
+ );
243
+ }
244
+
245
+ /** Rejects a lowered expression the model cannot hold, at the expression's own span. */
246
+ private reject(
247
+ span: SourceSpan | undefined,
248
+ code: string,
249
+ message: string,
250
+ ): never {
251
+ throw new SemanticError(error(code, message, span));
252
+ }
253
+
254
+ checked(value: Expression): Expression {
255
+ const message = expressionIssue(
256
+ value,
257
+ this.resolver.types,
258
+ this.byId(),
259
+ this.ranges,
260
+ );
261
+ if (message) {
262
+ this.reject(value.span, "PLC2002", message);
263
+ }
264
+ return value;
265
+ }
266
+
267
+ private coerce(value: Expression, destination: string): Expression {
268
+ if (value.type === destination) {
269
+ return value;
270
+ }
271
+ const source = this.resolver.types.get(value.type);
272
+ const target = this.resolver.types.get(destination);
273
+ if (!source || !target) {
274
+ this.reject(
275
+ value.span,
276
+ "PLC2001",
277
+ "This PLC type has not been resolved.",
278
+ );
279
+ }
280
+ const constant = fold(value, this.byId(), this.resolver.types);
281
+ if (
282
+ source.kind === "string" &&
283
+ target.kind === "string" &&
284
+ source.encoding === target.encoding &&
285
+ source.capacity <= target.capacity
286
+ ) {
287
+ return constant
288
+ ? {
289
+ kind: "constant",
290
+ type: destination,
291
+ value: constant,
292
+ span: value.span,
293
+ }
294
+ : {
295
+ kind: "convert",
296
+ type: destination,
297
+ operand: value,
298
+ policy: "exact",
299
+ span: value.span,
300
+ };
301
+ }
302
+ if (!canAssign(source, target, constant)) {
303
+ this.reject(
304
+ value.span,
305
+ "PLC2002",
306
+ "Use an explicit conversion between these PLC domains or widths.",
307
+ );
308
+ }
309
+ if (constant) {
310
+ return {
311
+ kind: "constant",
312
+ type: destination,
313
+ value: constant,
314
+ span: value.span,
315
+ };
316
+ }
317
+ return this.checked({
318
+ kind: "convert",
319
+ type: destination,
320
+ operand: value,
321
+ policy: "exact",
322
+ span: value.span,
323
+ });
324
+ }
325
+
326
+ constant(expression: Expression): Constant | undefined {
327
+ return fold(expression, this.byId(), this.resolver.types);
328
+ }
329
+
330
+ expression(node: ts.Expression, expected?: string): Expression {
331
+ if (
332
+ ts.isParenthesizedExpression(node) ||
333
+ ts.isSatisfiesExpression(node) ||
334
+ (ts.isAsExpression(node) && ts.isConstTypeReference(node.type))
335
+ ) {
336
+ return this.expression(node.expression, expected);
337
+ }
338
+ const literal = this.literal(node, expected);
339
+ if (literal) {
340
+ return literal;
341
+ }
342
+ const value = this.rawExpression(node, expected);
343
+ return expected ? this.coerce(value, expected) : value;
344
+ }
345
+
346
+ private rawExpression(node: ts.Expression, expected?: string): Expression {
347
+ if (
348
+ node.kind === ts.SyntaxKind.TrueKeyword ||
349
+ node.kind === ts.SyntaxKind.FalseKeyword
350
+ ) {
351
+ return {
352
+ span: this.positions.node(node),
353
+ type: "BOOL",
354
+ kind: "constant",
355
+ value: { kind: "bool", value: node.kind === ts.SyntaxKind.TrueKeyword },
356
+ };
357
+ }
358
+ if (ts.isStringLiteral(node) || ts.isNoSubstitutionTemplateLiteral(node)) {
359
+ return this.stringLiteral(node, expected);
360
+ }
361
+ if (ts.isObjectLiteralExpression(node)) {
362
+ const type = this.layout(expected);
363
+ if (type?.kind === "array" && type.index) {
364
+ return this.enumKeyedLiteral(node, type, type.index);
365
+ }
366
+ if (type?.kind !== "record") {
367
+ this.fail(
368
+ node,
369
+ "PLC2001",
370
+ "Record literals require an explicit closed PLC record type.",
371
+ );
372
+ }
373
+ return this.recordLiteral(node, type);
374
+ }
375
+ if (ts.isArrayLiteralExpression(node)) {
376
+ return this.arrayLiteral(node, expected);
377
+ }
378
+ if (ts.isPropertyAccessExpression(node)) {
379
+ const value = this.enumMember(node) ?? this.arrayLength(node);
380
+ if (value) {
381
+ return value;
382
+ }
383
+ }
384
+ if (
385
+ ts.isPropertyAccessExpression(node) ||
386
+ ts.isElementAccessExpression(node) ||
387
+ (ts.isIdentifier(node) && this.aliases.has(this.resolver.symbol(node)))
388
+ ) {
389
+ return this.placeLoad(node);
390
+ }
391
+ if (ts.isIdentifier(node)) {
392
+ return this.variableLoad(node);
393
+ }
394
+ if (ts.isPrefixUnaryExpression(node)) {
395
+ return this.unary(node, expected);
396
+ }
397
+ if (ts.isCallExpression(node)) {
398
+ return this.callExpression(node, expected);
399
+ }
400
+ if (ts.isConditionalExpression(node)) {
401
+ const then = this.expression(node.whenTrue, expected);
402
+ return {
403
+ span: this.positions.node(node),
404
+ type: then.type,
405
+ kind: "conditional",
406
+ condition: this.expression(node.condition, "BOOL"),
407
+ then,
408
+ else: this.expression(node.whenFalse, then.type),
409
+ };
410
+ }
411
+ if (ts.isBinaryExpression(node)) {
412
+ return this.binaryExpression(node, expected);
413
+ }
414
+ this.fail(
415
+ node,
416
+ "PLC1001",
417
+ `${ts.SyntaxKind[node.kind]} is not supported in PLC expressions.`,
418
+ );
419
+ }
420
+
421
+ /** The layout a literal is lowered into. */
422
+ private layout(expected: string | undefined): PlcType | undefined {
423
+ return expected ? this.resolver.types.get(expected) : undefined;
424
+ }
425
+
426
+ private literal(
427
+ node: ts.Expression,
428
+ expected?: string,
429
+ ): Expression | undefined {
430
+ const text = numericLiteral(node);
431
+ if (text === undefined) {
432
+ return undefined;
433
+ }
434
+ const type = expected ?? numericLiteralType(text);
435
+ const target = this.resolver.types.get(type);
436
+ if (!target || !["integer", "bits", "float"].includes(target.kind)) {
437
+ this.fail(
438
+ node,
439
+ "PLC2001",
440
+ "Numeric literals require an arithmetic or bit-string PLC type; use named enum members.",
441
+ );
442
+ }
443
+ return this.checked({
444
+ kind: "constant",
445
+ type,
446
+ value:
447
+ target.kind === "float"
448
+ ? floatConstant(text, target)
449
+ : this.integerConstant(node, text),
450
+ span: this.positions.node(node),
451
+ });
452
+ }
453
+
454
+ private integerConstant(node: ts.Expression, text: string): Constant {
455
+ try {
456
+ return { kind: "integer", value: String(parseInteger(text)) };
457
+ } catch (cause) {
458
+ this.fail(
459
+ node,
460
+ "PLC2002",
461
+ cause instanceof Error ? cause.message : "Invalid integer literal.",
462
+ );
463
+ }
464
+ }
465
+
466
+ private stringLiteral(
467
+ node: ts.StringLiteral | ts.NoSubstitutionTemplateLiteral,
468
+ expected: string | undefined,
469
+ ): Expression {
470
+ const span = this.positions.node(node);
471
+ const type = this.layout(expected);
472
+ if (type?.kind === "enum") {
473
+ const member = type.members.find((member) => member.name === node.text);
474
+ if (member) {
475
+ return {
476
+ span,
477
+ type: type.id,
478
+ kind: "constant",
479
+ value: { kind: "integer", value: member.value },
480
+ };
481
+ }
482
+ }
483
+ if (type?.kind !== "string") {
484
+ this.fail(
485
+ node,
486
+ "PLC2001",
487
+ "String literals require a bounded STRING or WSTRING context.",
488
+ );
489
+ }
490
+ return this.checked({
491
+ span,
492
+ type: type.id,
493
+ kind: "constant",
494
+ value: { kind: "string", value: node.text },
495
+ });
496
+ }
497
+
498
+ /** Like an array literal, every element in order, so items evaluate in source order. */
499
+ private enumKeyedLiteral(
500
+ node: ts.ObjectLiteralExpression,
501
+ type: ArrayLayout,
502
+ index: string,
503
+ ): Expression {
504
+ const order =
505
+ "Enum-keyed record literals list every enum member once, in value order.";
506
+ const items: Expression[] = [];
507
+ for (const property of node.properties) {
508
+ if (
509
+ !ts.isPropertyAssignment(property) ||
510
+ !ts.isComputedPropertyName(property.name)
511
+ ) {
512
+ this.fail(
513
+ property,
514
+ "PLC1001",
515
+ "Enum-keyed record literals use computed member keys such as [Station.A].",
516
+ );
517
+ }
518
+ const key = this.expression(property.name.expression, index);
519
+ if (
520
+ key.kind !== "constant" ||
521
+ key.type !== index ||
522
+ key.value.kind !== "integer"
523
+ ) {
524
+ this.fail(
525
+ property.name,
526
+ "PLC2001",
527
+ "Keys must be members of the record's enum.",
528
+ );
529
+ }
530
+ if (Number(key.value.value) !== type.lowerBound + items.length) {
531
+ this.fail(property, "PLC2001", order);
532
+ }
533
+ items.push(
534
+ this.implicitCopy(this.expression(property.initializer, type.element)),
535
+ );
536
+ }
537
+ if (items.length !== type.length) {
538
+ this.fail(node, "PLC2001", order);
539
+ }
540
+ return this.checked({
541
+ span: this.positions.node(node),
542
+ type: type.id,
543
+ kind: "array",
544
+ items,
545
+ });
546
+ }
547
+
548
+ private recordLiteral(
549
+ node: ts.ObjectLiteralExpression,
550
+ type: RecordLayout,
551
+ ): Expression {
552
+ const span = this.positions.node(node);
553
+ const fields: Record<string, Expression> = Object.create(null);
554
+ const written = new Set<string>();
555
+ for (const [position, property] of node.properties.entries()) {
556
+ if (ts.isSpreadAssignment(property) && !position) {
557
+ for (const [field, value] of this.spreadFields(
558
+ property.expression,
559
+ type.fields,
560
+ )) {
561
+ // TypeScript's spread shares a nested record or array, so a later write to it diverges.
562
+ this.recordCopySource(value);
563
+ fields[field.name] = this.implicitCopy(value);
564
+ }
565
+ continue;
566
+ }
567
+ const named = namedProperty(property);
568
+ if (!named) {
569
+ this.fail(
570
+ property,
571
+ "PLC1001",
572
+ "Record literals take named fields after at most one leading spread; methods are unsupported.",
573
+ );
574
+ }
575
+ const field = type.fields.find((field) => field.name === named.name);
576
+ if (!field || written.has(field.name)) {
577
+ this.fail(property, "PLC2001", "Unknown or duplicate record field.");
578
+ }
579
+ written.add(field.name);
580
+ // An explicit field overrides the spread and keeps its source evaluation order.
581
+ delete fields[field.name];
582
+ fields[field.name] = this.implicitCopy(
583
+ this.expression(named.value, field.type),
584
+ );
585
+ }
586
+ if (this.resolver.unions.has(type.id)) {
587
+ for (const field of type.fields) {
588
+ if (!Object.hasOwn(fields, field.name)) {
589
+ fields[field.name] = {
590
+ span,
591
+ type: field.type,
592
+ kind: "constant",
593
+ value: defaultValue(field.type, this.resolver.types),
594
+ };
595
+ }
596
+ }
597
+ }
598
+ return this.checked({ span, type: type.id, kind: "record", fields });
599
+ }
600
+
601
+ private arrayLiteral(
602
+ node: ts.ArrayLiteralExpression,
603
+ expected: string | undefined,
604
+ ): Expression {
605
+ const type = this.layout(expected);
606
+ if (type?.kind !== "array") {
607
+ this.fail(
608
+ node,
609
+ "PLC2001",
610
+ "Array literals require an explicit FixedArray type.",
611
+ );
612
+ }
613
+ const items = node.elements.map((element) => {
614
+ if (ts.isOmittedExpression(element) || ts.isSpreadElement(element)) {
615
+ this.fail(
616
+ element,
617
+ "PLC1001",
618
+ "Fixed arrays cannot have holes or spreading.",
619
+ );
620
+ }
621
+ return this.implicitCopy(this.expression(element, type.element));
622
+ });
623
+ return this.checked({
624
+ span: this.positions.node(node),
625
+ type: type.id,
626
+ kind: "array",
627
+ items,
628
+ });
629
+ }
630
+
631
+ private enumMember(
632
+ node: ts.PropertyAccessExpression,
633
+ ): Expression | undefined {
634
+ const declaration = this.resolver
635
+ .symbol(node.name)
636
+ .declarations?.find(ts.isEnumMember);
637
+ if (!declaration) {
638
+ return undefined;
639
+ }
640
+ const type = this.resolver.enumeration(declaration.parent).type;
641
+ const layout = this.resolver.types.get(type);
642
+ if (layout?.kind !== "enum") {
643
+ this.fail(node, "PLC2001", "Invalid enum layout.");
644
+ }
645
+ return {
646
+ span: this.positions.node(node),
647
+ type,
648
+ kind: "constant",
649
+ value: {
650
+ kind: "integer",
651
+ value: layout.members.find(
652
+ (member) => member.name === declaration.name.getText(),
653
+ )!.value,
654
+ },
655
+ };
656
+ }
657
+
658
+ private arrayLength(
659
+ node: ts.PropertyAccessExpression,
660
+ ): Expression | undefined {
661
+ // A module global named length, read through its namespace import, is storage, not an array's length.
662
+ if (
663
+ node.name.text !== "length" ||
664
+ this.variables.has(this.resolver.symbol(node.name))
665
+ ) {
666
+ return undefined;
667
+ }
668
+ const base = this.expression(node.expression);
669
+ const type = this.resolver.types.get(base.type);
670
+ return type?.kind === "array"
671
+ ? {
672
+ span: this.positions.node(node),
673
+ type: "DINT",
674
+ kind: "length",
675
+ operand: base,
676
+ }
677
+ : undefined;
678
+ }
679
+
680
+ private placeLoad(node: ts.Expression): Expression {
681
+ const span = this.positions.node(node);
682
+ const place = this.place(node);
683
+ const { type, issue } = this.placeType(place);
684
+ if (issue || !type) {
685
+ this.fail(node, "PLC2001", issue ?? "Invalid PLC place.");
686
+ }
687
+ return { span, type, kind: "load", place };
688
+ }
689
+
690
+ private variableLoad(node: ts.Identifier): Expression {
691
+ const variable = this.variables.get(this.resolver.symbol(node));
692
+ if (!variable) {
693
+ this.fail(node, "PLC1002", "This value has no supported PLC storage.");
694
+ }
695
+ if (variable.type === "inferred") {
696
+ this.fail(
697
+ node,
698
+ "PLC3001",
699
+ "Resolve constant initializer dependencies in declaration order.",
700
+ );
701
+ }
702
+ return {
703
+ span: this.positions.node(node),
704
+ type: variable.type,
705
+ kind: "load",
706
+ place: { root: variable.id, path: [] },
707
+ };
708
+ }
709
+
710
+ private unary(
711
+ node: ts.PrefixUnaryExpression,
712
+ expected: string | undefined,
713
+ ): Expression {
714
+ const operator = unaryOperators.get(node.operator);
715
+ if (!operator) {
716
+ this.fail(node, "PLC2001", "Unsupported unary operation.");
717
+ }
718
+ const operand = this.expression(
719
+ node.operand,
720
+ operator === "not" ? "BOOL" : expected,
721
+ );
722
+ return this.checked({
723
+ span: this.positions.node(node),
724
+ type: operator === "not" ? "BOOL" : operand.type,
725
+ kind: "unary",
726
+ operator,
727
+ operand,
728
+ });
729
+ }
730
+
731
+ private callExpression(
732
+ node: ts.CallExpression,
733
+ expected: string | undefined,
734
+ ): Expression {
735
+ const intrinsic = intrinsicExpression(this, node, expected);
736
+ if (intrinsic) {
737
+ return intrinsic;
738
+ }
739
+ const call = this.call(node);
740
+ if (!call.fn.result) {
741
+ this.fail(
742
+ node,
743
+ "PLC2001",
744
+ "A void helper cannot produce an expression value.",
745
+ );
746
+ }
747
+ return {
748
+ span: this.positions.node(node),
749
+ type: call.fn.result,
750
+ kind: "call",
751
+ function: call.fn.id,
752
+ arguments: call.arguments,
753
+ ...(call.instance && { instance: call.instance }),
754
+ ...(call.index && { index: call.index }),
755
+ };
756
+ }
757
+
758
+ private binaryExpression(
759
+ node: ts.BinaryExpression,
760
+ expected?: string,
761
+ ): Expression {
762
+ const span = this.positions.node(node);
763
+ const operator = operators.get(node.operatorToken.kind);
764
+ if (!operator) {
765
+ this.fail(
766
+ node.operatorToken,
767
+ "PLC2001",
768
+ "Unsupported binary operation; implicit coercion is prohibited.",
769
+ );
770
+ }
771
+ const logical = operator === "and" || operator === "or";
772
+ const comparison = comparisonOperators.has(operator);
773
+ const left = this.leftOperand(node, operator, expected);
774
+ const right = this.expression(
775
+ node.right,
776
+ operator === "shiftLeft" || operator === "shiftRight"
777
+ ? "DINT"
778
+ : left.type,
779
+ );
780
+ if (
781
+ operator === "divide" &&
782
+ this.resolver.types.get(left.type)?.kind !== "float"
783
+ ) {
784
+ this.fail(
785
+ node,
786
+ "PLC2002",
787
+ "Use div<T>() for truncating integer division.",
788
+ );
789
+ }
790
+ return this.checked({
791
+ span,
792
+ type: logical || comparison ? "BOOL" : left.type,
793
+ kind: "binary",
794
+ operator,
795
+ left,
796
+ right,
797
+ });
798
+ }
799
+
800
+ /**
801
+ * The left operand in the type the operation works in: BOOL for logic, the right
802
+ * operand's type when a literal is compared to it, and the wider side of any other
803
+ * comparison. The right operand then takes the left's type.
804
+ */
805
+ private leftOperand(
806
+ node: ts.BinaryExpression,
807
+ operator: BinaryOperator,
808
+ expected: string | undefined,
809
+ ): Expression {
810
+ if (operator === "and" || operator === "or") {
811
+ return this.expression(node.left, "BOOL");
812
+ }
813
+ if (!comparisonOperators.has(operator)) {
814
+ return this.expression(node.left, expected);
815
+ }
816
+ if (contextualLiteral(node.left)) {
817
+ return this.expression(node.left, this.expression(node.right).type);
818
+ }
819
+ const left = this.expression(node.left);
820
+ if (contextualLiteral(node.right)) {
821
+ return left;
822
+ }
823
+ // Compare at the wider type; widening cannot change the value.
824
+ const wider = this.expression(node.right).type;
825
+ const from = this.resolver.types.get(left.type);
826
+ const to = this.resolver.types.get(wider);
827
+ return from && to && !canAssign(to, from) && canAssign(from, to)
828
+ ? this.coerce(left, wider)
829
+ : left;
830
+ }
831
+
832
+ sdkCall(node: ts.CallExpression): string | undefined {
833
+ const name = calleeName(node.expression);
834
+ return name && this.resolver.sdkName(name);
835
+ }
836
+
837
+ /** `instance.update({ ... })` with every block input bound, or undefined for any other call. */
838
+ update(node: ts.CallExpression): Statement | undefined {
839
+ if (
840
+ !ts.isPropertyAccessExpression(node.expression) ||
841
+ node.expression.name.text !== "update"
842
+ ) {
843
+ return undefined;
844
+ }
845
+ const receiver = this.blockReceiver(node.expression.expression);
846
+ if (!receiver.block || !receiver.selected) {
847
+ this.fail(
848
+ node,
849
+ "PLC1007",
850
+ "Update requires a static block instance binding.",
851
+ );
852
+ }
853
+ const definition = this.blocks.definitions.get(receiver.block)!;
854
+ const [record, ...rest] = node.arguments;
855
+ if (
856
+ node.typeArguments?.length ||
857
+ !record ||
858
+ rest.length ||
859
+ !ts.isObjectLiteralExpression(record)
860
+ ) {
861
+ this.fail(
862
+ node,
863
+ "PLC2001",
864
+ "Block update requires one complete named input record.",
865
+ );
866
+ }
867
+ const inputs: Record<string, Expression> = Object.create(null);
868
+ const written = new Set<string>();
869
+ for (const [position, property] of record.properties.entries()) {
870
+ if (ts.isSpreadAssignment(property) && !position) {
871
+ for (const [parameter, value] of this.spreadFields(
872
+ property.expression,
873
+ definition.inputs,
874
+ )) {
875
+ inputs[parameter.name] =
876
+ parameter.mode === "inOut"
877
+ ? this.reference(value, parameter)
878
+ : value;
879
+ }
880
+ continue;
881
+ }
882
+ const named = namedProperty(property);
883
+ if (!named) {
884
+ this.fail(
885
+ property,
886
+ "PLC2001",
887
+ "Block inputs are named fields after at most one leading spread.",
888
+ );
889
+ }
890
+ const parameter = definition.inputs.find(
891
+ (input) => input.name === named.name,
892
+ );
893
+ if (!parameter || written.has(parameter.name)) {
894
+ this.fail(property, "PLC2001", "Unknown or duplicate block input.");
895
+ }
896
+ written.add(parameter.name);
897
+ delete inputs[parameter.name];
898
+ inputs[parameter.name] = this.inputArgument(named.value, parameter);
899
+ }
900
+ if (definition.inputs.some((input) => !Object.hasOwn(inputs, input.name))) {
901
+ this.fail(
902
+ node,
903
+ "PLC2001",
904
+ "Block update must bind every input on each call.",
905
+ );
906
+ }
907
+ return {
908
+ kind: "blockUpdate",
909
+ instance: receiver.place.root,
910
+ ...(receiver.index && { index: receiver.index }),
911
+ inputs,
912
+ span: this.positions.node(node),
913
+ };
914
+ }
915
+
916
+ /** The block instance a receiver names: a static instance, or one element of an instance array. */
917
+ private blockReceiver(node: ts.Expression) {
918
+ const place = this.place(node);
919
+ const variable = this.byId().get(place.root);
920
+ const [selector, ...rest] = place.path;
921
+ const index = selector?.kind === "index" ? selector.value : undefined;
922
+ const array =
923
+ variable !== undefined &&
924
+ this.resolver.types.get(variable.type)?.kind === "array";
925
+ return {
926
+ place,
927
+ variable,
928
+ block:
929
+ variable && instancedBlock(variable.type, this.resolver.types)?.block,
930
+ index,
931
+ // An instance is named bare, and an instance array element by one index.
932
+ selected: !rest.length && (array ? Boolean(index) : !selector),
933
+ };
934
+ }
935
+
936
+ call(node: ts.CallExpression): RoutineCall {
937
+ const name = calleeName(node.expression);
938
+ if (!name) {
939
+ this.fail(
940
+ node,
941
+ "PLC1001",
942
+ "Call a statically resolved PLC helper or block method.",
943
+ );
944
+ }
945
+ const symbol = this.resolver.symbol(name);
946
+ // Structural return types can give a receiver a transient property symbol.
947
+ // Resolve its declaration back to the canonical instance method identity.
948
+ const method =
949
+ this.routines.methods.get(symbol) ??
950
+ symbol.declarations
951
+ ?.filter(ts.isMethodDeclaration)
952
+ .map((node) =>
953
+ this.routines.methods.get(this.resolver.symbol(node.name)),
954
+ )
955
+ .find((fn) => fn !== undefined);
956
+ if (method) {
957
+ return this.methodCall(node, method);
958
+ }
959
+ const declaration = this.routines.functionDeclarations.get(symbol);
960
+ if (!declaration) {
961
+ this.fail(
962
+ node,
963
+ "PLC1001",
964
+ "Calls require PLC TypeScript implementation source.",
965
+ );
966
+ }
967
+ const fn = declaration.typeParameters?.length
968
+ ? this.routines.instantiate(
969
+ declaration,
970
+ node.typeArguments ?? [],
971
+ node,
972
+ this.environment,
973
+ )
974
+ : this.routines.functions.get(symbol);
975
+ if (
976
+ !fn ||
977
+ (!declaration.typeParameters?.length && node.typeArguments?.length)
978
+ ) {
979
+ this.fail(node, "PLC2001", "Type arguments require a generic helper.");
980
+ }
981
+ return { fn, arguments: this.callArguments(node, fn) };
982
+ }
983
+
984
+ private methodCall(
985
+ node: ts.CallExpression,
986
+ method: PlcFunction,
987
+ ): RoutineCall {
988
+ if (
989
+ !ts.isPropertyAccessExpression(node.expression) ||
990
+ node.typeArguments?.length
991
+ ) {
992
+ this.fail(node, "PLC1007", "Methods require a static instance receiver.");
993
+ }
994
+ const receiver = node.expression.expression;
995
+ if (receiver.kind === ts.SyntaxKind.ThisKeyword) {
996
+ if (method.owner?.block !== this.activeBlock?.block.id) {
997
+ this.fail(
998
+ node,
999
+ "PLC1007",
1000
+ "Method receiver differs from the enclosing block.",
1001
+ );
1002
+ }
1003
+ return { fn: method, arguments: this.callArguments(node, method) };
1004
+ }
1005
+ const instance = this.blockReceiver(receiver);
1006
+ if (
1007
+ (instance.variable?.storage !== "instance" &&
1008
+ instance.variable?.mode !== "inOut") ||
1009
+ !instance.selected ||
1010
+ instance.block !== method.owner?.block
1011
+ ) {
1012
+ this.fail(
1013
+ node,
1014
+ "PLC1007",
1015
+ "Methods require a matching static block instance.",
1016
+ );
1017
+ }
1018
+ if (
1019
+ method.owner?.access !== "public" &&
1020
+ method.owner?.block !== this.activeBlock?.block.id
1021
+ ) {
1022
+ this.fail(
1023
+ node,
1024
+ "PLC1007",
1025
+ "Private and protected methods are only accessible within their block.",
1026
+ );
1027
+ }
1028
+ return {
1029
+ fn: method,
1030
+ arguments: this.callArguments(node, method),
1031
+ instance: instance.place.root,
1032
+ ...(instance.index && { index: instance.index }),
1033
+ };
1034
+ }
1035
+
1036
+ private callArguments(
1037
+ node: ts.CallExpression,
1038
+ fn: PlcFunction,
1039
+ ): Expression[] {
1040
+ if (node.arguments.length !== fn.parameters.length) {
1041
+ this.fail(
1042
+ node,
1043
+ "PLC2001",
1044
+ "PLC argument count differs from its signature.",
1045
+ );
1046
+ }
1047
+ return fn.parameters.map((parameter, index) =>
1048
+ this.inputArgument(node.arguments[index]!, parameter),
1049
+ );
1050
+ }
1051
+
1052
+ private inputArgument(value: ts.Expression, parameter: Variable): Expression {
1053
+ if (parameter.mode !== "inOut") {
1054
+ return this.expression(value, parameter.type);
1055
+ }
1056
+ if (ts.isCallExpression(value) && this.sdkCall(value) === "ref") {
1057
+ const [borrowed, ...rest] = value.arguments;
1058
+ if (!borrowed || rest.length || value.typeArguments?.length) {
1059
+ this.fail(value, "PLC3003", "ref takes one place.");
1060
+ }
1061
+ const target = this.target(borrowed);
1062
+ if (target.type !== parameter.type) {
1063
+ this.fail(
1064
+ value,
1065
+ "PLC2001",
1066
+ "Borrowed place type must exactly match its InOut parameter.",
1067
+ );
1068
+ }
1069
+ return {
1070
+ kind: "borrow",
1071
+ place: target.place,
1072
+ type: target.type,
1073
+ span: this.positions.node(value),
1074
+ };
1075
+ }
1076
+ if (this.resolver.types.get(parameter.type)?.kind === "block") {
1077
+ const place = this.place(value);
1078
+ if (this.placeType(place).type !== parameter.type) {
1079
+ this.fail(
1080
+ value,
1081
+ "PLC2001",
1082
+ "Pass a block instance of the parameter's type.",
1083
+ );
1084
+ }
1085
+ return {
1086
+ kind: "borrow",
1087
+ place,
1088
+ type: parameter.type,
1089
+ span: this.positions.node(value),
1090
+ };
1091
+ }
1092
+ return this.reference(this.expression(value, parameter.type), parameter);
1093
+ }
1094
+
1095
+ /**
1096
+ * An aggregate InOut argument borrows its place; a value with no writable address reaches
1097
+ * the callee through a compiler temporary.
1098
+ */
1099
+ private reference(argument: Expression, parameter: Variable): Expression {
1100
+ if (!aggregate(this.resolver.types.get(parameter.type))) {
1101
+ this.reject(
1102
+ argument.span,
1103
+ "PLC3003",
1104
+ "Scalar InOut arguments require a direct ref(place) borrow.",
1105
+ );
1106
+ }
1107
+ return argument.kind === "load" &&
1108
+ !this.loopCounters.has(argument.place.root) &&
1109
+ !this.writablePlaceType(argument.place).issue
1110
+ ? {
1111
+ kind: "borrow",
1112
+ place: argument.place,
1113
+ type: argument.type,
1114
+ span: argument.span,
1115
+ }
1116
+ : this.implicitCopy(argument);
1117
+ }
1118
+
1119
+ /**
1120
+ * The fields `{ ...base }` supplies, each with the target it fills: base is a record whose
1121
+ * fields are all target fields of the same type. A stored base is read field by field;
1122
+ * `defaultValue<T>()` gives constants.
1123
+ */
1124
+ private spreadFields<Target extends { name: string; type: string }>(
1125
+ node: ts.Expression,
1126
+ targets: readonly Target[],
1127
+ ): [Target, Expression][] {
1128
+ const spread = this.expression(node);
1129
+ const layout = this.resolver.types.get(spread.type);
1130
+ const filled: [Target, string][] = [];
1131
+ for (const field of layout?.kind === "record" ? layout.fields : []) {
1132
+ const target = targets.find((target) => target.name === field.name);
1133
+ if (target?.type !== field.type) {
1134
+ break;
1135
+ }
1136
+ filled.push([target, field.name]);
1137
+ }
1138
+ if (layout?.kind !== "record" || filled.length !== layout.fields.length) {
1139
+ this.fail(
1140
+ node,
1141
+ "PLC2001",
1142
+ "A spread is a record whose fields are all fields of the target, with the same types.",
1143
+ );
1144
+ }
1145
+ // Static initializers run before any scan, so a stored base contributes its initial value.
1146
+ const initial =
1147
+ !this.activeFunction &&
1148
+ spread.kind === "load" &&
1149
+ !spread.place.path.length
1150
+ ? this.byId().get(spread.place.root)?.initial
1151
+ : undefined;
1152
+ const base: Expression = initial
1153
+ ? { ...spread, kind: "constant", value: initial }
1154
+ : spread;
1155
+ if (base.kind === "load") {
1156
+ const { place } = base;
1157
+ return filled.map(([target, name]) => [
1158
+ target,
1159
+ {
1160
+ kind: "load",
1161
+ type: target.type,
1162
+ place: {
1163
+ root: place.root,
1164
+ path: [...place.path, { kind: "field", name }],
1165
+ },
1166
+ span: base.span,
1167
+ },
1168
+ ]);
1169
+ }
1170
+ if (base.kind !== "constant" || base.value.kind !== "record") {
1171
+ this.fail(
1172
+ node,
1173
+ "PLC1001",
1174
+ "Spread a record in storage or defaultValue<T>(); bind other values to a const first.",
1175
+ );
1176
+ }
1177
+ const { value } = base;
1178
+ return filled.map(([target, name]) => [
1179
+ target,
1180
+ {
1181
+ kind: "constant",
1182
+ type: target.type,
1183
+ value: value.fields[name]!,
1184
+ span: base.span,
1185
+ },
1186
+ ]);
1187
+ }
1188
+
1189
+ /** A record or array assigned into storage copies: fixed storage cannot repoint at its source. */
1190
+ implicitCopy(value: Expression): Expression {
1191
+ if (instancedBlock(value.type, this.resolver.types)) {
1192
+ this.reject(
1193
+ value.span,
1194
+ "PLC3003",
1195
+ "Block instances cannot be copied, aliased or returned.",
1196
+ );
1197
+ }
1198
+ return aggregate(this.resolver.types.get(value.type)) &&
1199
+ value.kind === "load"
1200
+ ? { kind: "copy", type: value.type, operand: value, span: value.span }
1201
+ : value;
1202
+ }
1203
+
1204
+ /** Remember a copied source, so a later write to it in this routine cannot silently diverge. */
1205
+ recordCopySource(value: Expression): void {
1206
+ if (
1207
+ value.kind === "load" &&
1208
+ aggregate(this.resolver.types.get(value.type))
1209
+ ) {
1210
+ this.copySources.push(value.place);
1211
+ }
1212
+ }
1213
+
1214
+ /** An alias re-reads its path at each use, so its indexes must keep their value for its scope. */
1215
+ unchanging(value: Expression): boolean {
1216
+ if (value.kind === "constant") {
1217
+ return true;
1218
+ }
1219
+ if (value.kind === "convert") {
1220
+ return this.unchanging(value.operand);
1221
+ }
1222
+ if (value.kind === "binary") {
1223
+ return this.unchanging(value.left) && this.unchanging(value.right);
1224
+ }
1225
+ if (value.kind !== "load" || value.place.path.length) {
1226
+ return false;
1227
+ }
1228
+ const root = this.byId().get(value.place.root);
1229
+ return (
1230
+ this.loopCounters.has(value.place.root) ||
1231
+ Boolean(
1232
+ root &&
1233
+ !root.mutable &&
1234
+ ["parameter", "local", "constant"].includes(root.storage),
1235
+ )
1236
+ );
1237
+ }
1238
+
1239
+ place(node: ts.Expression): Place {
1240
+ if (ts.isParenthesizedExpression(node)) {
1241
+ return this.place(node.expression);
1242
+ }
1243
+ if (this.activeBlock && ts.isPropertyAccessExpression(node)) {
1244
+ if (
1245
+ ts.isIdentifier(node.expression) &&
1246
+ this.resolver.symbol(node.expression) === this.activeBlock.inputSymbol
1247
+ ) {
1248
+ const variable = this.activeBlock.inputBindings.get(node.name.text);
1249
+ if (!variable) {
1250
+ this.fail(node, "PLC2001", "Unknown block input field.");
1251
+ }
1252
+ return { root: variable.id, path: [] };
1253
+ }
1254
+ if (
1255
+ ts.isPropertyAccessExpression(node.expression) &&
1256
+ node.expression.expression.kind === ts.SyntaxKind.ThisKeyword &&
1257
+ node.expression.name.text === "out"
1258
+ ) {
1259
+ const variable = this.activeBlock.block.outputs.find(
1260
+ (output) => output.name === node.name.text,
1261
+ );
1262
+ if (!variable) {
1263
+ this.fail(node, "PLC2001", "Unknown block output field.");
1264
+ }
1265
+ return { root: variable.id, path: [] };
1266
+ }
1267
+ }
1268
+ if (
1269
+ ts.isPropertyAccessExpression(node) &&
1270
+ this.activeBlock?.fieldBindings.has(this.resolver.symbol(node.name)) &&
1271
+ node.expression.kind !== ts.SyntaxKind.ThisKeyword
1272
+ ) {
1273
+ this.fail(
1274
+ node,
1275
+ "PLC1007",
1276
+ "Private block state is accessible through this.field only.",
1277
+ );
1278
+ }
1279
+ if (ts.isIdentifier(node)) {
1280
+ const alias = this.aliases.get(this.resolver.symbol(node));
1281
+ if (alias) {
1282
+ return alias;
1283
+ }
1284
+ }
1285
+ if (ts.isIdentifier(node) || ts.isPropertyAccessExpression(node)) {
1286
+ const variable = this.variables.get(
1287
+ this.resolver.symbol(ts.isIdentifier(node) ? node : node.name),
1288
+ );
1289
+ if (variable) {
1290
+ return { root: variable.id, path: [] };
1291
+ }
1292
+ }
1293
+ if (ts.isPropertyAccessExpression(node)) {
1294
+ const base = this.place(node.expression);
1295
+ return {
1296
+ root: base.root,
1297
+ path: [...base.path, { kind: "field", name: node.name.text }],
1298
+ };
1299
+ }
1300
+ if (ts.isElementAccessExpression(node) && node.argumentExpression) {
1301
+ const base = this.place(node.expression);
1302
+ const value = this.expression(node.argumentExpression);
1303
+ const baseType = this.placeType(base).type;
1304
+ const array =
1305
+ baseType === undefined ? undefined : this.resolver.types.get(baseType);
1306
+ if (
1307
+ array?.kind === "array" &&
1308
+ array.index &&
1309
+ value.type !== array.index
1310
+ ) {
1311
+ this.fail(
1312
+ node,
1313
+ "PLC2001",
1314
+ "An enum-keyed record is indexed only by its own enum.",
1315
+ );
1316
+ }
1317
+ return {
1318
+ root: base.root,
1319
+ path: [...base.path, { kind: "index", value }],
1320
+ };
1321
+ }
1322
+ this.fail(
1323
+ node,
1324
+ "PLC1001",
1325
+ "Access requires statically allocated PLC storage.",
1326
+ );
1327
+ }
1328
+
1329
+ target(node: ts.Expression): { place: Place; type: string } {
1330
+ if (ts.isIdentifier(node)) {
1331
+ const binding = this.checker.getSymbolAtLocation(node);
1332
+ if (binding && binding.flags & ts.SymbolFlags.Alias) {
1333
+ this.fail(node, "PLC3002", "Imported scalar bindings are read-only.");
1334
+ }
1335
+ }
1336
+ const place = this.place(node);
1337
+ const { type, issue } = this.writablePlaceType(place);
1338
+ if (issue || !type || this.loopCounters.has(place.root)) {
1339
+ this.fail(node, "PLC3002", issue ?? "This PLC storage is read-only.");
1340
+ }
1341
+ const overlaps = (source: Place) =>
1342
+ source.root === place.root &&
1343
+ source.path.every((segment, index) => {
1344
+ const other = place.path[index];
1345
+ return (
1346
+ !other ||
1347
+ segment.kind !== "field" ||
1348
+ other.kind !== "field" ||
1349
+ segment.name === other.name
1350
+ );
1351
+ });
1352
+ if (this.copySources.some(overlaps)) {
1353
+ this.fail(
1354
+ node,
1355
+ "PLC3003",
1356
+ "This value was assigned into other storage, which holds a copy, so this write will not reach it. Assign it afterwards, or use copy(value) if separate values are intended.",
1357
+ );
1358
+ }
1359
+ return { place, type };
1360
+ }
1361
+ }
1362
+
1363
+ /** A float literal rounds to its PLC type's width. */
1364
+ function floatConstant(
1365
+ text: string,
1366
+ type: Extract<PlcType, { kind: "float" }>,
1367
+ ): Constant {
1368
+ const clean = text.replaceAll("_", "");
1369
+ const number = /^-?0[xob]/i.test(clean)
1370
+ ? Number(parseInteger(clean))
1371
+ : Number(clean);
1372
+ return { kind: "float", value: roundFloat(number, type) };
1373
+ }
1374
+
1375
+ /** A literal whose type comes from the other side of a comparison. */
1376
+ function contextualLiteral(node: ts.Expression): boolean {
1377
+ const inner = unparenthesized(node);
1378
+ return (
1379
+ numericLiteral(inner) !== undefined ||
1380
+ ts.isStringLiteral(inner) ||
1381
+ ts.isNoSubstitutionTemplateLiteral(inner)
1382
+ );
1383
+ }