@tsplc/compiler 0.2.12 → 0.2.14

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.
package/package.json CHANGED
@@ -17,7 +17,7 @@
17
17
  "url": "git+https://github.com/livingforjesus/tsplc.git",
18
18
  "directory": "packages/compiler"
19
19
  },
20
- "version": "0.2.12",
20
+ "version": "0.2.14",
21
21
  "type": "module",
22
22
  "exports": {
23
23
  ".": {
@@ -90,14 +90,14 @@
90
90
  "bun": ">=1.4.3"
91
91
  },
92
92
  "dependencies": {
93
- "@tsplc/agent": "0.2.12",
94
- "@tsplc/build": "0.2.12",
95
- "@tsplc/config": "0.2.12",
96
- "@tsplc/typegen": "0.2.12",
93
+ "@tsplc/agent": "0.2.14",
94
+ "@tsplc/build": "0.2.14",
95
+ "@tsplc/config": "0.2.14",
96
+ "@tsplc/typegen": "0.2.14",
97
97
  "typescript": "6.0.3",
98
98
  "zod": "4.3.6",
99
99
  "@types/bun": "1.4.2",
100
- "@tsplc/server": "0.2.12"
100
+ "@tsplc/server": "0.2.14"
101
101
  },
102
102
  "bin": {
103
103
  "tsplc": "./dist/cli.js"
package/project/plant.ts CHANGED
@@ -286,9 +286,14 @@ const deploy = async (
286
286
  }
287
287
  };
288
288
 
289
- /** Opens a login when none is open; it stays open across commands until `tsplc logout`. */
289
+ /** Opens a login when none is working; it stays open across commands until `tsplc logout`. */
290
290
  const ensureLogin = async (agent: AgentClient) => {
291
- if ((await agent.status()).login) return;
291
+ const { login } = await agent.status();
292
+ if (login && "state" in login) return;
293
+ if (login) {
294
+ console.log(`The open login failed (${login.error}); replacing it.`);
295
+ await agent.logout();
296
+ }
292
297
  const credentials = await askCredentials();
293
298
  console.log(
294
299
  "Logging in. CODESYS takes a few minutes to start; the login stays open until tsplc logout.",
@@ -378,9 +383,13 @@ export const runPlantCommand = async (
378
383
  console.log(
379
384
  `Server ${status.server ? `${status.server.running ? "running" : "restarting"} (${status.server.executable})` : "none"}`,
380
385
  );
381
- console.log(
382
- `Login ${status.login ? `open; application ${status.login.state}${status.login.forced.length ? `; forced: ${status.login.forced.join(", ")}` : ""}` : "closed"}`,
383
- );
386
+ const { login } = status;
387
+ if (!login) console.log("Login closed");
388
+ else if ("error" in login) console.log(`Login failed: ${login.error} (tsplc logout)`);
389
+ else
390
+ console.log(
391
+ `Login open; application ${login.state}${login.forced.length ? `; forced: ${login.forced.join(", ")}` : ""}`,
392
+ );
384
393
  return;
385
394
  }
386
395
  case "login":
@@ -390,7 +399,8 @@ export const runPlantCommand = async (
390
399
  return;
391
400
  case "logout": {
392
401
  expect(0, "");
393
- const forced = (await agent.status()).login?.forced ?? [];
402
+ const { login } = await agent.status();
403
+ const forced = login && "forced" in login ? login.forced : [];
394
404
  if (
395
405
  forced.length &&
396
406
  !(await confirm(
@@ -256,6 +256,16 @@ export class Layouts {
256
256
  return this.text(type, value, hint);
257
257
  }
258
258
 
259
+ /** A record field's layout, with the lengths setup gave its arrays. */
260
+ fieldText(property: ts.Symbol): string {
261
+ return this.declaredText(
262
+ property.valueDeclaration,
263
+ this.checker.getTypeOfSymbol(property),
264
+ this.fieldSample(property),
265
+ pascal(property.name),
266
+ );
267
+ }
268
+
259
269
  /** A captured value of a field, from any captured record that has it. */
260
270
  private fieldSample(property: ts.Symbol): CapturedValue | undefined {
261
271
  for (const node of this.model.nodes) {
@@ -29,6 +29,8 @@ export type Value =
29
29
  iec?: string;
30
30
  /** For an array place, the IEC width its declaration gives its elements, as `Array<BYTE>` does. */
31
31
  elementIec?: string;
32
+ /** For an array place, its layout with the length setup gave it, such as `FixedArray<BYTE, 32>`. */
33
+ layout?: string;
32
34
  /** A module global another module stores into through its setter; an import is read-only. */
33
35
  setter?: string;
34
36
  };
@@ -678,10 +680,12 @@ export class Specializer {
678
680
  if (arg.kind === "code" || (arg.kind === "virtual" && !this.isKnownShape(arg))) {
679
681
  const local = frame.emitter.local(name.text);
680
682
  const iec = this.layouts.iecName(name.parent);
681
- parameters.push(`${local}: ${iec ?? this.layouts.text(declared)}`);
683
+ // An array parameter takes the length of the storage passed to it, which its type doesn't name.
684
+ const layout = arg.kind === "code" ? arg.layout : undefined;
685
+ parameters.push(`${local}: ${iec ?? layout ?? this.layouts.text(declared)}`);
682
686
  runtimeArgs.push(this.assignmentText(arg, declared, frame, iec));
683
- frame.env.set(symbol, { kind: "code", text: local, declared, place: true });
684
- keys.push(`${name.text}=code`);
687
+ frame.env.set(symbol, { kind: "code", text: local, declared, place: true, layout });
688
+ keys.push(`${name.text}=code${layout ? `:${layout}` : ""}`);
685
689
  return;
686
690
  }
687
691
  if (
@@ -779,10 +783,14 @@ export class Specializer {
779
783
  this.switch(node, frame);
780
784
  return;
781
785
  }
782
- if (ts.isForStatement(node) || ts.isWhileStatement(node)) {
786
+ if (ts.isForStatement(node)) {
787
+ this.forLoop(node, frame);
788
+ return;
789
+ }
790
+ if (ts.isWhileStatement(node)) {
783
791
  throw new SpecializeError(
784
792
  node,
785
- "Use for…of over an array; counted and while loops are not lowered yet.",
793
+ "Use a counted for loop or for…of; while loops have no bound to prove.",
786
794
  );
787
795
  }
788
796
  if (ts.isTryStatement(node)) {
@@ -917,6 +925,19 @@ export class Specializer {
917
925
  }
918
926
 
919
927
  private forOf(node: ts.ForOfStatement, frame: Frame): void {
928
+ const call = node.expression;
929
+ if (
930
+ ts.isCallExpression(call) &&
931
+ ts.isPropertyAccessExpression(call.expression) &&
932
+ call.expression.name.text === "entries" &&
933
+ !call.arguments.length
934
+ ) {
935
+ const array = this.expression(call.expression.expression, frame);
936
+ if (array.kind === "code") {
937
+ this.forEntries(node, array.text, frame);
938
+ return;
939
+ }
940
+ }
920
941
  const iterable = this.expression(node.expression, frame);
921
942
  const items = this.items(iterable);
922
943
  const declaration = node.initializer;
@@ -949,6 +970,95 @@ export class Specializer {
949
970
  frame.emitter.close();
950
971
  }
951
972
 
973
+ /** `for (const [index, item] of array.entries())` over a runtime array stays a loop, as the backend lowers it. */
974
+ private forEntries(node: ts.ForOfStatement, array: string, frame: Frame): void {
975
+ const declaration = node.initializer;
976
+ const binding =
977
+ ts.isVariableDeclarationList(declaration) && declaration.declarations.length === 1
978
+ ? declaration.declarations[0]!.name
979
+ : undefined;
980
+ const names =
981
+ binding && ts.isArrayBindingPattern(binding)
982
+ ? binding.elements.map((element) =>
983
+ ts.isBindingElement(element) && ts.isIdentifier(element.name)
984
+ ? element.name
985
+ : undefined,
986
+ )
987
+ : [];
988
+ const [indexName, itemName] = names;
989
+ if (names.length !== 2 || !indexName || !itemName)
990
+ throw new SpecializeError(
991
+ node.initializer,
992
+ "Destructure [index, item] from array.entries().",
993
+ );
994
+ const [index, item] = [indexName, itemName].map((name) => {
995
+ const local = frame.emitter.local(name.text);
996
+ frame.env.set(this.checker.getSymbolAtLocation(name)!, {
997
+ kind: "code",
998
+ text: local,
999
+ declared: this.checker.getTypeAtLocation(name),
1000
+ place: true,
1001
+ });
1002
+ return local;
1003
+ });
1004
+ frame.emitter.open(`for (const [${index}, ${item}] of ${array}.entries()) {`);
1005
+ this.inner(node.statement, frame);
1006
+ frame.emitter.close();
1007
+ }
1008
+
1009
+ /** A counted loop stays a loop, in the header shape the backend proves bounded: `let i = start; i < bound; i++`. */
1010
+ private forLoop(node: ts.ForStatement, frame: Frame): void {
1011
+ const { condition, incrementor, initializer } = node;
1012
+ if (
1013
+ !initializer ||
1014
+ !ts.isVariableDeclarationList(initializer) ||
1015
+ !(initializer.flags & ts.NodeFlags.Let) ||
1016
+ initializer.declarations.length !== 1
1017
+ )
1018
+ throw new SpecializeError(node, "Declare one let counter in the for header.");
1019
+ const declaration = initializer.declarations[0]!;
1020
+ const name = declaration.name;
1021
+ if (!ts.isIdentifier(name) || !declaration.initializer)
1022
+ throw new SpecializeError(declaration, "Initialize the loop counter.");
1023
+ if (!condition || !ts.isBinaryExpression(condition) || !incrementor)
1024
+ throw new SpecializeError(
1025
+ node,
1026
+ "Compare the counter to a bound and step it in the for header.",
1027
+ );
1028
+ const declared = this.checker.getTypeAtLocation(name);
1029
+ // An annotation such as UINT keeps the counter's width, to index alongside unsigned fields.
1030
+ const iec = this.layouts.iecName(declaration);
1031
+ const start = this.code(
1032
+ this.expression(declaration.initializer, frame, declared),
1033
+ declared,
1034
+ frame,
1035
+ );
1036
+ const local = frame.emitter.local(name.text);
1037
+ frame.env.set(this.checker.getSymbolAtLocation(name)!, {
1038
+ kind: "code",
1039
+ text: local,
1040
+ declared,
1041
+ place: true,
1042
+ iec,
1043
+ });
1044
+ const test = `${this.code(this.expression(condition.left, frame), declared, frame)} ${condition.operatorToken.getText()} ${this.code(this.expression(condition.right, frame), declared, frame)}`;
1045
+ let step: string;
1046
+ if (ts.isPrefixUnaryExpression(incrementor) || ts.isPostfixUnaryExpression(incrementor))
1047
+ step = `${local}${ts.tokenToString(incrementor.operator)}`;
1048
+ else if (ts.isBinaryExpression(incrementor))
1049
+ step = `${local} ${incrementor.operatorToken.getText()} ${this.code(this.expression(incrementor.right, frame), declared, frame)}`;
1050
+ else
1051
+ throw new SpecializeError(
1052
+ incrementor,
1053
+ "Use i++, i--, i += step or i -= step in the for header.",
1054
+ );
1055
+ frame.emitter.open(
1056
+ `for (let ${local}: ${iec ?? this.localType(declared)} = ${start}; ${test}; ${step}) {`,
1057
+ );
1058
+ this.inner(node.statement, frame);
1059
+ frame.emitter.close();
1060
+ }
1061
+
952
1062
  /**
953
1063
  * The elements of an array setup built or scan code assembled from known parts; undefined for
954
1064
  * a runtime array. Known arrays unroll, so each element's identity stays known.
@@ -1429,6 +1539,11 @@ export class Specializer {
1429
1539
  declared,
1430
1540
  place: object.place,
1431
1541
  iec: this.layouts.iecName(property?.valueDeclaration),
1542
+ elementIec: this.elementIec(property?.valueDeclaration),
1543
+ layout:
1544
+ property && declared && this.checker.isArrayType(declared)
1545
+ ? this.layouts.fieldText(property)
1546
+ : undefined,
1432
1547
  };
1433
1548
  }
1434
1549
  if (object.kind === "const" && object.value === undefined)
@@ -2236,6 +2351,7 @@ const binaryToken = (kind: ts.SyntaxKind): string | undefined =>
2236
2351
  [ts.SyntaxKind.PlusToken]: "+",
2237
2352
  [ts.SyntaxKind.MinusToken]: "-",
2238
2353
  [ts.SyntaxKind.AsteriskToken]: "*",
2354
+ [ts.SyntaxKind.PercentToken]: "%",
2239
2355
  [ts.SyntaxKind.LessThanToken]: "<",
2240
2356
  [ts.SyntaxKind.LessThanEqualsToken]: "<=",
2241
2357
  [ts.SyntaxKind.GreaterThanToken]: ">",
@@ -2259,6 +2375,8 @@ const foldNumber = (
2259
2375
  return left - right;
2260
2376
  case ts.SyntaxKind.AsteriskToken:
2261
2377
  return left * right;
2378
+ case ts.SyntaxKind.PercentToken:
2379
+ return right === 0 ? undefined : left % right;
2262
2380
  case ts.SyntaxKind.LessThanToken:
2263
2381
  return left < right;
2264
2382
  case ts.SyntaxKind.LessThanEqualsToken:
@@ -1257,7 +1257,8 @@ class Analyzer {
1257
1257
  },
1258
1258
  };
1259
1259
  }
1260
- if (node.name.text === "length") {
1260
+ // A module global named length, read through its namespace import, is storage, not an array's length.
1261
+ if (node.name.text === "length" && !this.variables.has(this.resolver.symbol(node.name))) {
1261
1262
  const base = this.expression(node.expression),
1262
1263
  type = this.resolver.types.get(base.type);
1263
1264
  if (type?.kind === "array")