@tsplc/compiler 0.2.21 → 0.4.0

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 (115) hide show
  1. package/README.md +1 -1
  2. package/dist/cli.js +280 -223
  3. package/dist/cli.js.map +12 -12
  4. package/dist/codesys.js +452 -330
  5. package/dist/codesys.js.map +24 -24
  6. package/dist/elaborate-capture.js +112 -7
  7. package/dist/elaborate-capture.js.map +5 -4
  8. package/dist/index.js +5682 -5407
  9. package/dist/index.js.map +39 -37
  10. package/dist/ir.js +1154 -327
  11. package/dist/ir.js.map +23 -20
  12. package/dist/project.js +68 -29
  13. package/dist/project.js.map +4 -4
  14. package/dist/retain.js +8 -0
  15. package/dist/retain.js.map +10 -0
  16. package/dist/server-check.js +59 -0
  17. package/dist/server-check.js.map +11 -0
  18. package/dist/telemetry.js +19 -10
  19. package/dist/telemetry.js.map +3 -3
  20. package/package.json +33 -12
  21. package/src/codesys/config.ts +1 -1
  22. package/src/codesys/debug.ts +7 -21
  23. package/src/codesys/engineering.ts +8 -12
  24. package/src/codesys/global-lists.ts +19 -17
  25. package/src/codesys/global-names.ts +3 -3
  26. package/src/codesys/http.ts +37 -34
  27. package/src/codesys/index.ts +5 -22
  28. package/src/codesys/instrumentation.ts +3 -1
  29. package/src/codesys/io-paths.ts +2 -1
  30. package/src/codesys/manifest.ts +35 -18
  31. package/src/codesys/numeric.ts +2 -4
  32. package/src/codesys/plan.ts +94 -26
  33. package/src/codesys/publication.ts +4 -3
  34. package/src/codesys/routines.ts +2 -2
  35. package/src/codesys/sources.ts +1 -0
  36. package/src/codesys/st-files.ts +86 -50
  37. package/src/codesys/storage.ts +44 -9
  38. package/src/codesys/task-access.ts +32 -10
  39. package/src/codesys/telemetry.ts +93 -46
  40. package/src/codesys/types.ts +81 -3
  41. package/src/codesys/vendor.ts +1 -1
  42. package/src/frontend/analyzer.ts +15 -14
  43. package/src/frontend/async.ts +23 -21
  44. package/src/frontend/blocks.ts +7 -6
  45. package/src/frontend/configuration.ts +8 -6
  46. package/src/frontend/const-functions.ts +5 -5
  47. package/src/frontend/cooperative.ts +2 -1
  48. package/src/frontend/coroutines.ts +24 -21
  49. package/src/frontend/elaborate/calls.ts +12 -7
  50. package/src/frontend/elaborate/capture-protocol.ts +103 -0
  51. package/src/frontend/elaborate/capture.ts +48 -19
  52. package/src/frontend/elaborate/dialect.ts +2 -2
  53. package/src/frontend/elaborate/expressions.ts +9 -6
  54. package/src/frontend/elaborate/frame.ts +1 -1
  55. package/src/frontend/elaborate/graph.ts +27 -43
  56. package/src/frontend/elaborate/index.ts +52 -17
  57. package/src/frontend/elaborate/initializers.ts +3 -2
  58. package/src/frontend/elaborate/layouts.ts +2 -2
  59. package/src/frontend/elaborate/model.ts +34 -21
  60. package/src/frontend/elaborate/retention.ts +206 -0
  61. package/src/frontend/elaborate/specialize.ts +7 -6
  62. package/src/frontend/elaborate/statements.ts +47 -38
  63. package/src/frontend/elaborate/storage.ts +26 -6
  64. package/src/frontend/exposure.ts +6 -6
  65. package/src/frontend/expressions.ts +26 -25
  66. package/src/frontend/intrinsics.ts +3 -3
  67. package/src/frontend/module-graph.ts +1 -1
  68. package/src/frontend/positions.ts +2 -1
  69. package/src/frontend/promise-chains.ts +1 -0
  70. package/src/frontend/promises.ts +8 -7
  71. package/src/frontend/routines.ts +3 -2
  72. package/src/frontend/sdk.ts +2 -2
  73. package/src/frontend/services.ts +23 -20
  74. package/src/frontend/statements.ts +8 -6
  75. package/src/frontend/tasks.ts +11 -6
  76. package/src/frontend/telemetry.ts +1 -1
  77. package/src/frontend/types.ts +11 -9
  78. package/src/frontend/typescript.ts +92 -42
  79. package/src/index.ts +2 -1
  80. package/src/ir/aggregates.ts +4 -3
  81. package/src/ir/allocation.ts +2 -1
  82. package/src/ir/core-model.ts +38 -8
  83. package/src/ir/declarations.ts +12 -12
  84. package/src/ir/domains.ts +8 -8
  85. package/src/ir/fold.ts +2 -2
  86. package/src/ir/index.ts +53 -40
  87. package/src/ir/job-errors.ts +22 -11
  88. package/src/ir/layouts.ts +3 -2
  89. package/src/ir/link.ts +6 -24
  90. package/src/ir/model.ts +3 -2
  91. package/src/ir/normalization-error.ts +1 -1
  92. package/src/ir/normalize.ts +19 -12
  93. package/src/ir/numeric.ts +1 -0
  94. package/src/{codesys → ir}/operands.ts +2 -6
  95. package/src/ir/ranges.ts +2 -2
  96. package/src/ir/routine.ts +35 -20
  97. package/src/ir/scalars.ts +3 -3
  98. package/src/ir/share.ts +862 -0
  99. package/src/ir/temporaries.ts +236 -0
  100. package/src/ir/types.ts +1 -1
  101. package/src/project/artifacts.ts +12 -2
  102. package/src/project/cli.ts +42 -44
  103. package/src/project/debugger.ts +15 -9
  104. package/src/project/index.ts +1 -1
  105. package/src/project/plant.ts +34 -23
  106. package/src/project/project-commands.ts +92 -73
  107. package/src/project/project.ts +91 -42
  108. package/src/project/release.ts +50 -57
  109. package/src/project/server-check.ts +54 -0
  110. package/src/project/server.ts +60 -41
  111. package/src/project/terminal.ts +3 -1
  112. package/stdlib/retain.ts +2 -0
  113. package/types/globals.d.ts +1 -0
  114. package/types/retain.d.ts +6 -0
  115. package/types/telemetry.d.ts +2 -2
package/dist/ir.js CHANGED
@@ -1,17 +1,5 @@
1
- // packages/compiler/src/ir/core-model.ts
2
- var nestedBodies = (item) => {
3
- if (item.kind === "if") {
4
- return [item.then, item.else];
5
- }
6
- if (item.kind === "switch") {
7
- return [...item.cases.map((branch) => branch.body), item.fallback];
8
- }
9
- if (item.kind === "for") {
10
- return [item.body];
11
- }
12
- return [];
13
- };
14
- var verified = Symbol("verified core");
1
+ // packages/compiler/src/ir/domains.ts
2
+ import { elementaryType, integerRange as integerRange2 } from "@tsplc/iec";
15
3
 
16
4
  // packages/compiler/src/ir/model.ts
17
5
  var comparisonOperators = new Set([
@@ -105,8 +93,8 @@ var standardBlocks = {
105
93
 
106
94
  // packages/compiler/src/ir/types.ts
107
95
  import {
108
- elementaryTypes,
109
- integerRange as elementaryIntegerRange
96
+ integerRange as elementaryIntegerRange,
97
+ elementaryTypes
110
98
  } from "@tsplc/iec";
111
99
  var instancedBlock = (id, types) => {
112
100
  const type = types.get(id);
@@ -252,7 +240,6 @@ var applyIntegerPolicy = (value, type, policy) => {
252
240
  };
253
241
 
254
242
  // packages/compiler/src/ir/domains.ts
255
- import { elementaryType, integerRange as integerRange2 } from "@tsplc/iec";
256
243
  var nanosecondsPerMillisecond = 1000000n;
257
244
  var [, latestMillisecond] = integerRange2({
258
245
  bits: elementaryType("TIME").bits,
@@ -1035,10 +1022,38 @@ function expressionIssue(value, types, variables, ranges) {
1035
1022
  }
1036
1023
  return scalarIssue(value, types, variables, ranges);
1037
1024
  }
1038
-
1039
- // packages/compiler/src/ir/layouts.ts
1040
- import { elementaryType as elementaryType2, integerRange as integerRange3 } from "@tsplc/iec";
1041
-
1025
+ // packages/compiler/src/ir/core-model.ts
1026
+ var nestedBodies = (item) => {
1027
+ if (item.kind === "if") {
1028
+ return [item.then, item.else];
1029
+ }
1030
+ if (item.kind === "switch") {
1031
+ return [...item.cases.map((branch) => branch.body), item.fallback];
1032
+ }
1033
+ if (item.kind === "for") {
1034
+ return [item.body];
1035
+ }
1036
+ return [];
1037
+ };
1038
+ var directWrites = (item) => {
1039
+ if (item.kind === "assign") {
1040
+ return [item.root];
1041
+ }
1042
+ if (item.kind === "for") {
1043
+ return [item.counter];
1044
+ }
1045
+ if (item.kind === "invoke") {
1046
+ return [
1047
+ ...item.destination ? [item.destination] : [],
1048
+ ...item.arguments.flatMap((argument) => argument.kind === "borrow" ? [argument.place.root] : [])
1049
+ ];
1050
+ }
1051
+ if (item.kind === "blockUpdate") {
1052
+ return Object.values(item.inputs).flatMap((input) => input.kind === "borrow" ? [input.place.root] : []);
1053
+ }
1054
+ return [];
1055
+ };
1056
+ var verified = Symbol("verified core");
1042
1057
  // packages/compiler/src/ir/diagnostics.ts
1043
1058
  function error(code, message, span) {
1044
1059
  return {
@@ -1075,6 +1090,35 @@ ${" ".repeat(String(span.line).length + 3 + span.column - 1)}${"^".repeat(width)
1075
1090
  }
1076
1091
  return result;
1077
1092
  }
1093
+ // packages/compiler/src/ir/job-errors.ts
1094
+ var jobError = {
1095
+ cancelled: 1,
1096
+ timeout: 2,
1097
+ tooLarge: 3,
1098
+ malformedResponse: 4,
1099
+ network: 5,
1100
+ tls: 6,
1101
+ noRequestSlot: 7
1102
+ };
1103
+ var httpErrors = { base: 1e4, last: 10999 };
1104
+ var jobErrors = {
1105
+ [jobError.cancelled]: "cancelled",
1106
+ [jobError.timeout]: "timeout",
1107
+ [jobError.tooLarge]: "request or response too large to encode",
1108
+ [jobError.malformedResponse]: "malformed response",
1109
+ [jobError.network]: "network error or server restarted",
1110
+ [jobError.tls]: "TLS error",
1111
+ [jobError.noRequestSlot]: "no free request slot",
1112
+ [httpErrors.base]: "HTTP status: 10000 + status code"
1113
+ };
1114
+ var errorName = (code) => {
1115
+ if (code > httpErrors.base && code <= httpErrors.last) {
1116
+ return `HTTP ${code - httpErrors.base}`;
1117
+ }
1118
+ return code < httpErrors.base ? jobErrors[code] : undefined;
1119
+ };
1120
+ // packages/compiler/src/ir/layouts.ts
1121
+ import { elementaryType as elementaryType2, integerRange as integerRange3 } from "@tsplc/iec";
1078
1122
 
1079
1123
  // packages/compiler/src/ir/normalization-error.ts
1080
1124
  class InvalidCore extends Error {
@@ -1184,6 +1228,58 @@ var layoutIssue = (types) => {
1184
1228
  throw cause;
1185
1229
  }
1186
1230
  };
1231
+ // packages/compiler/src/ir/allocation.ts
1232
+ function checkStaticAllocation(module, declarations) {
1233
+ const { types, blocks, layoutSizes } = declarations;
1234
+ const payload = (id) => layoutSizes.get(id);
1235
+ const instanceSize = (id) => {
1236
+ const type = types.get(id);
1237
+ return type.kind === "array" ? type.length * instanceSize(type.element) : allocation(type.kind === "block" ? type.block : "").size;
1238
+ };
1239
+ const allocations = new Map;
1240
+ const allocating = new Set;
1241
+ const allocation = (id) => {
1242
+ if (allocating.size >= maxNestingDepth) {
1243
+ reject(`Static block allocation nesting exceeds ${maxNestingDepth} levels.`, blocks.get(id)?.span);
1244
+ }
1245
+ if (allocating.has(id)) {
1246
+ reject("Recursive static block allocation.", blocks.get(id)?.span);
1247
+ }
1248
+ const cached = allocations.get(id);
1249
+ if (cached) {
1250
+ return cached;
1251
+ }
1252
+ allocating.add(id);
1253
+ const block = blocks.get(id);
1254
+ const children = block.state.filter((item) => item.storage === "instance").map((item) => ({
1255
+ height: allocation(instancedBlock(item.type, types).block).height,
1256
+ size: instanceSize(item.type)
1257
+ }));
1258
+ const own = [
1259
+ ...block.inputs,
1260
+ ...block.outputs,
1261
+ ...block.state.filter((item) => item.storage !== "instance")
1262
+ ].reduce((sum, item) => sum + (item.mode === "inOut" ? 1 : payload(item.type)), 1);
1263
+ const size = own + children.reduce((sum, child) => sum + child.size, 0);
1264
+ const height = children.length ? 1 + Math.max(...children.map((child) => child.height)) : 1;
1265
+ if (size > maxScalarElements || height > maxNestingDepth) {
1266
+ reject("Static block allocation exceeds its finite budget.", block.span);
1267
+ }
1268
+ allocating.delete(id);
1269
+ const result = { size, height };
1270
+ allocations.set(id, result);
1271
+ return result;
1272
+ };
1273
+ for (const block of module.blocks) {
1274
+ allocation(block.id);
1275
+ }
1276
+ const staticPayload = module.variables.reduce((sum, variable) => {
1277
+ return sum + (instancedBlock(variable.type, types) ? instanceSize(variable.type) : payload(variable.type));
1278
+ }, 0);
1279
+ if (staticPayload > maxScalarElements) {
1280
+ reject("Static module storage exceeds one million scalar elements.");
1281
+ }
1282
+ }
1187
1283
 
1188
1284
  // packages/compiler/src/ir/declarations.ts
1189
1285
  var matchesPorts = (variables, schema) => variables.length === schema.length && schema.every(([name, , type]) => variables.some((variable) => variable.name === name && variable.type === type && !variable.mode && !variable.retain));
@@ -1345,58 +1441,238 @@ class ModuleDeclarations {
1345
1441
  }
1346
1442
  }
1347
1443
 
1348
- // packages/compiler/src/ir/allocation.ts
1349
- function checkStaticAllocation(module, declarations) {
1350
- const { types, blocks, layoutSizes } = declarations;
1351
- const payload = (id) => layoutSizes.get(id);
1352
- const instanceSize = (id) => {
1353
- const type = types.get(id);
1354
- return type.kind === "array" ? type.length * instanceSize(type.element) : allocation(type.kind === "block" ? type.block : "").size;
1444
+ // packages/compiler/src/ir/link.ts
1445
+ function linkModule(module, declarations, functions, normalizedBlocks, edges) {
1446
+ const entries = checkPrograms(module, declarations);
1447
+ const routines = new Map([...functions, ...normalizedBlocks].map((fn) => [fn.id, fn]));
1448
+ checkRecursion(routines, edges, entries, declarations);
1449
+ checkLoopCounterWrites(module, declarations, routines, edges);
1450
+ const reachable = reachableRoutines(module, declarations, functions, entries, edges);
1451
+ const linkedFunctions = functions.filter((fn) => reachable.has(fn.id));
1452
+ const linkedBlocks = normalizedBlocks.filter((block) => reachable.has(block.id));
1453
+ const usedTypes = usedTypeIds(module, declarations.types, linkedFunctions, linkedBlocks);
1454
+ return {
1455
+ types: module.types.filter((type) => usedTypes.has(type.id)),
1456
+ variables: module.variables,
1457
+ functions: linkedFunctions,
1458
+ blocks: linkedBlocks,
1459
+ programs: module.programs,
1460
+ ...module.folded && { folded: module.folded }
1355
1461
  };
1356
- const allocations = new Map;
1357
- const allocating = new Set;
1358
- const allocation = (id) => {
1359
- if (allocating.size >= maxNestingDepth) {
1360
- reject(`Static block allocation nesting exceeds ${maxNestingDepth} levels.`, blocks.get(id)?.span);
1462
+ }
1463
+ var checkPrograms = (module, declarations) => {
1464
+ const names = new Set;
1465
+ const entries = new Set;
1466
+ for (const program of module.programs) {
1467
+ declarations.claimId(program.id);
1468
+ const entry = declarations.signatures.get(program.entry);
1469
+ if (!entry || entry.owner || entry.parameters.length || entry.result) {
1470
+ reject("Program entry must be a parameterless void helper.");
1361
1471
  }
1362
- if (allocating.has(id)) {
1363
- reject("Recursive static block allocation.", blocks.get(id)?.span);
1472
+ if (names.has(program.name)) {
1473
+ reject(`Duplicate program ${program.name}.`);
1364
1474
  }
1365
- const cached = allocations.get(id);
1475
+ names.add(program.name);
1476
+ entries.add(program.entry);
1477
+ }
1478
+ if (!module.programs.length) {
1479
+ reject("At least one program is required.");
1480
+ }
1481
+ return entries;
1482
+ };
1483
+ var checkRecursion = (routines, edges, entries, { signatures }) => {
1484
+ const visited = new Set;
1485
+ const active = new Set;
1486
+ const visit = (id) => {
1487
+ if (active.has(id)) {
1488
+ reject("Recursive scan calls are prohibited.", signatures.get(id)?.span);
1489
+ }
1490
+ if (visited.has(id)) {
1491
+ return;
1492
+ }
1493
+ active.add(id);
1494
+ for (const child of edges.get(id) ?? []) {
1495
+ if (entries.has(child)) {
1496
+ reject("Program entries cannot be called as ordinary helpers.", signatures.get(id)?.span);
1497
+ }
1498
+ visit(child);
1499
+ }
1500
+ active.delete(id);
1501
+ visited.add(id);
1502
+ };
1503
+ for (const id of routines.keys()) {
1504
+ visit(id);
1505
+ }
1506
+ };
1507
+ var checkLoopCounterWrites = (module, { types }, routines, edges) => {
1508
+ const variables = new Map([
1509
+ ...module.variables,
1510
+ ...[...routines.values()].flatMap((routine) => ("inputs" in routine) ? [
1511
+ ...routine.inputs,
1512
+ ...routine.outputs,
1513
+ ...routine.state,
1514
+ ...routine.locals
1515
+ ] : [...routine.parameters, ...routine.locals])
1516
+ ].map((variable) => [variable.id, variable]));
1517
+ const calledRoutine = (item) => {
1518
+ if (item.kind === "invoke") {
1519
+ return item.function;
1520
+ }
1521
+ if (item.kind !== "blockUpdate") {
1522
+ return;
1523
+ }
1524
+ const variable = variables.get(item.instance);
1525
+ return variable && instancedBlock(variable.type, types)?.block;
1526
+ };
1527
+ const writes = new Map;
1528
+ const routineWrites = (id) => {
1529
+ const cached = writes.get(id);
1366
1530
  if (cached) {
1367
1531
  return cached;
1368
1532
  }
1369
- allocating.add(id);
1370
- const block = blocks.get(id);
1371
- const children = block.state.filter((item) => item.storage === "instance").map((item) => ({
1372
- height: allocation(instancedBlock(item.type, types).block).height,
1373
- size: instanceSize(item.type)
1374
- }));
1375
- const own = [
1376
- ...block.inputs,
1377
- ...block.outputs,
1378
- ...block.state.filter((item) => item.storage !== "instance")
1379
- ].reduce((sum, item) => sum + (item.mode === "inOut" ? 1 : payload(item.type)), 1);
1380
- const size = own + children.reduce((sum, child) => sum + child.size, 0);
1381
- const height = children.length ? 1 + Math.max(...children.map((child) => child.height)) : 1;
1382
- if (size > maxScalarElements || height > maxNestingDepth) {
1383
- reject("Static block allocation exceeds its finite budget.", block.span);
1533
+ const result = new Set;
1534
+ const inspect = (body) => {
1535
+ for (const item of body) {
1536
+ for (const root of directWrites(item)) {
1537
+ result.add(root);
1538
+ }
1539
+ for (const nested of nestedBodies(item)) {
1540
+ inspect(nested);
1541
+ }
1542
+ }
1543
+ };
1544
+ inspect(routines.get(id).body);
1545
+ for (const child of edges.get(id) ?? []) {
1546
+ for (const root of routineWrites(child)) {
1547
+ result.add(root);
1548
+ }
1384
1549
  }
1385
- allocating.delete(id);
1386
- const result = { size, height };
1387
- allocations.set(id, result);
1550
+ writes.set(id, result);
1388
1551
  return result;
1389
1552
  };
1390
- for (const block of module.blocks) {
1391
- allocation(block.id);
1553
+ const checkCalls = (body, counters) => {
1554
+ for (const item of body) {
1555
+ const called = calledRoutine(item);
1556
+ if (called && [...counters].some((counter) => routineWrites(called).has(counter))) {
1557
+ reject("A called routine may mutate an active loop counter.", item.span);
1558
+ }
1559
+ const nestedCounters = item.kind === "for" ? new Set([...counters, item.counter]) : counters;
1560
+ for (const nested of nestedBodies(item)) {
1561
+ checkCalls(nested, nestedCounters);
1562
+ }
1563
+ }
1564
+ };
1565
+ for (const routine of routines.values()) {
1566
+ checkCalls(routine.body, new Set);
1392
1567
  }
1393
- const staticPayload = module.variables.reduce((sum, variable) => {
1394
- return sum + (instancedBlock(variable.type, types) ? instanceSize(variable.type) : payload(variable.type));
1395
- }, 0);
1396
- if (staticPayload > maxScalarElements) {
1397
- reject("Static module storage exceeds one million scalar elements.");
1568
+ };
1569
+ var reachableRoutines = (module, { signatures, blocks, types }, functions, entries, edges) => {
1570
+ const reachable = new Set;
1571
+ const link = (id) => {
1572
+ if (reachable.has(id)) {
1573
+ return;
1574
+ }
1575
+ reachable.add(id);
1576
+ for (const child of edges.get(id) ?? []) {
1577
+ link(child);
1578
+ }
1579
+ const owner = signatures.get(id)?.owner;
1580
+ if (owner) {
1581
+ link(owner.block);
1582
+ }
1583
+ for (const method of functions.filter((fn) => fn.owner?.block === id)) {
1584
+ link(method.id);
1585
+ }
1586
+ for (const instance of blocks.get(id)?.state.filter((variable) => variable.storage === "instance") ?? []) {
1587
+ const type = instancedBlock(instance.type, types);
1588
+ if (type) {
1589
+ link(type.block);
1590
+ }
1591
+ }
1592
+ };
1593
+ for (const entry of entries) {
1594
+ link(entry);
1398
1595
  }
1399
- }
1596
+ for (const variable of module.variables) {
1597
+ const type = instancedBlock(variable.type, types);
1598
+ if (type) {
1599
+ link(type.block);
1600
+ }
1601
+ }
1602
+ return reachable;
1603
+ };
1604
+ var usedTypeIds = (module, types, linkedFunctions, linkedBlocks) => {
1605
+ const usedTypes = new Set;
1606
+ const useType = (id) => {
1607
+ if (usedTypes.has(id)) {
1608
+ return;
1609
+ }
1610
+ usedTypes.add(id);
1611
+ const type = types.get(id);
1612
+ if (type.kind === "record") {
1613
+ for (const field of type.fields) {
1614
+ useType(field.type);
1615
+ }
1616
+ }
1617
+ if (type.kind === "array") {
1618
+ useType(type.element);
1619
+ if (type.index) {
1620
+ useType(type.index);
1621
+ }
1622
+ }
1623
+ if (type.kind === "enum") {
1624
+ useType(type.base);
1625
+ }
1626
+ if (type.kind === "block" && type.output) {
1627
+ useType(type.output);
1628
+ }
1629
+ };
1630
+ types.forEach((type) => {
1631
+ if (["bool", "integer", "bits", "float", "duration", "calendar"].includes(type.kind)) {
1632
+ useType(type.id);
1633
+ }
1634
+ });
1635
+ for (const variable of module.variables) {
1636
+ useType(variable.type);
1637
+ }
1638
+ for (const fn of linkedFunctions) {
1639
+ if (fn.result) {
1640
+ useType(fn.result);
1641
+ }
1642
+ for (const variable of [...fn.parameters, ...fn.locals]) {
1643
+ useType(variable.type);
1644
+ }
1645
+ }
1646
+ for (const block of linkedBlocks) {
1647
+ if (block.result) {
1648
+ useType(block.result);
1649
+ }
1650
+ for (const variable of [
1651
+ ...block.inputs,
1652
+ ...block.outputs,
1653
+ ...block.state,
1654
+ ...block.locals
1655
+ ]) {
1656
+ useType(variable.type);
1657
+ }
1658
+ }
1659
+ const useTelemetryTypes = (body) => {
1660
+ for (const item of body) {
1661
+ if (item.kind === "telemetry") {
1662
+ for (const operand of telemetryOperands(item)) {
1663
+ useType(operand.type);
1664
+ }
1665
+ }
1666
+ for (const nested of nestedBodies(item)) {
1667
+ useTelemetryTypes(nested);
1668
+ }
1669
+ }
1670
+ };
1671
+ for (const routine of [...linkedFunctions, ...linkedBlocks]) {
1672
+ useTelemetryTypes(routine.body);
1673
+ }
1674
+ return usedTypes;
1675
+ };
1400
1676
 
1401
1677
  // packages/compiler/src/ir/routine.ts
1402
1678
  var join = (branches, initialized) => {
@@ -1413,6 +1689,12 @@ var join = (branches, initialized) => {
1413
1689
  initialized
1414
1690
  };
1415
1691
  };
1692
+ var temporaryPrefix = (routine) => `${routine}:temporary:`;
1693
+ var temporaryId = (routine, index) => `${temporaryPrefix(routine)}${index}`;
1694
+ function isTemporary(routine, variable) {
1695
+ const prefix = temporaryPrefix(routine);
1696
+ return variable.storage === "local" && variable.id.startsWith(prefix) && /^\d+$/.test(variable.id.slice(prefix.length));
1697
+ }
1416
1698
 
1417
1699
  class RoutineNormalizer {
1418
1700
  declarations;
@@ -1467,7 +1749,7 @@ class RoutineNormalizer {
1467
1749
  temporary(type, span) {
1468
1750
  let id;
1469
1751
  do {
1470
- id = `${this.fn.id}:temporary:${this.temporaryCount++}`;
1752
+ id = temporaryId(this.fn.id, this.temporaryCount++);
1471
1753
  } while (this.declarations.hasId(id));
1472
1754
  this.declarations.claimId(id);
1473
1755
  const item = {
@@ -2136,322 +2418,858 @@ class RoutineNormalizer {
2136
2418
  }
2137
2419
  }
2138
2420
 
2139
- // packages/compiler/src/ir/link.ts
2140
- function linkModule(module, declarations, functions, normalizedBlocks, edges) {
2141
- const entries = checkPrograms(module, declarations);
2142
- const routines = new Map([...functions, ...normalizedBlocks].map((fn) => [fn.id, fn]));
2143
- checkRecursion(routines, edges, entries, declarations);
2144
- checkLoopCounterWrites(module, declarations, routines, edges);
2145
- const reachable = reachableRoutines(module, declarations, functions, entries, edges);
2146
- const linkedFunctions = functions.filter((fn) => reachable.has(fn.id));
2147
- const linkedBlocks = normalizedBlocks.filter((block) => reachable.has(block.id));
2148
- const usedTypes = usedTypeIds(module, declarations.types, linkedFunctions, linkedBlocks);
2149
- return {
2150
- types: module.types.filter((type) => usedTypes.has(type.id)),
2151
- variables: module.variables,
2152
- functions: linkedFunctions,
2153
- blocks: linkedBlocks,
2154
- programs: module.programs,
2155
- ...module.folded && { folded: module.folded }
2156
- };
2421
+ // packages/compiler/src/ir/normalize.ts
2422
+ var verifiedModules = new WeakSet;
2423
+ function isVerifiedCore(value) {
2424
+ return typeof value === "object" && value !== null && verifiedModules.has(value);
2157
2425
  }
2158
- var checkPrograms = (module, declarations) => {
2159
- const names = new Set;
2160
- const entries = new Set;
2161
- for (const program of module.programs) {
2162
- declarations.claimId(program.id);
2163
- const entry = declarations.signatures.get(program.entry);
2164
- if (!entry || entry.owner || entry.parameters.length || entry.result) {
2165
- reject("Program entry must be a parameterless void helper.");
2426
+ function freeze(value) {
2427
+ if (typeof value !== "object" || value === null || Object.isFrozen(value)) {
2428
+ return;
2429
+ }
2430
+ for (const child of Object.values(value)) {
2431
+ freeze(child);
2432
+ }
2433
+ Object.freeze(value);
2434
+ }
2435
+ function admitCore(core) {
2436
+ freeze(core);
2437
+ verifiedModules.add(core);
2438
+ return core;
2439
+ }
2440
+ function normalizeModule(module) {
2441
+ try {
2442
+ const declarations = new ModuleDeclarations(module);
2443
+ checkStaticAllocation(module, declarations);
2444
+ const functions = [];
2445
+ const blocks = [];
2446
+ const edges = new Map;
2447
+ for (const source of [...module.functions, ...module.blocks]) {
2448
+ const normalized = new RoutineNormalizer(source, declarations).normalize();
2449
+ edges.set(source.id, normalized.callees);
2450
+ if ("inputs" in normalized.routine) {
2451
+ blocks.push(normalized.routine);
2452
+ } else {
2453
+ functions.push(normalized.routine);
2454
+ }
2166
2455
  }
2167
- if (names.has(program.name)) {
2168
- reject(`Duplicate program ${program.name}.`);
2456
+ const linked = linkModule(module, declarations, functions, blocks, edges);
2457
+ return {
2458
+ core: admitCore({ ...structuredClone(linked), [verified]: true }),
2459
+ diagnostics: []
2460
+ };
2461
+ } catch (cause) {
2462
+ if (cause instanceof InvalidCore) {
2463
+ return { diagnostics: [cause.diagnostic] };
2169
2464
  }
2170
- names.add(program.name);
2171
- entries.add(program.entry);
2465
+ throw cause;
2172
2466
  }
2173
- if (!module.programs.length) {
2174
- reject("At least one program is required.");
2467
+ }
2468
+ // packages/compiler/src/ir/operands.ts
2469
+ var pathIndexes = (path = []) => path.flatMap((segment) => segment.kind === "index" ? [segment.value] : []);
2470
+ var subexpressions = (value) => {
2471
+ switch (value.kind) {
2472
+ case "constant":
2473
+ return [];
2474
+ case "load":
2475
+ return pathIndexes(value.path);
2476
+ case "borrow":
2477
+ return pathIndexes(value.place.path);
2478
+ case "unary":
2479
+ case "convert":
2480
+ return [value.operand];
2481
+ case "binary":
2482
+ return [value.left, value.right];
2175
2483
  }
2176
- return entries;
2177
2484
  };
2178
- var checkRecursion = (routines, edges, entries, { signatures }) => {
2179
- const visited = new Set;
2180
- const active = new Set;
2181
- const visit = (id) => {
2182
- if (active.has(id)) {
2183
- reject("Recursive scan calls are prohibited.", signatures.get(id)?.span);
2485
+ var statementExpressions = (item) => {
2486
+ switch (item.kind) {
2487
+ case "assign":
2488
+ return [...pathIndexes(item.path), item.value];
2489
+ case "if":
2490
+ return [item.condition];
2491
+ case "switch":
2492
+ return [item.value];
2493
+ case "for":
2494
+ return item.dynamic ? [item.dynamic.start, item.dynamic.limit] : [];
2495
+ case "invoke":
2496
+ return [...item.index ? [item.index] : [], ...item.arguments];
2497
+ case "blockUpdate":
2498
+ return [
2499
+ ...item.index ? [item.index] : [],
2500
+ ...Object.values(item.inputs)
2501
+ ];
2502
+ case "return":
2503
+ return item.value ? [item.value] : [];
2504
+ case "telemetry":
2505
+ return telemetryOperands(item);
2506
+ case "break":
2507
+ case "continue":
2508
+ return [];
2509
+ }
2510
+ };
2511
+ // packages/compiler/src/ir/share.ts
2512
+ function shareRoutines(core, partition) {
2513
+ const types = new Map(core.types.map((type) => [type.id, type]));
2514
+ const globals = new Map(core.variables.map((item) => [item.id, item]));
2515
+ const entries = new Set(core.programs.map((program) => program.entry));
2516
+ const bodies = new Map([...core.functions, ...core.blocks].map((routine) => [
2517
+ routine.id,
2518
+ routine.body
2519
+ ]));
2520
+ const merged = new Map;
2521
+ const shared = new Map;
2522
+ const plainData = (id, seen = new Set) => {
2523
+ const type = types.get(id);
2524
+ if (!type || seen.has(id)) {
2525
+ return type !== undefined;
2184
2526
  }
2185
- if (visited.has(id)) {
2186
- return;
2527
+ seen.add(id);
2528
+ if (type.kind === "block") {
2529
+ return false;
2187
2530
  }
2188
- active.add(id);
2189
- for (const child of edges.get(id) ?? []) {
2190
- if (entries.has(child)) {
2191
- reject("Program entries cannot be called as ordinary helpers.", signatures.get(id)?.span);
2192
- }
2193
- visit(child);
2531
+ if (type.kind === "array") {
2532
+ return plainData(type.element, seen);
2194
2533
  }
2195
- active.delete(id);
2196
- visited.add(id);
2534
+ if (type.kind === "record") {
2535
+ return type.fields.every((field) => field.mode !== "inOut" && plainData(field.type, seen));
2536
+ }
2537
+ return true;
2197
2538
  };
2198
- for (const id of routines.keys()) {
2199
- visit(id);
2539
+ const roots = {
2540
+ anchorable: (root) => {
2541
+ const variable = globals.get(root);
2542
+ return variable !== undefined && variable.storage !== "constant";
2543
+ },
2544
+ type: (root) => globals.get(root)?.type,
2545
+ name: (root) => globals.get(root)?.name ?? "anchor",
2546
+ plainData: (type) => plainData(type)
2547
+ };
2548
+ const candidates = core.functions.filter((fn) => !fn.owner && !entries.has(fn.id));
2549
+ for (const level of callLevels(candidates, bodies)) {
2550
+ const groups = new Map;
2551
+ for (const fn of level) {
2552
+ const group = partition(fn);
2553
+ if (group === undefined) {
2554
+ continue;
2555
+ }
2556
+ const anchored = anchor({ ...fn, body: bodies.get(fn.id) ?? fn.body }, types, roots);
2557
+ if (!anchored) {
2558
+ continue;
2559
+ }
2560
+ const key = `${group}
2561
+ ${anchored.key}`;
2562
+ groups.set(key, [...groups.get(key) ?? [], anchored]);
2563
+ }
2564
+ const calls = new Map;
2565
+ for (const members of groups.values()) {
2566
+ const [first] = members;
2567
+ if (!first || members.length < 2) {
2568
+ continue;
2569
+ }
2570
+ const varying = {
2571
+ anchors: first.anchors.map((slot, index) => members.some((member) => member.anchors[index]?.key !== slot.key)),
2572
+ constants: first.constants.map((constant, index) => members.some((member) => JSON.stringify(member.constants[index]?.value) !== JSON.stringify(constant.value)))
2573
+ };
2574
+ shared.set(first.fn.id, mergedRoutine(first, varying, roots, types));
2575
+ for (const [index, member] of members.entries()) {
2576
+ if (index) {
2577
+ merged.set(member.fn.id, first.fn.id);
2578
+ }
2579
+ calls.set(member.fn.id, {
2580
+ target: first.fn.id,
2581
+ borrows: member.anchors.filter((_, slot) => varying.anchors[slot]),
2582
+ values: member.constants.filter((_, slot) => varying.constants[slot])
2583
+ });
2584
+ }
2585
+ }
2586
+ if (!calls.size) {
2587
+ continue;
2588
+ }
2589
+ for (const [id, body] of bodies) {
2590
+ bodies.set(id, rewriteCalls(body, calls));
2591
+ }
2200
2592
  }
2201
- };
2202
- var checkLoopCounterWrites = (module, { types }, routines, edges) => {
2203
- const variables = new Map([
2204
- ...module.variables,
2205
- ...[...routines.values()].flatMap((routine) => ("inputs" in routine) ? [
2206
- ...routine.inputs,
2207
- ...routine.outputs,
2208
- ...routine.state,
2209
- ...routine.locals
2210
- ] : [...routine.parameters, ...routine.locals])
2211
- ].map((variable) => [variable.id, variable]));
2212
- const calledRoutine = (item) => {
2213
- if (item.kind === "invoke") {
2214
- return item.function;
2593
+ if (!merged.size) {
2594
+ return { core, routines: merged };
2595
+ }
2596
+ const functions = core.functions.flatMap((fn) => {
2597
+ if (merged.has(fn.id)) {
2598
+ return [];
2215
2599
  }
2216
- if (item.kind !== "blockUpdate") {
2217
- return;
2600
+ const routine = shared.get(fn.id);
2601
+ if (routine) {
2602
+ return [routine];
2218
2603
  }
2219
- const variable = variables.get(item.instance);
2220
- return variable && instancedBlock(variable.type, types)?.block;
2604
+ return [{ ...fn, body: bodies.get(fn.id) ?? fn.body }];
2605
+ });
2606
+ const blocks = core.blocks.map((block) => ({
2607
+ ...block,
2608
+ body: bodies.get(block.id) ?? block.body
2609
+ }));
2610
+ return {
2611
+ core: admitCore({ ...core, functions, blocks }),
2612
+ routines: merged
2221
2613
  };
2222
- const writes = new Map;
2223
- const routineWrites = (id) => {
2224
- const cached = writes.get(id);
2225
- if (cached) {
2226
- return cached;
2227
- }
2228
- const result = new Set;
2229
- const inspect = (body) => {
2230
- for (const item of body) {
2231
- if (item.kind === "assign") {
2232
- result.add(item.root);
2233
- }
2234
- if (item.kind === "for") {
2235
- result.add(item.counter);
2236
- }
2237
- if (item.kind === "invoke") {
2238
- if (item.destination) {
2239
- result.add(item.destination);
2240
- }
2241
- for (const argument of item.arguments) {
2242
- if (argument.kind === "borrow") {
2243
- result.add(argument.place.root);
2244
- }
2245
- }
2246
- }
2247
- if (item.kind === "blockUpdate") {
2248
- for (const input of Object.values(item.inputs)) {
2249
- if (input.kind === "borrow") {
2250
- result.add(input.place.root);
2251
- }
2252
- }
2253
- }
2254
- for (const nested of nestedBodies(item)) {
2255
- inspect(nested);
2256
- }
2614
+ }
2615
+ function callLevels(candidates, bodies) {
2616
+ const levels = new Map;
2617
+ const callees = (items, found) => {
2618
+ for (const item of items) {
2619
+ if (item.kind === "invoke") {
2620
+ found.add(item.function);
2257
2621
  }
2258
- };
2259
- inspect(routines.get(id).body);
2260
- for (const child of edges.get(id) ?? []) {
2261
- for (const root of routineWrites(child)) {
2262
- result.add(root);
2622
+ for (const body of nestedBodies(item)) {
2623
+ callees(body, found);
2263
2624
  }
2264
2625
  }
2265
- writes.set(id, result);
2266
- return result;
2626
+ return found;
2267
2627
  };
2268
- const checkCalls = (body, counters) => {
2269
- for (const item of body) {
2270
- const called = calledRoutine(item);
2271
- if (called && [...counters].some((counter) => routineWrites(called).has(counter))) {
2272
- reject("A called routine may mutate an active loop counter.", item.span);
2628
+ const level = (id, path) => {
2629
+ const known = levels.get(id);
2630
+ if (known !== undefined) {
2631
+ return known;
2632
+ }
2633
+ if (path.has(id)) {
2634
+ return 0;
2635
+ }
2636
+ path.add(id);
2637
+ const deepest = [...callees(bodies.get(id) ?? [], new Set)].reduce((depth, callee) => Math.max(depth, level(callee, path) + 1), 0);
2638
+ path.delete(id);
2639
+ levels.set(id, deepest);
2640
+ return deepest;
2641
+ };
2642
+ const ordered = [];
2643
+ for (const fn of candidates) {
2644
+ const depth = level(fn.id, new Set);
2645
+ ordered[depth] = [...ordered[depth] ?? [], fn];
2646
+ }
2647
+ return ordered.filter((items) => items !== undefined);
2648
+ }
2649
+ var staticIndex = (segment) => segment.kind === "index" && segment.value.kind === "constant" && segment.value.value.kind === "integer";
2650
+ function anchorLength(path) {
2651
+ const dynamic = path.findIndex((segment) => segment.kind === "index" && !staticIndex(segment));
2652
+ if (dynamic >= 0) {
2653
+ return dynamic;
2654
+ }
2655
+ return path.at(-1)?.kind === "field" ? path.length - 1 : path.length;
2656
+ }
2657
+ var pathType = (root, path, types) => path.reduce((id, segment) => {
2658
+ const type = id === undefined ? undefined : types.get(id);
2659
+ if (segment.kind === "field" && type?.kind === "record") {
2660
+ return type.fields.find((field) => field.name === segment.name)?.type;
2661
+ }
2662
+ if (segment.kind === "index" && type?.kind === "array") {
2663
+ return type.element;
2664
+ }
2665
+ return;
2666
+ }, root);
2667
+ var constantText = (segment) => segment.kind === "field" ? `.${segment.name}` : `[${segment.value.kind === "constant" ? JSON.stringify(segment.value.value) : "?"}]`;
2668
+ function anchor(fn, types, roots) {
2669
+ const own = new Map([...fn.parameters, ...fn.locals].map((variable, index) => [
2670
+ variable.id,
2671
+ `#${index}`
2672
+ ]));
2673
+ const anchors = [];
2674
+ const constants = [];
2675
+ const numbers = new Map;
2676
+ const rewrite = {
2677
+ constant: (value) => {
2678
+ if (!scalarConstant(value, types)) {
2679
+ return value;
2273
2680
  }
2274
- const nestedCounters = item.kind === "for" ? new Set([...counters, item.counter]) : counters;
2275
- for (const nested of nestedBodies(item)) {
2276
- checkCalls(nested, nestedCounters);
2681
+ constants.push(value);
2682
+ return {
2683
+ kind: "load",
2684
+ type: value.type,
2685
+ span: value.span,
2686
+ root: `$${constants.length - 1}`
2687
+ };
2688
+ },
2689
+ place: (root, path) => {
2690
+ if (!roots.anchorable(root)) {
2691
+ return { root: own.get(root) ?? root, path: mapPath(path) };
2692
+ }
2693
+ const { fixed, key } = anchorOf(root, path);
2694
+ const rest = mapPath(path.slice(fixed.length));
2695
+ const known = numbers.get(key);
2696
+ if (known !== undefined) {
2697
+ return { root: `@${known}`, path: rest };
2698
+ }
2699
+ const rootType = roots.type(root);
2700
+ const type = rootType === undefined ? undefined : pathType(rootType, fixed, types);
2701
+ if (type === undefined) {
2702
+ throw new Unanchored;
2703
+ }
2704
+ if (!roots.plainData(type)) {
2705
+ return { root, path: [...fixed, ...rest] };
2277
2706
  }
2707
+ numbers.set(key, anchors.length);
2708
+ anchors.push({ root, path: fixed, type, key });
2709
+ return { root: `@${anchors.length - 1}`, path: rest };
2710
+ },
2711
+ identity: (root) => {
2712
+ if (roots.anchorable(root)) {
2713
+ throw new Unanchored;
2714
+ }
2715
+ return own.get(root) ?? root;
2278
2716
  }
2279
2717
  };
2280
- for (const routine of routines.values()) {
2281
- checkCalls(routine.body, new Set);
2718
+ const mapPath = (path) => path.map((segment) => segment.kind === "field" ? segment : { kind: "index", value: rewriteExpression(segment.value, rewrite) });
2719
+ try {
2720
+ const body = rewriteStatements(fn.body, rewrite);
2721
+ const signature = {
2722
+ span: fn.span,
2723
+ result: fn.result,
2724
+ parameters: fn.parameters.map(({ id, ...rest }) => rest),
2725
+ locals: fn.locals.map(({ id, ...rest }) => rest),
2726
+ anchors: anchors.map((item) => item.type)
2727
+ };
2728
+ return { fn, key: JSON.stringify([signature, body]), anchors, constants };
2729
+ } catch (cause) {
2730
+ if (cause instanceof Unanchored) {
2731
+ return;
2732
+ }
2733
+ throw cause;
2282
2734
  }
2735
+ }
2736
+ var anchorOf = (root, path) => {
2737
+ const fixed = path.slice(0, anchorLength(path));
2738
+ return { fixed, key: `${root}${fixed.map(constantText).join("")}` };
2283
2739
  };
2284
- var reachableRoutines = (module, { signatures, blocks, types }, functions, entries, edges) => {
2285
- const reachable = new Set;
2286
- const link = (id) => {
2287
- if (reachable.has(id)) {
2288
- return;
2740
+ function mergedRoutine({ fn, anchors, constants }, varying, roots, types) {
2741
+ const borrowed = new Map;
2742
+ for (const [index, slot] of anchors.entries()) {
2743
+ if (!varying.anchors[index]) {
2744
+ continue;
2745
+ }
2746
+ const field = [...slot.path].reverse().find((segment) => segment.kind === "field");
2747
+ borrowed.set(index, {
2748
+ id: `${fn.id}:anchor${index}`,
2749
+ name: field?.kind === "field" ? field.name : roots.name(slot.root),
2750
+ type: slot.type,
2751
+ storage: "parameter",
2752
+ mutable: true,
2753
+ retain: false,
2754
+ mode: "inOut",
2755
+ span: fn.span
2756
+ });
2757
+ }
2758
+ const values = new Map;
2759
+ for (const [index, constant] of constants.entries()) {
2760
+ if (varying.constants[index]) {
2761
+ values.set(index, {
2762
+ id: `${fn.id}:value${index}`,
2763
+ name: "value",
2764
+ type: constant.type,
2765
+ storage: "parameter",
2766
+ mutable: false,
2767
+ retain: false,
2768
+ span: fn.span
2769
+ });
2289
2770
  }
2290
- reachable.add(id);
2291
- for (const child of edges.get(id) ?? []) {
2292
- link(child);
2771
+ }
2772
+ const slots = new Map(anchors.map((slot, index) => [slot.key, index]));
2773
+ const order = constants.keys();
2774
+ const rewrite = {
2775
+ constant: (value) => {
2776
+ if (!scalarConstant(value, types)) {
2777
+ return value;
2778
+ }
2779
+ const parameter = values.get(order.next().value ?? -1);
2780
+ return parameter ? {
2781
+ kind: "load",
2782
+ type: value.type,
2783
+ span: value.span,
2784
+ root: parameter.id
2785
+ } : value;
2786
+ },
2787
+ place: (root, path) => {
2788
+ if (!roots.anchorable(root)) {
2789
+ return { root, path: mapPath(path) };
2790
+ }
2791
+ const { fixed, key } = anchorOf(root, path);
2792
+ const rest = mapPath(path.slice(fixed.length));
2793
+ const parameter = borrowed.get(slots.get(key) ?? -1);
2794
+ return parameter ? { root: parameter.id, path: rest } : { root, path: [...fixed, ...rest] };
2795
+ },
2796
+ identity: (root) => root
2797
+ };
2798
+ const mapPath = (path) => path.map((segment) => segment.kind === "field" ? segment : { kind: "index", value: rewriteExpression(segment.value, rewrite) });
2799
+ return {
2800
+ ...fn,
2801
+ parameters: [...fn.parameters, ...borrowed.values(), ...values.values()],
2802
+ body: rewriteStatements(fn.body, rewrite)
2803
+ };
2804
+ }
2805
+ function rewriteCalls(items, calls) {
2806
+ return items.map((item) => {
2807
+ if (item.kind === "invoke") {
2808
+ const call = calls.get(item.function);
2809
+ if (!call) {
2810
+ return item;
2811
+ }
2812
+ return {
2813
+ ...item,
2814
+ function: call.target,
2815
+ arguments: [
2816
+ ...item.arguments,
2817
+ ...call.borrows.map((borrow) => ({
2818
+ kind: "borrow",
2819
+ type: borrow.type,
2820
+ span: item.span,
2821
+ place: { root: borrow.root, path: borrow.path }
2822
+ })),
2823
+ ...call.values
2824
+ ]
2825
+ };
2293
2826
  }
2294
- const owner = signatures.get(id)?.owner;
2295
- if (owner) {
2296
- link(owner.block);
2827
+ switch (item.kind) {
2828
+ case "if":
2829
+ return {
2830
+ ...item,
2831
+ then: rewriteCalls(item.then, calls),
2832
+ else: rewriteCalls(item.else, calls)
2833
+ };
2834
+ case "switch":
2835
+ return {
2836
+ ...item,
2837
+ cases: item.cases.map((branch) => ({
2838
+ ...branch,
2839
+ body: rewriteCalls(branch.body, calls)
2840
+ })),
2841
+ fallback: rewriteCalls(item.fallback, calls)
2842
+ };
2843
+ case "for":
2844
+ return { ...item, body: rewriteCalls(item.body, calls) };
2845
+ default:
2846
+ return item;
2297
2847
  }
2298
- for (const method of functions.filter((fn) => fn.owner?.block === id)) {
2299
- link(method.id);
2848
+ });
2849
+ }
2850
+
2851
+ class Unanchored extends Error {
2852
+ }
2853
+ var scalarConstant = (value, types) => ["bool", "integer", "float", "duration", "calendar"].includes(value.value.kind) && types.get(value.type)?.kind !== "string";
2854
+ function rewriteExpression(value, rewrite) {
2855
+ switch (value.kind) {
2856
+ case "constant":
2857
+ return rewrite.constant(value);
2858
+ case "load": {
2859
+ const place = rewrite.place(value.root, value.path ?? []);
2860
+ return {
2861
+ ...value,
2862
+ root: place.root,
2863
+ ...value.path || place.path.length ? { path: place.path } : {}
2864
+ };
2300
2865
  }
2301
- for (const instance of blocks.get(id)?.state.filter((variable) => variable.storage === "instance") ?? []) {
2302
- const type = instancedBlock(instance.type, types);
2303
- if (type) {
2304
- link(type.block);
2305
- }
2866
+ case "borrow":
2867
+ return {
2868
+ ...value,
2869
+ place: rewrite.place(value.place.root, value.place.path)
2870
+ };
2871
+ case "unary":
2872
+ case "convert":
2873
+ return { ...value, operand: rewriteExpression(value.operand, rewrite) };
2874
+ case "binary":
2875
+ return {
2876
+ ...value,
2877
+ left: rewriteExpression(value.left, rewrite),
2878
+ right: rewriteExpression(value.right, rewrite)
2879
+ };
2880
+ }
2881
+ }
2882
+ function rewriteStatements(items, rewrite) {
2883
+ const expression = (value) => rewriteExpression(value, rewrite);
2884
+ const statements = (body) => rewriteStatements(body, rewrite);
2885
+ return items.map((item) => rewriteStatement(item, rewrite, expression, statements));
2886
+ }
2887
+ function rewriteStatement(item, rewrite, expression, statements) {
2888
+ switch (item.kind) {
2889
+ case "assign": {
2890
+ const place = rewrite.place(item.root, item.path ?? []);
2891
+ return {
2892
+ ...item,
2893
+ root: place.root,
2894
+ ...item.path || place.path.length ? { path: place.path } : {},
2895
+ value: expression(item.value)
2896
+ };
2306
2897
  }
2307
- };
2308
- for (const entry of entries) {
2309
- link(entry);
2898
+ case "if":
2899
+ return {
2900
+ ...item,
2901
+ condition: expression(item.condition),
2902
+ then: statements(item.then),
2903
+ else: statements(item.else)
2904
+ };
2905
+ case "switch":
2906
+ return {
2907
+ ...item,
2908
+ value: expression(item.value),
2909
+ cases: item.cases.map((branch) => ({
2910
+ ...branch,
2911
+ body: statements(branch.body)
2912
+ })),
2913
+ fallback: statements(item.fallback)
2914
+ };
2915
+ case "for":
2916
+ return {
2917
+ ...item,
2918
+ counter: rewrite.identity(item.counter),
2919
+ ...item.dynamic && {
2920
+ dynamic: {
2921
+ ...item.dynamic,
2922
+ start: expression(item.dynamic.start),
2923
+ limit: expression(item.dynamic.limit)
2924
+ }
2925
+ },
2926
+ body: statements(item.body)
2927
+ };
2928
+ case "invoke":
2929
+ return {
2930
+ ...item,
2931
+ ...item.instance !== undefined && {
2932
+ instance: rewrite.identity(item.instance)
2933
+ },
2934
+ ...item.index && { index: expression(item.index) },
2935
+ arguments: item.arguments.map(expression),
2936
+ ...item.destination !== undefined && {
2937
+ destination: rewrite.identity(item.destination)
2938
+ }
2939
+ };
2940
+ case "blockUpdate":
2941
+ return {
2942
+ ...item,
2943
+ instance: rewrite.identity(item.instance),
2944
+ ...item.index && { index: expression(item.index) },
2945
+ inputs: Object.fromEntries(Object.entries(item.inputs).map(([name, input]) => [
2946
+ name,
2947
+ expression(input)
2948
+ ]))
2949
+ };
2950
+ case "return":
2951
+ return item.value ? { ...item, value: expression(item.value) } : item;
2952
+ case "telemetry":
2953
+ return {
2954
+ ...item,
2955
+ properties: item.properties.map((property) => ({
2956
+ ...property,
2957
+ value: expression(property.value),
2958
+ ...property.length && { length: expression(property.length) }
2959
+ })),
2960
+ ...item.record.kind === "exception" && {
2961
+ record: { ...item.record, code: expression(item.record.code) }
2962
+ }
2963
+ };
2964
+ case "break":
2965
+ case "continue":
2966
+ return item;
2310
2967
  }
2311
- for (const variable of module.variables) {
2312
- const type = instancedBlock(variable.type, types);
2313
- if (type) {
2314
- link(type.block);
2968
+ }
2969
+ var returns = (items) => items.some((item) => item.kind === "return" || nestedBodies(item).some(returns));
2970
+ function joinPrograms(core, groups) {
2971
+ const functions = new Map(core.functions.map((fn) => [fn.id, fn]));
2972
+ const programs = new Map(core.programs.map((item) => [item.name, item]));
2973
+ const joined = new Map;
2974
+ const routines = new Map;
2975
+ const removed = new Set;
2976
+ for (const group of groups) {
2977
+ const members = group.flatMap((name) => {
2978
+ const program = programs.get(name);
2979
+ const entry = program && functions.get(program.entry);
2980
+ return program && entry && !returns(entry.body) ? [{ program, entry }] : [];
2981
+ });
2982
+ const [first, ...rest] = members;
2983
+ if (!first || !rest.length) {
2984
+ continue;
2985
+ }
2986
+ joined.set(first.entry.id, {
2987
+ ...first.entry,
2988
+ locals: members.flatMap(({ entry }) => entry.locals),
2989
+ body: members.flatMap(({ entry }) => entry.body)
2990
+ });
2991
+ for (const { program, entry } of rest) {
2992
+ removed.add(program.name);
2993
+ routines.set(entry.id, first.entry.id);
2315
2994
  }
2316
2995
  }
2317
- return reachable;
2996
+ if (!routines.size) {
2997
+ return { core, routines };
2998
+ }
2999
+ return {
3000
+ core: admitCore({
3001
+ ...core,
3002
+ functions: core.functions.flatMap((fn) => routines.has(fn.id) ? [] : [joined.get(fn.id) ?? fn]),
3003
+ programs: core.programs.filter((item) => !removed.has(item.name))
3004
+ }),
3005
+ routines
3006
+ };
3007
+ }
3008
+ function constantResult(fn) {
3009
+ const [only, ...rest] = fn.body;
3010
+ if (rest.length || fn.owner) {
3011
+ return;
3012
+ }
3013
+ if (!only) {
3014
+ return fn.result ? undefined : {};
3015
+ }
3016
+ if (only.kind !== "return") {
3017
+ return;
3018
+ }
3019
+ if (!only.value) {
3020
+ return fn.result ? undefined : {};
3021
+ }
3022
+ return only.value.kind === "constant" ? { value: only.value } : undefined;
3023
+ }
3024
+ var placePath = (value) => {
3025
+ if (value.kind === "load") {
3026
+ return value.path ?? [];
3027
+ }
3028
+ return value.kind === "borrow" ? value.place.path : undefined;
2318
3029
  };
2319
- var usedTypeIds = (module, types, linkedFunctions, linkedBlocks) => {
2320
- const usedTypes = new Set;
2321
- const useType = (id) => {
2322
- if (usedTypes.has(id)) {
2323
- return;
2324
- }
2325
- usedTypes.add(id);
2326
- const type = types.get(id);
2327
- if (type.kind === "record") {
2328
- for (const field of type.fields) {
2329
- useType(field.type);
3030
+ var plainArgument = (value) => {
3031
+ if (value.kind === "constant") {
3032
+ return true;
3033
+ }
3034
+ return placePath(value)?.every((segment) => segment.kind === "field" || plainArgument(segment.value)) ?? false;
3035
+ };
3036
+ function foldConstantRoutines(core) {
3037
+ const entries = new Set(core.programs.map((program) => program.entry));
3038
+ const constants = new Map(core.functions.flatMap((fn) => {
3039
+ const result = entries.has(fn.id) ? undefined : constantResult(fn);
3040
+ return result ? [[fn.id, result]] : [];
3041
+ }));
3042
+ if (!constants.size) {
3043
+ return { core, routines: new Set };
3044
+ }
3045
+ const called = new Set;
3046
+ const fold = (items) => items.flatMap((item) => {
3047
+ if (item.kind === "invoke") {
3048
+ const result = constants.get(item.function);
3049
+ if (!result || !item.arguments.every(plainArgument)) {
3050
+ called.add(item.function);
3051
+ return [item];
2330
3052
  }
2331
- }
2332
- if (type.kind === "array") {
2333
- useType(type.element);
2334
- if (type.index) {
2335
- useType(type.index);
3053
+ if (item.destination === undefined || !result.value) {
3054
+ return [];
2336
3055
  }
3056
+ return [
3057
+ {
3058
+ kind: "assign",
3059
+ span: item.span,
3060
+ root: item.destination,
3061
+ value: { ...result.value, span: item.span }
3062
+ }
3063
+ ];
2337
3064
  }
2338
- if (type.kind === "enum") {
2339
- useType(type.base);
2340
- }
2341
- if (type.kind === "block" && type.output) {
2342
- useType(type.output);
2343
- }
2344
- };
2345
- types.forEach((type) => {
2346
- if (["bool", "integer", "bits", "float", "duration", "calendar"].includes(type.kind)) {
2347
- useType(type.id);
3065
+ switch (item.kind) {
3066
+ case "if":
3067
+ return [
3068
+ {
3069
+ ...item,
3070
+ then: fold(item.then),
3071
+ else: fold(item.else)
3072
+ }
3073
+ ];
3074
+ case "switch":
3075
+ return [
3076
+ {
3077
+ ...item,
3078
+ cases: item.cases.map((branch) => ({
3079
+ ...branch,
3080
+ body: fold(branch.body)
3081
+ })),
3082
+ fallback: fold(item.fallback)
3083
+ }
3084
+ ];
3085
+ case "for":
3086
+ return [{ ...item, body: fold(item.body) }];
3087
+ default:
3088
+ return [item];
2348
3089
  }
2349
3090
  });
2350
- for (const variable of module.variables) {
2351
- useType(variable.type);
2352
- }
2353
- for (const fn of linkedFunctions) {
2354
- if (fn.result) {
2355
- useType(fn.result);
2356
- }
2357
- for (const variable of [...fn.parameters, ...fn.locals]) {
2358
- useType(variable.type);
2359
- }
3091
+ const functions = core.functions.map((fn) => ({
3092
+ ...fn,
3093
+ body: fold(fn.body)
3094
+ }));
3095
+ const blocks = core.blocks.map((block) => ({ ...block, body: fold(block.body) }));
3096
+ const routines = new Set([...constants.keys()].filter((id) => !called.has(id)));
3097
+ return {
3098
+ core: admitCore({
3099
+ ...core,
3100
+ functions: functions.filter((fn) => !routines.has(fn.id)),
3101
+ blocks
3102
+ }),
3103
+ routines
3104
+ };
3105
+ }
3106
+ // packages/compiler/src/ir/temporaries.ts
3107
+ function forwardTemporaries(core) {
3108
+ const functions = core.functions.map((fn) => forward(fn));
3109
+ const blocks = core.blocks.map((block) => forward(block));
3110
+ return admitCore({ ...core, functions, blocks });
3111
+ }
3112
+ function forward(routine) {
3113
+ const temporaries = new Set(routine.locals.filter((local) => isTemporary(routine.id, local)).map((local) => local.id));
3114
+ if (!temporaries.size) {
3115
+ return routine;
2360
3116
  }
2361
- for (const block of linkedBlocks) {
2362
- if (block.result) {
2363
- useType(block.result);
3117
+ const writes = new Map;
3118
+ const reads = new Map;
3119
+ const count = (counts, root) => counts.set(root, (counts.get(root) ?? 0) + 1);
3120
+ const expression = (value) => {
3121
+ if (value.kind === "load") {
3122
+ count(reads, value.root);
2364
3123
  }
2365
- for (const variable of [
2366
- ...block.inputs,
2367
- ...block.outputs,
2368
- ...block.state,
2369
- ...block.locals
2370
- ]) {
2371
- useType(variable.type);
3124
+ if (value.kind === "borrow") {
3125
+ count(writes, value.place.root);
3126
+ count(reads, value.place.root);
2372
3127
  }
2373
- }
2374
- const useTelemetryTypes = (body) => {
2375
- for (const item of body) {
2376
- if (item.kind === "telemetry") {
2377
- for (const operand of telemetryOperands(item)) {
2378
- useType(operand.type);
2379
- }
3128
+ subexpressions(value).forEach(expression);
3129
+ };
3130
+ const statements = (items) => {
3131
+ for (const item of items) {
3132
+ if (item.kind === "assign") {
3133
+ count(writes, item.root);
2380
3134
  }
2381
- for (const nested of nestedBodies(item)) {
2382
- useTelemetryTypes(nested);
3135
+ if (item.kind === "for") {
3136
+ count(writes, item.counter);
3137
+ }
3138
+ if (item.kind === "invoke" && item.destination !== undefined) {
3139
+ count(writes, item.destination);
2383
3140
  }
3141
+ statementExpressions(item).forEach(expression);
3142
+ nestedBodies(item).forEach(statements);
2384
3143
  }
2385
3144
  };
2386
- for (const routine of [...linkedFunctions, ...linkedBlocks]) {
2387
- useTelemetryTypes(routine.body);
3145
+ statements(routine.body);
3146
+ const movable = (item) => item.kind === "assign" && !item.path?.length && temporaries.has(item.root) && writes.get(item.root) === 1 && reads.get(item.root) === 1 && (item.value.kind === "load" || item.value.kind === "constant" || item.value.type === "BOOL");
3147
+ const forwarded = new Set;
3148
+ const rewrite = (items) => {
3149
+ const result = items.map((item) => withBodies(item, rewrite));
3150
+ for (let index = result.length - 2;index >= 0; index--) {
3151
+ const item = result[index];
3152
+ const next = result[index + 1];
3153
+ if (!item || !next || !movable(item) || !readsOwn(next, item.root)) {
3154
+ continue;
3155
+ }
3156
+ result.splice(index, 2, substitute(next, item.root, item.value));
3157
+ forwarded.add(item.root);
3158
+ }
3159
+ return result;
3160
+ };
3161
+ const body = rewrite(routine.body);
3162
+ if (!forwarded.size) {
3163
+ return routine;
2388
3164
  }
2389
- return usedTypes;
2390
- };
2391
-
2392
- // packages/compiler/src/ir/normalize.ts
2393
- var verifiedModules = new WeakSet;
2394
- function isVerifiedCore(value) {
2395
- return typeof value === "object" && value !== null && verifiedModules.has(value);
3165
+ return {
3166
+ ...routine,
3167
+ locals: routine.locals.filter((local) => !forwarded.has(local.id)),
3168
+ body
3169
+ };
2396
3170
  }
2397
- function freeze(value) {
2398
- if (typeof value !== "object" || value === null || Object.isFrozen(value)) {
2399
- return;
3171
+ function readsOwn(item, root) {
3172
+ if (item.kind === "for" || item.kind === "switch") {
3173
+ return false;
2400
3174
  }
2401
- for (const child of Object.values(value)) {
2402
- freeze(child);
3175
+ const reads = (value) => value.kind === "load" && value.root === root || subexpressions(value).some(reads);
3176
+ return statementExpressions(item).some(reads);
3177
+ }
3178
+ function withBodies(item, rewrite) {
3179
+ switch (item.kind) {
3180
+ case "if":
3181
+ return {
3182
+ ...item,
3183
+ then: rewrite(item.then),
3184
+ else: rewrite(item.else)
3185
+ };
3186
+ case "switch":
3187
+ return {
3188
+ ...item,
3189
+ cases: item.cases.map((branch) => ({
3190
+ ...branch,
3191
+ body: rewrite(branch.body)
3192
+ })),
3193
+ fallback: rewrite(item.fallback)
3194
+ };
3195
+ case "for":
3196
+ return { ...item, body: rewrite(item.body) };
3197
+ default:
3198
+ return item;
2403
3199
  }
2404
- Object.freeze(value);
2405
3200
  }
2406
- function normalizeModule(module) {
2407
- try {
2408
- const declarations = new ModuleDeclarations(module);
2409
- checkStaticAllocation(module, declarations);
2410
- const functions = [];
2411
- const blocks = [];
2412
- const edges = new Map;
2413
- for (const source of [...module.functions, ...module.blocks]) {
2414
- const normalized = new RoutineNormalizer(source, declarations).normalize();
2415
- edges.set(source.id, normalized.callees);
2416
- if ("inputs" in normalized.routine) {
2417
- blocks.push(normalized.routine);
2418
- } else {
2419
- functions.push(normalized.routine);
2420
- }
2421
- }
2422
- const linked = linkModule(module, declarations, functions, blocks, edges);
2423
- const core = {
2424
- ...structuredClone(linked),
2425
- [verified]: true
2426
- };
2427
- freeze(core);
2428
- verifiedModules.add(core);
2429
- return { core, diagnostics: [] };
2430
- } catch (cause) {
2431
- if (cause instanceof InvalidCore) {
2432
- return { diagnostics: [cause.diagnostic] };
3201
+ function substitute(item, root, value) {
3202
+ const replace = (expression) => {
3203
+ if (expression.kind === "load" && expression.root === root) {
3204
+ return value;
3205
+ }
3206
+ switch (expression.kind) {
3207
+ case "constant":
3208
+ return expression;
3209
+ case "load":
3210
+ return expression.path ? { ...expression, path: replacePath(expression.path) } : expression;
3211
+ case "borrow":
3212
+ return {
3213
+ ...expression,
3214
+ place: {
3215
+ ...expression.place,
3216
+ path: replacePath(expression.place.path)
3217
+ }
3218
+ };
3219
+ case "unary":
3220
+ case "convert":
3221
+ return { ...expression, operand: replace(expression.operand) };
3222
+ case "binary":
3223
+ return {
3224
+ ...expression,
3225
+ left: replace(expression.left),
3226
+ right: replace(expression.right)
3227
+ };
2433
3228
  }
2434
- throw cause;
3229
+ };
3230
+ const replacePath = (path) => path.map((segment) => segment.kind === "field" ? segment : { kind: "index", value: replace(segment.value) });
3231
+ switch (item.kind) {
3232
+ case "assign":
3233
+ return {
3234
+ ...item,
3235
+ ...item.path && { path: replacePath(item.path) },
3236
+ value: replace(item.value)
3237
+ };
3238
+ case "if":
3239
+ return { ...item, condition: replace(item.condition) };
3240
+ case "invoke":
3241
+ return {
3242
+ ...item,
3243
+ ...item.index && { index: replace(item.index) },
3244
+ arguments: item.arguments.map(replace)
3245
+ };
3246
+ case "blockUpdate":
3247
+ return {
3248
+ ...item,
3249
+ ...item.index && { index: replace(item.index) },
3250
+ inputs: Object.fromEntries(Object.entries(item.inputs).map(([name, input]) => [
3251
+ name,
3252
+ replace(input)
3253
+ ]))
3254
+ };
3255
+ case "return":
3256
+ return item.value ? { ...item, value: replace(item.value) } : item;
3257
+ case "telemetry":
3258
+ return {
3259
+ ...item,
3260
+ ...item.record.kind === "exception" && {
3261
+ record: { ...item.record, code: replace(item.record.code) }
3262
+ },
3263
+ properties: item.properties.map((property) => ({
3264
+ ...property,
3265
+ value: replace(property.value),
3266
+ ...property.length && { length: replace(property.length) }
3267
+ }))
3268
+ };
3269
+ default:
3270
+ return item;
2435
3271
  }
2436
3272
  }
2437
- // packages/compiler/src/ir/job-errors.ts
2438
- var jobErrors = {
2439
- "1": "cancelled",
2440
- "2": "timeout",
2441
- "3": "request or response too large to encode",
2442
- "4": "malformed response",
2443
- "5": "network error or server restarted",
2444
- "6": "TLS error",
2445
- "7": "no free request slot",
2446
- "10000": "HTTP status: 10000 + status code"
2447
- };
2448
- var httpErrors = { base: 1e4, last: 10999 };
2449
- var errorName = (code) => {
2450
- if (code > httpErrors.base && code <= httpErrors.last) {
2451
- return `HTTP ${code - httpErrors.base}`;
2452
- }
2453
- return code < httpErrors.base ? jobErrors[code] : undefined;
2454
- };
2455
3273
  export {
2456
3274
  aggregate,
2457
3275
  aggregateIssue,
@@ -2461,6 +3279,7 @@ export {
2461
3279
  comparisonOperators,
2462
3280
  constantFits,
2463
3281
  defaultValue,
3282
+ directWrites,
2464
3283
  domainConstantFits,
2465
3284
  domainIssue,
2466
3285
  durationLiteral,
@@ -2469,7 +3288,9 @@ export {
2469
3288
  expressionIssue,
2470
3289
  floatMaximum,
2471
3290
  fold,
3291
+ foldConstantRoutines,
2472
3292
  formatDiagnostic,
3293
+ forwardTemporaries,
2473
3294
  hasErrors,
2474
3295
  httpErrors,
2475
3296
  instancedBlock,
@@ -2477,7 +3298,9 @@ export {
2477
3298
  integerType,
2478
3299
  interval,
2479
3300
  isVerifiedCore,
3301
+ jobError,
2480
3302
  jobErrors,
3303
+ joinPrograms,
2481
3304
  layoutIssue,
2482
3305
  loopBounds,
2483
3306
  loopIterations,
@@ -2489,17 +3312,21 @@ export {
2489
3312
  nestedBodies,
2490
3313
  normalizeModule,
2491
3314
  parseInteger,
3315
+ pathIndexes,
2492
3316
  placeType,
2493
3317
  primitiveTypes,
2494
3318
  roundFloat,
2495
3319
  saturateFloat,
2496
3320
  scalarIssue,
3321
+ shareRoutines,
2497
3322
  standardBlocks,
3323
+ statementExpressions,
3324
+ subexpressions,
2498
3325
  telemetryOperands,
2499
3326
  valueFits,
2500
3327
  valueRange,
2501
3328
  wrapsNatively
2502
3329
  };
2503
3330
 
2504
- //# debugId=AD6AE5E0818FE34A64756E2164756E21
3331
+ //# debugId=EED404D57725C8B464756E2164756E21
2505
3332
  //# sourceMappingURL=ir.js.map