@tsplc/compiler 0.5.7 → 0.5.9

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 (59) hide show
  1. package/dist/bun-runtime.js +8 -2
  2. package/dist/bun-runtime.js.map +3 -3
  3. package/dist/cli.js +17 -5
  4. package/dist/cli.js.map +5 -5
  5. package/dist/codesys.js +2933 -1724
  6. package/dist/codesys.js.map +20 -19
  7. package/dist/index.js +870 -685
  8. package/dist/index.js.map +20 -19
  9. package/dist/ir.js +1654 -1364
  10. package/dist/ir.js.map +16 -14
  11. package/dist/project.js +5 -2
  12. package/dist/project.js.map +3 -3
  13. package/dist/telemetry.js +8 -2
  14. package/dist/telemetry.js.map +3 -3
  15. package/package.json +9 -9
  16. package/src/codesys/debug.ts +17 -2
  17. package/src/codesys/emit.ts +34 -11
  18. package/src/codesys/engineering.ts +27 -12
  19. package/src/codesys/explain.ts +1465 -0
  20. package/src/codesys/global-lists.ts +21 -9
  21. package/src/codesys/http.ts +12 -0
  22. package/src/codesys/instrumentation.ts +131 -3
  23. package/src/codesys/manifest.ts +29 -12
  24. package/src/codesys/numeric.ts +5 -3
  25. package/src/codesys/plan.ts +31 -28
  26. package/src/codesys/programs.ts +63 -1
  27. package/src/codesys/types.ts +34 -12
  28. package/src/frontend/async.ts +14 -8
  29. package/src/frontend/coroutines.ts +55 -16
  30. package/src/frontend/elaborate/expressions.ts +10 -2
  31. package/src/frontend/elaborate/filtered-arrays.ts +5 -5
  32. package/src/frontend/elaborate/index.ts +42 -4
  33. package/src/frontend/elaborate/model.ts +48 -1
  34. package/src/frontend/elaborate/references.ts +6 -6
  35. package/src/frontend/elaborate/specialize.ts +18 -4
  36. package/src/frontend/elaborate/storage.ts +58 -2
  37. package/src/frontend/expressions.ts +2 -2
  38. package/src/frontend/generated-names.ts +95 -0
  39. package/src/frontend/intrinsics.ts +1 -2
  40. package/src/frontend/promise-chains.ts +22 -8
  41. package/src/frontend/promises.ts +8 -10
  42. package/src/frontend/statements.ts +3 -2
  43. package/src/frontend/tasks.ts +8 -8
  44. package/src/frontend/typescript.ts +5 -2
  45. package/src/ir/conditions.ts +895 -0
  46. package/src/ir/core-model.ts +2 -2
  47. package/src/ir/fold.ts +15 -107
  48. package/src/ir/identity.ts +9 -0
  49. package/src/ir/index.ts +18 -13
  50. package/src/ir/job-errors.ts +14 -0
  51. package/src/ir/link.ts +1 -0
  52. package/src/ir/model.ts +16 -79
  53. package/src/ir/numeric.ts +5 -41
  54. package/src/ir/ranges.ts +8 -14
  55. package/src/ir/scalars.ts +6 -4
  56. package/src/ir/share.ts +0 -52
  57. package/src/project/debugger.ts +9 -0
  58. package/src/project/project.ts +6 -0
  59. package/src/project/release.ts +7 -4
package/dist/index.js CHANGED
@@ -1,9 +1,9 @@
1
1
  // packages/compiler/src/frontend/typescript.ts
2
2
  import { mkdirSync, writeFileSync as writeFileSync2 } from "node:fs";
3
3
  import { createRequire as createRequire2 } from "node:module";
4
- import { dirname as dirname7, join as join4, relative as relative5, resolve as resolve7 } from "node:path";
4
+ import { dirname as dirname7, join as join4, relative as relative8, resolve as resolve7 } from "node:path";
5
5
  import { hasErrors } from "@tsplc/compiler/ir";
6
- import ts38 from "typescript";
6
+ import ts39 from "typescript";
7
7
 
8
8
  // packages/compiler/src/frontend/analyzer.ts
9
9
  import { resolve as resolve2 } from "node:path";
@@ -902,9 +902,9 @@ import {
902
902
  narrowRanges,
903
903
  parseInteger as parseInteger3,
904
904
  placeType,
905
- roundFloat,
906
905
  valueRange
907
906
  } from "@tsplc/compiler/ir";
907
+ import { roundFloat } from "@tsplc/iec/arithmetic";
908
908
  import ts5 from "typescript";
909
909
 
910
910
  // packages/compiler/src/frontend/intrinsics.ts
@@ -912,9 +912,9 @@ import {
912
912
  calendarLiteral,
913
913
  defaultValue as defaultValue2,
914
914
  durationLiteral,
915
- elementaryFunctions,
916
915
  parseInteger as parseInteger2
917
916
  } from "@tsplc/compiler/ir";
917
+ import { elementaryFunctions } from "@tsplc/iec/arithmetic";
918
918
  import ts4 from "typescript";
919
919
  var durationScales = new Map([
920
920
  ["ms", 1000000n],
@@ -2145,9 +2145,9 @@ import {
2145
2145
  aggregate as aggregate4,
2146
2146
  integerRange as integerRange2,
2147
2147
  loopBounds,
2148
- loopIterations,
2149
2148
  maxLoopIterations
2150
2149
  } from "@tsplc/compiler/ir";
2150
+ import { loopIterations } from "@tsplc/iec/arithmetic";
2151
2151
  import ts9 from "typescript";
2152
2152
 
2153
2153
  // packages/compiler/src/frontend/telemetry.ts
@@ -2543,7 +2543,7 @@ class StatementLowering {
2543
2543
  const direction = ascending ? 1n : -1n;
2544
2544
  const finish = BigInt(bound.value) - (exclusive ? direction : 0n);
2545
2545
  const first = BigInt(start.value);
2546
- const count = loopIterations(first, finish, step);
2546
+ const count = loopIterations(first, BigInt(bound.value), exclusive, step);
2547
2547
  this.checkIterations(node, count);
2548
2548
  if (existing) {
2549
2549
  this.checkFinalIncrement(node, plcType, first + count * step);
@@ -3189,10 +3189,10 @@ import { resolve as resolve5 } from "node:path";
3189
3189
  import {
3190
3190
  error as error4
3191
3191
  } from "@tsplc/compiler/ir";
3192
- import ts14 from "typescript";
3192
+ import ts15 from "typescript";
3193
3193
 
3194
3194
  // packages/compiler/src/frontend/coroutines.ts
3195
- import { jobError as jobError2 } from "@tsplc/compiler/ir";
3195
+ import { identityDigest, jobError as jobError2, reservedErrors } from "@tsplc/compiler/ir";
3196
3196
  import ts12 from "typescript";
3197
3197
 
3198
3198
  // packages/compiler/src/frontend/configuration.ts
@@ -3631,7 +3631,8 @@ var compoundSteps = new Map([
3631
3631
  ]);
3632
3632
  var awaitedCall = (node) => ts12.isAwaitExpression(node) ? node.expression : node;
3633
3633
  var containsAwait = (node, source) => ts12.isAwaitExpression(node) || node.getChildren(source).some((child) => containsAwait(child, source));
3634
- var aliasPrefix = (fn) => `TsplcAsync${fn.name.getText(fn.getSourceFile())}${fn.getStart(fn.getSourceFile())}`;
3634
+ var aliasPrefix = (names, fn) => names.name(`TsplcAsync${fn.name.getText(fn.getSourceFile())}`, fn);
3635
+ var codeDigest = (code) => Number.parseInt(identityDigest(code), 16) || 1;
3635
3636
  function lowerCoroutine(context, file, fn) {
3636
3637
  new Coroutine(context, file, fn).lower();
3637
3638
  }
@@ -3792,7 +3793,7 @@ class Coroutine {
3792
3793
  if (called.getSourceFile() === source) {
3793
3794
  return annotated;
3794
3795
  }
3795
- const type = `${aliasPrefix(called)}Result`;
3796
+ const type = `${aliasPrefix(this.context.names, called)}Result`;
3796
3797
  const statement = `import type {${type}} from ${importSpecifier(source.fileName, called.getSourceFile().fileName)};`;
3797
3798
  if (!extra.some((item) => item.text === statement)) {
3798
3799
  extra.push(from(node, statement));
@@ -3928,7 +3929,7 @@ class Coroutine {
3928
3929
  this.context.fail(call, "GET requests cannot contain json.");
3929
3930
  }
3930
3931
  const responseType = this.text(response);
3931
- const httpName = `Tsplc${rpc ? "Rpc" : "Http"}${this.context.sequence()}`;
3932
+ const httpName = this.context.names.name(`Tsplc${rpc ? "Rpc" : "Http"}`, call);
3932
3933
  if (!json) {
3933
3934
  extra.push(from(call, `interface ${httpName}Request {reserved:BOOL}`));
3934
3935
  }
@@ -4052,6 +4053,9 @@ class ${httpName} extends FunctionBlock<${httpName}Input,${httpName}Output> { pr
4052
4053
  if (!checker.isTypeAssignableTo(checker.getTypeAtLocation(statement.expression), checker.getNumberType())) {
4053
4054
  this.context.fail(statement, "Async throw requires a numeric error code.");
4054
4055
  }
4056
+ if (ts12.isNumericLiteral(statement.expression) && Number(statement.expression.text) >= reservedErrors.first && Number(statement.expression.text) <= reservedErrors.last) {
4057
+ this.context.fail(statement, `Error codes ${reservedErrors.first} to ${reservedErrors.last} are tsPLC's own; throw another code.`);
4058
+ }
4055
4059
  return this.state(reject(this.rewrite(statement.expression)), statement, "throw");
4056
4060
  }
4057
4061
  if (ts12.isReturnStatement(statement)) {
@@ -4134,7 +4138,7 @@ class ${httpName} extends FunctionBlock<${httpName}Input,${httpName}Output> { pr
4134
4138
  const field = declaration && this.fields.get(this.context.symbol(declaration.name));
4135
4139
  return this.block(statement.tryBlock.statements, next, (error, cancellable) => {
4136
4140
  const recover = mapped`${field ? mapped`this.${field.name} = ${error};` : ""}this.step = ${caught};`;
4137
- return cancellable ? mapped`if(${error} === 1) {${this.failure(error)}} else {${recover}}` : recover;
4141
+ return cancellable ? mapped`if(${error} === ${jobError2.cancelled} || ${error} === ${jobError2.codeChanged}) {${this.failure(error)}} else {${recover}}` : recover;
4138
4142
  });
4139
4143
  }
4140
4144
  returnStatement(statement, reject) {
@@ -4163,22 +4167,38 @@ class ${httpName} extends FunctionBlock<${httpName}Input,${httpName}Output> { pr
4163
4167
  generate(entry) {
4164
4168
  const { fn, returnType, parameters } = this;
4165
4169
  const exported = hasModifier(fn, ts12.SyntaxKind.ExportKeyword) ? "export " : "";
4166
- const aliases = `export type ${aliasPrefix(fn)}Result = ${returnType};
4167
- ${parameters.map((p, i) => `export type ${aliasPrefix(fn)}Argument${i} = ${p.type};`).join(`
4170
+ const prefix = aliasPrefix(this.context.names, fn);
4171
+ const aliases = `export type ${prefix}Result = ${returnType};
4172
+ ${parameters.map((p, i) => `export type ${prefix}Argument${i} = ${p.type};`).join(`
4168
4173
  `)}`;
4169
- return mapped`${aliases}\n${exported}class ${this.text(fn.name)} extends FunctionBlock<{cancel:BOOL}> {
4170
- private step:UINT=0; private cancelling:BOOL=false; private busy:BOOL=false; private done:BOOL=false; private error:UDINT=0; private value:${returnType}=defaultValue<${returnType}>();
4174
+ const fields = `private step:UINT=0; private cancelling:BOOL=false; private busy:BOOL=false; private done:BOOL=false; private error:UDINT=0; private value:${returnType}=defaultValue<${returnType}>();
4171
4175
  ${[...this.fields.values()].map((f) => `private ${f.name}:${f.type}=defaultValue<${f.type}>();`).join(`
4172
4176
  `)}
4173
4177
  ${[...this.positionFields.values()].map((name) => `private ${name}:DINT=0;`).join(`
4174
4178
  `)}
4175
4179
  ${this.children.join(`
4176
- `)}
4177
- start(${parameters.map((p) => `${p.name}:${p.type}`).join(",")}):BOOL {if(this.busy || this.done)return false; ${parameters.map((p) => `this.${p.field} = ${copyValue(p.name, p.aggregate)};`).join(" ")} ${this.resets.join(" ")} this.value = defaultValue<${returnType}>(); this.error=0;this.cancelling=false;this.busy=true;this.done=false;this.step=${entry};return true;}
4178
- reset():void {${this.resets.join(" ")} this.busy=false;this.cancelling=false;this.done=false;this.error=0;this.step=0;}
4179
- snapshot():{busy:BOOL;done:BOOL;error:UDINT;result:${returnType}} {return {busy:this.busy,done:this.done,error:this.error,result:${copyValue("this.value", this.resultAggregate)}};}
4180
- protected execute(input:{cancel:BOOL}):void {if(!this.busy)return;if(input.cancel)this.cancelling=true;if(this.cancelling){${this.cancels.map((cancel) => `{${cancel}}`).join(" ")}${this.failure("1")}return;}for(let transition:DINT=0;transition<${this.states.size + 1};transition++){const previous:UINT=this.step;switch(this.step){${joined([...this.states].map(([id, body]) => mapped`case ${id}: {${body}} break;`), `
4181
- `)} }if(!this.busy||this.step===previous${[...this.yielding].map((id) => `||previous===${id}`).join("")})return;}}
4180
+ `)}`;
4181
+ const table = joined([...this.states].map(([id, body]) => mapped`case ${id}: {${body}} break;`), `
4182
+ `);
4183
+ const code = codeDigest([
4184
+ fields,
4185
+ parameters.map((p) => `${p.field}:${p.type}`).join(","),
4186
+ entry,
4187
+ table.text,
4188
+ this.resets.join(" "),
4189
+ this.cancels.join(" "),
4190
+ [...this.yielding].join(",")
4191
+ ].join(`
4192
+ `));
4193
+ const { codeChanged } = jobError2;
4194
+ return mapped`${aliases}\n${exported}class ${this.text(fn.name)} extends FunctionBlock<{cancel:BOOL}> {
4195
+ ${fields}
4196
+ private tsplcCode:UDINT=0; private tsplcPending:UDINT=0;
4197
+ start(${parameters.map((p) => `${p.name}:${p.type}`).join(",")}):BOOL {if(this.busy || this.done)return false; ${parameters.map((p) => `this.${p.field} = ${copyValue(p.name, p.aggregate)};`).join(" ")} ${this.resets.join(" ")} this.value = defaultValue<${returnType}>(); this.error=0;this.cancelling=false;this.tsplcPending=0;this.tsplcCode=${code};this.busy=true;this.done=false;this.step=${entry};return true;}
4198
+ reset():void {${this.resets.join(" ")} this.busy=false;this.cancelling=false;this.tsplcPending=0;this.done=false;this.error=0;this.step=0;}
4199
+ snapshot():{busy:BOOL;done:BOOL;error:UDINT;result:${returnType}} {if(this.done&&this.tsplcCode!==${code}){return {busy:false,done:true,error:${codeChanged},result:defaultValue<${returnType}>()};}return {busy:this.busy,done:this.done,error:this.error,result:${copyValue("this.value", this.resultAggregate)}};}
4200
+ protected execute(input:{cancel:BOOL}):void {if(!this.busy)return;if(this.tsplcCode!==${code}&&!this.cancelling){this.tsplcPending=${codeChanged};this.cancelling=true;}if(input.cancel)this.cancelling=true;if(this.cancelling){${this.cancels.map((cancel) => `{${cancel}}`).join(" ")}if(this.tsplcPending===0)this.tsplcPending=${jobError2.cancelled};${this.failure("this.tsplcPending")}return;}for(let transition:DINT=0;transition<${this.states.size + 1};transition++){const previous:UINT=this.step;switch(this.step){${table}
4201
+ default: {this.tsplcPending=${codeChanged};this.cancelling=true;return;} }if(!this.busy||this.step===previous${[...this.yielding].map((id) => `||previous===${id}`).join("")})return;}}
4182
4202
 
4183
4203
  }`;
4184
4204
  }
@@ -4188,7 +4208,7 @@ protected execute(input:{cancel:BOOL}):void {if(!this.busy)return;if(input.cance
4188
4208
  const worker = parsed.statements.find(ts12.isClassDeclaration);
4189
4209
  const names = new Map(worker.members.map((member) => [
4190
4210
  member.name.getText(parsed),
4191
- `tsplcAsync${this.fn.getStart(source)}_${member.name.getText(parsed)}`
4211
+ `${this.context.names.name("tsplcAsync", this.fn)}_${member.name.getText(parsed)}`
4192
4212
  ]));
4193
4213
  names.set("start", method.start);
4194
4214
  names.set("reset", method.reset);
@@ -4244,6 +4264,70 @@ protected execute(input:{cancel:BOOL}):void {if(!this.busy)return;if(input.cance
4244
4264
  }
4245
4265
  }
4246
4266
 
4267
+ // packages/compiler/src/frontend/generated-names.ts
4268
+ import { relative as relative3 } from "node:path";
4269
+ import { identityDigest as identityDigest2 } from "@tsplc/compiler/ir";
4270
+ import ts13 from "typescript";
4271
+
4272
+ class GeneratedNames {
4273
+ root;
4274
+ constructor(root) {
4275
+ this.root = root;
4276
+ }
4277
+ name(base, node) {
4278
+ return `${base}_${identityDigest2(this.identity(node))}`;
4279
+ }
4280
+ identity(node) {
4281
+ const source = node.getSourceFile();
4282
+ const module = relative3(this.root, source.fileName).replace(/\\/g, "/");
4283
+ const scopes = enclosingDeclarations(node);
4284
+ const scope = scopes.at(-1)?.node ?? source;
4285
+ const key = nodeKey(node, source);
4286
+ const ordinal = sameKey(scope, key, source).indexOf(node);
4287
+ return [
4288
+ module,
4289
+ ...scopes.map((declaration) => declaration.name),
4290
+ `${key}#${ordinal}`
4291
+ ].join("\x00");
4292
+ }
4293
+ }
4294
+ var nodeKey = (node, source) => {
4295
+ if (ts13.isCallExpression(node)) {
4296
+ return `call ${node.expression.getText(source)}`;
4297
+ }
4298
+ const name = declarationName(node);
4299
+ return name === undefined ? ts13.SyntaxKind[node.kind] : `${ts13.SyntaxKind[node.kind]} ${name}`;
4300
+ };
4301
+ var sameKey = (scope, key, source) => {
4302
+ const found = [];
4303
+ const visit = (node) => {
4304
+ if (nodeKey(node, source) === key) {
4305
+ found.push(node);
4306
+ }
4307
+ ts13.forEachChild(node, visit);
4308
+ };
4309
+ ts13.forEachChild(scope, visit);
4310
+ return found;
4311
+ };
4312
+ var declarationName = (node) => {
4313
+ if ((ts13.isClassDeclaration(node) || ts13.isFunctionDeclaration(node) || ts13.isMethodDeclaration(node) || ts13.isPropertyDeclaration(node) || ts13.isGetAccessorDeclaration(node) || ts13.isSetAccessorDeclaration(node) || ts13.isVariableDeclaration(node) || ts13.isInterfaceDeclaration(node) || ts13.isTypeAliasDeclaration(node)) && node.name && (ts13.isIdentifier(node.name) || ts13.isStringLiteral(node.name))) {
4314
+ return node.name.text;
4315
+ }
4316
+ if (ts13.isConstructorDeclaration(node)) {
4317
+ return "constructor";
4318
+ }
4319
+ return;
4320
+ };
4321
+ var enclosingDeclarations = (node) => {
4322
+ const parent = node.parent;
4323
+ if (!parent || ts13.isSourceFile(parent)) {
4324
+ return [];
4325
+ }
4326
+ const name = declarationName(parent);
4327
+ const outer = enclosingDeclarations(parent);
4328
+ return name === undefined ? outer : [...outer, { name, node: parent }];
4329
+ };
4330
+
4247
4331
  // packages/compiler/src/frontend/tasks.ts
4248
4332
  import { resolve as resolve4 } from "node:path";
4249
4333
  import {
@@ -4251,17 +4335,17 @@ import {
4251
4335
  jobError as jobError3,
4252
4336
  nanosecondsPerMillisecond
4253
4337
  } from "@tsplc/compiler/ir";
4254
- import ts13 from "typescript";
4338
+ import ts14 from "typescript";
4255
4339
  function lowerTaskDefinitions(context, file) {
4256
4340
  for (const declaration of declarations(file.source)) {
4257
4341
  const init = declaration.initializer;
4258
- if (!init || !ts13.isCallExpression(init) || !ts13.isPropertyAccessExpression(init.expression) || !context.namesSdk(init.expression.expression, "backgroundTasks") && !context.namesSdk(init.expression.expression, "cooperativeTasks") && !context.namesSdk(init.expression.expression, "tasks") || init.expression.name.text !== "define") {
4342
+ if (!init || !ts14.isCallExpression(init) || !ts14.isPropertyAccessExpression(init.expression) || !context.namesSdk(init.expression.expression, "backgroundTasks") && !context.namesSdk(init.expression.expression, "cooperativeTasks") && !context.namesSdk(init.expression.expression, "tasks") || init.expression.name.text !== "define") {
4259
4343
  continue;
4260
4344
  }
4261
4345
  const definition = {
4262
4346
  declaration,
4263
4347
  init,
4264
- owner: ts13.isPropertyDeclaration(declaration) ? declaration.parent : undefined
4348
+ owner: ts14.isPropertyDeclaration(declaration) ? declaration.parent : undefined
4265
4349
  };
4266
4350
  if (context.namesSdk(init.expression.expression, "tasks")) {
4267
4351
  taskDefinition(context, file, definition);
@@ -4273,11 +4357,11 @@ function lowerTaskDefinitions(context, file) {
4273
4357
  }
4274
4358
  }
4275
4359
  var declarations = (source) => source.statements.flatMap((statement) => {
4276
- if (ts13.isVariableStatement(statement)) {
4360
+ if (ts14.isVariableStatement(statement)) {
4277
4361
  return [...statement.declarationList.declarations];
4278
4362
  }
4279
- if (ts13.isClassDeclaration(statement)) {
4280
- return statement.members.filter(ts13.isPropertyDeclaration);
4363
+ if (ts14.isClassDeclaration(statement)) {
4364
+ return statement.members.filter(ts14.isPropertyDeclaration);
4281
4365
  }
4282
4366
  return [];
4283
4367
  });
@@ -4286,11 +4370,11 @@ function taskDefinition(context, file, definition) {
4286
4370
  const [work, ...rest] = init.arguments;
4287
4371
  const symbol = context.symbol(work ?? init);
4288
4372
  const fn = symbol && context.functions.get(symbol);
4289
- if (!ts13.isIdentifier(declaration.name) || !work || rest.length || !fn?.type) {
4373
+ if (!ts14.isIdentifier(declaration.name) || !work || rest.length || !fn?.type) {
4290
4374
  context.fail(init, "tasks.define requires one named async function with a return type.");
4291
4375
  }
4292
4376
  const { params, valueType, valueAggregate } = workTypes(context, file, fn, declaration);
4293
- const worker = `tsplcTaskWorker${context.sequence()}`;
4377
+ const worker = context.names.name("tsplcTaskWorker", declaration);
4294
4378
  const receiver = `this.${worker}`;
4295
4379
  const site = taskSite(declaration.name.text, params, {
4296
4380
  start: `${receiver}.start`,
@@ -4307,10 +4391,10 @@ function taskDefinition(context, file, definition) {
4307
4391
  function cooperativeDefinition(context, file, definition) {
4308
4392
  const { declaration, init, owner } = definition;
4309
4393
  const [work, ...rest] = init.arguments;
4310
- if (!ts13.isIdentifier(declaration.name) || !work || rest.length) {
4394
+ if (!ts14.isIdentifier(declaration.name) || !work || rest.length) {
4311
4395
  context.fail(init, "Invalid compiler-owned continuation slot.");
4312
4396
  }
4313
- const symbol = context.symbol(ts13.isPropertyAccessExpression(work) ? work.name : work);
4397
+ const symbol = context.symbol(ts14.isPropertyAccessExpression(work) ? work.name : work);
4314
4398
  const routine = symbol && context.functions.get(symbol);
4315
4399
  if (!routine) {
4316
4400
  context.fail(work, "A continuation requires a named async routine.");
@@ -4318,10 +4402,10 @@ function cooperativeDefinition(context, file, definition) {
4318
4402
  const params = routine.parameters.map((parameter, index) => ({
4319
4403
  name: `argument${index}`,
4320
4404
  type: parameter.type.getText(routine.getSourceFile()),
4321
- aggregate: Boolean(context.checker.getTypeAtLocation(parameter).flags & ts13.TypeFlags.Object)
4405
+ aggregate: Boolean(context.checker.getTypeAtLocation(parameter).flags & ts14.TypeFlags.Object)
4322
4406
  }));
4323
4407
  const method = context.methods.get(symbol);
4324
- const worker = `tsplcCooperativeWorker${context.sequence()}`;
4408
+ const worker = context.names.name("tsplcCooperativeWorker", declaration);
4325
4409
  const receiver = method ? "this" : `this.${worker}`;
4326
4410
  const site = cooperativeSite(declaration.name.text, params, {
4327
4411
  start: `${receiver}.${method?.start ?? "start"}`,
@@ -4352,7 +4436,7 @@ function placeSite(context, { source, replacements, extra }, { declaration, init
4352
4436
  ]);
4353
4437
  const field = context.symbol(declaration.name);
4354
4438
  const visit = (node) => {
4355
- if (ts13.isCallExpression(node) && ts13.isPropertyAccessExpression(node.expression) && ts13.isPropertyAccessExpression(node.expression.expression) && node.expression.expression.expression.kind === ts13.SyntaxKind.ThisKeyword && context.symbol(node.expression.expression.name) === field) {
4439
+ if (ts14.isCallExpression(node) && ts14.isPropertyAccessExpression(node.expression) && ts14.isPropertyAccessExpression(node.expression.expression) && node.expression.expression.expression.kind === ts14.SyntaxKind.ThisKeyword && context.symbol(node.expression.expression.name) === field) {
4356
4440
  const renamed = site.renames.get(node.expression.name.text);
4357
4441
  if (renamed) {
4358
4442
  replacements.push({
@@ -4362,13 +4446,13 @@ function placeSite(context, { source, replacements, extra }, { declaration, init
4362
4446
  });
4363
4447
  }
4364
4448
  }
4365
- ts13.forEachChild(node, visit);
4449
+ ts14.forEachChild(node, visit);
4366
4450
  };
4367
4451
  visit(owner);
4368
4452
  return;
4369
4453
  }
4370
- const block = `${siteClass}${context.sequence()}`;
4371
- const entry = `tsplcContinuation${context.sequence()}`;
4454
+ const block = context.names.name(siteClass, declaration);
4455
+ const entry = context.names.name("tsplcContinuation", declaration);
4372
4456
  extra.push(from(declaration, `class ${block} extends FunctionBlock<{}>{${site.body}protected execute(input:{}):void{}}
4373
4457
  export function ${entry}():void{${name}.poll();}`));
4374
4458
  replacements.push({
@@ -4389,18 +4473,18 @@ function backgroundDefinition(context, file, definition) {
4389
4473
  const { declaration, init, owner } = definition;
4390
4474
  const { source, replacements, extra } = file;
4391
4475
  const [work, options, ...rest] = init.arguments;
4392
- if (!ts13.isIdentifier(declaration.name) || !work || !options || rest.length || !ts13.isObjectLiteralExpression(options)) {
4476
+ if (!ts14.isIdentifier(declaration.name) || !work || !options || rest.length || !ts14.isObjectLiteralExpression(options)) {
4393
4477
  context.fail(declaration, "Define background tasks at module scope or as function-block fields with a named async function and scheduling options.");
4394
4478
  }
4395
4479
  const symbol = context.symbol(work);
4396
4480
  const fn = symbol && context.functions.get(symbol);
4397
- if (!fn?.type || !ts13.isTypeReferenceNode(fn.type)) {
4481
+ if (!fn?.type || !ts14.isTypeReferenceNode(fn.type)) {
4398
4482
  context.fail(init, "backgroundTasks.define requires a named async function.");
4399
4483
  }
4400
4484
  const { params, valueType, valueAggregate } = workTypes(context, file, fn, declaration);
4401
- const mailbox = `TsplcMailbox${context.sequence()}`;
4402
- const worker = `tsplcWorker${context.sequence()}`;
4403
- const entry = `tsplcBackground${context.sequence()}`;
4485
+ const mailbox = context.names.name("TsplcMailbox", declaration);
4486
+ const worker = context.names.name("tsplcWorker", declaration);
4487
+ const entry = context.names.name("tsplcBackground", declaration);
4404
4488
  const requestType = `{ready:BOOL;${params.map((p) => `${p.field}:${p.type}`).join(";")}}`;
4405
4489
  const snapshotType = `{valid:BOOL;busy:BOOL;done:BOOL;cancelRequested:BOOL;error:UDINT;result:${valueType}}`;
4406
4490
  const emptySnapshot = `{valid:true,busy:this.pending || this.active,done:this.completed,cancelRequested:this.cancelRequested,error:this.failure,result:${copyValue("this.value", valueAggregate)}}`;
@@ -4463,11 +4547,11 @@ protected execute(input:{}):void {}
4463
4547
  });
4464
4548
  }
4465
4549
  function scheduleTiming(context, source, init, options) {
4466
- const properties = new Map(options.properties.filter(ts13.isPropertyAssignment).map((property) => [property.name.getText(source), property.initializer]));
4550
+ const properties = new Map(options.properties.filter(ts14.isPropertyAssignment).map((property) => [property.name.getText(source), property.initializer]));
4467
4551
  const interval = properties.get("interval");
4468
4552
  const priority = properties.get("priority");
4469
- const [amount, ...rest] = interval && ts13.isCallExpression(interval) ? interval.arguments : [];
4470
- if (!interval || !ts13.isCallExpression(interval) || !amount || rest.length || !ts13.isNumericLiteral(amount) || !priority || !ts13.isNumericLiteral(priority) || !["ms", "seconds"].some((name) => context.namesSdk(interval.expression, name))) {
4553
+ const [amount, ...rest] = interval && ts14.isCallExpression(interval) ? interval.arguments : [];
4554
+ if (!interval || !ts14.isCallExpression(interval) || !amount || rest.length || !ts14.isNumericLiteral(amount) || !priority || !ts14.isNumericLiteral(priority) || !["ms", "seconds"].some((name) => context.namesSdk(interval.expression, name))) {
4471
4555
  context.fail(init, "Background schedules require a literal ms/seconds interval and priority.");
4472
4556
  }
4473
4557
  const milliseconds = Number(amount.text) * (context.namesSdk(interval.expression, "seconds") ? 1000 : 1);
@@ -4484,13 +4568,13 @@ function scheduleTiming(context, source, init, options) {
4484
4568
  function workTypes(context, { source, extra }, fn, declaration) {
4485
4569
  const { checker } = context;
4486
4570
  const reference = fn.type;
4487
- const returnType = reference.typeArguments[0].kind === ts13.SyntaxKind.VoidKeyword ? "BOOL" : reference.typeArguments[0].getText(fn.getSourceFile());
4571
+ const returnType = reference.typeArguments[0].kind === ts14.SyntaxKind.VoidKeyword ? "BOOL" : reference.typeArguments[0].getText(fn.getSourceFile());
4488
4572
  const promised = checker.getAwaitedType(checker.getReturnTypeOfSignature(checker.getSignatureFromDeclaration(fn)));
4489
- const valueAggregate = Boolean(promised.flags & ts13.TypeFlags.Object);
4573
+ const valueAggregate = Boolean(promised.flags & ts14.TypeFlags.Object);
4490
4574
  const parameter = (node, index, type) => ({
4491
4575
  field: `argument${index}`,
4492
4576
  name: `argument${index}`,
4493
- aggregate: Boolean(checker.getTypeAtLocation(node).flags & ts13.TypeFlags.Object),
4577
+ aggregate: Boolean(checker.getTypeAtLocation(node).flags & ts14.TypeFlags.Object),
4494
4578
  type
4495
4579
  });
4496
4580
  if (fn.getSourceFile() === source) {
@@ -4500,7 +4584,7 @@ function workTypes(context, { source, extra }, fn, declaration) {
4500
4584
  valueAggregate
4501
4585
  };
4502
4586
  }
4503
- const prefix = aliasPrefix(fn);
4587
+ const prefix = aliasPrefix(context.names, fn);
4504
4588
  const params = fn.parameters.map((node, index) => parameter(node, index, `${prefix}Argument${index}`));
4505
4589
  const valueType = `${prefix}Result`;
4506
4590
  extra.push(from(declaration, `import type {${valueType},${params.map((p) => p.type).join(",")}} from ${importSpecifier(source.fileName, fn.getSourceFile().fileName)};`));
@@ -4508,9 +4592,9 @@ function workTypes(context, { source, extra }, fn, declaration) {
4508
4592
  }
4509
4593
 
4510
4594
  // packages/compiler/src/frontend/async.ts
4511
- var isAsyncRoutine = (node) => (ts14.isFunctionDeclaration(node) || ts14.isMethodDeclaration(node)) && node.name !== undefined && hasModifier(node, ts14.SyntaxKind.AsyncKeyword);
4595
+ var isAsyncRoutine = (node) => (ts15.isFunctionDeclaration(node) || ts15.isMethodDeclaration(node)) && node.name !== undefined && hasModifier(node, ts15.SyntaxKind.AsyncKeyword);
4512
4596
  var asyncDiagnostic = (positions, node, message) => error4("PLC1010", message, positions.node(node));
4513
- var lowerAsync = (program, sdk, positions) => {
4597
+ var lowerAsync = (program, sdk, positions, root) => {
4514
4598
  const result = {
4515
4599
  sources: new Map,
4516
4600
  blocks: new Map,
@@ -4525,11 +4609,11 @@ var lowerAsync = (program, sdk, positions) => {
4525
4609
  const fail = (node, message) => {
4526
4610
  throw new SemanticError(asyncDiagnostic(positions, node, message));
4527
4611
  };
4528
- const { functions, methods } = asyncRoutines(program, symbol);
4612
+ const names = new GeneratedNames(root);
4613
+ const { functions, methods } = asyncRoutines(program, symbol, names);
4529
4614
  if (!functions.size) {
4530
4615
  return result;
4531
4616
  }
4532
- let sequence = 0;
4533
4617
  const context = {
4534
4618
  checker,
4535
4619
  positions,
@@ -4541,7 +4625,7 @@ var lowerAsync = (program, sdk, positions) => {
4541
4625
  symbol,
4542
4626
  namesSdk: (node, name) => namesSdk(checker, sdk, node, name),
4543
4627
  fail,
4544
- sequence: () => sequence++
4628
+ names
4545
4629
  };
4546
4630
  const sources = runtimeSources(program).filter((source) => !source.isDeclarationFile);
4547
4631
  for (const source of sources) {
@@ -4552,7 +4636,7 @@ var lowerAsync = (program, sdk, positions) => {
4552
4636
  }
4553
4637
  return result;
4554
4638
  };
4555
- function asyncRoutines(program, symbol) {
4639
+ function asyncRoutines(program, symbol, names) {
4556
4640
  const functions = new Map;
4557
4641
  const methods = new Map;
4558
4642
  for (const source of runtimeSources(program)) {
@@ -4560,14 +4644,14 @@ function asyncRoutines(program, symbol) {
4560
4644
  continue;
4561
4645
  }
4562
4646
  for (const statement of source.statements) {
4563
- const routines = ts14.isClassDeclaration(statement) ? statement.members.filter(ts14.isMethodDeclaration) : [statement];
4647
+ const routines = ts15.isClassDeclaration(statement) ? statement.members.filter(ts15.isMethodDeclaration) : [statement];
4564
4648
  for (const fn of routines) {
4565
4649
  if (!isAsyncRoutine(fn)) {
4566
4650
  continue;
4567
4651
  }
4568
4652
  functions.set(symbol(fn.name), fn);
4569
- if (ts14.isMethodDeclaration(fn)) {
4570
- const prefix = `tsplcAsync${fn.name.getText(source)}${fn.getStart(source)}`;
4653
+ if (ts15.isMethodDeclaration(fn)) {
4654
+ const prefix = names.name(`tsplcAsync${fn.name.getText(source)}`, fn);
4571
4655
  methods.set(symbol(fn.name), {
4572
4656
  start: `${prefix}Start`,
4573
4657
  reset: `${prefix}Reset`,
@@ -4596,10 +4680,10 @@ function rewriteSource(context, source) {
4596
4680
  }
4597
4681
  const added = joined(extra, `
4598
4682
  `);
4599
- const generated = ts14.createSourceFile(source.fileName, added.text, ts14.ScriptTarget.Latest, true);
4683
+ const generated = ts15.createSourceFile(source.fileName, added.text, ts15.ScriptTarget.Latest, true);
4600
4684
  const part = (node) => slice(added, node.getStart(generated), node.end);
4601
- const before = generated.statements.filter(ts14.isClassDeclaration).map(part);
4602
- const after = generated.statements.filter((statement) => !ts14.isClassDeclaration(statement)).map(part);
4685
+ const before = generated.statements.filter(ts15.isClassDeclaration).map(part);
4686
+ const after = generated.statements.filter((statement) => !ts15.isClassDeclaration(statement)).map(part);
4603
4687
  context.result.sources.set(source.fileName, mapped`${joined(before, `
4604
4688
  `)}\n${edited(source, replacements)}\n${joined(after, `
4605
4689
  `)}`);
@@ -4618,17 +4702,17 @@ function addInstanceEntries(context, source) {
4618
4702
  const jobs = instance && context.ownedJobs.get(context.symbol(instance.block));
4619
4703
  const polls = instance && context.ownedContinuations.get(context.symbol(instance.block));
4620
4704
  if (!instance || !jobs && !polls) {
4621
- ts14.forEachChild(node, visit);
4705
+ ts15.forEachChild(node, visit);
4622
4706
  return;
4623
4707
  }
4624
4708
  const declaration = node.parent;
4625
- if (!ts14.isVariableDeclaration(declaration) || !ts14.isIdentifier(declaration.name) || !ts14.isVariableDeclarationList(declaration.parent) || !ts14.isVariableStatement(declaration.parent.parent) || !ts14.isSourceFile(declaration.parent.parent.parent) || jobs && instance.first !== undefined) {
4709
+ if (!ts15.isVariableDeclaration(declaration) || !ts15.isIdentifier(declaration.name) || !ts15.isVariableDeclarationList(declaration.parent) || !ts15.isVariableStatement(declaration.parent.parent) || !ts15.isSourceFile(declaration.parent.parent.parent) || jobs && instance.first !== undefined) {
4626
4710
  result.diagnostics.push(asyncDiagnostic(positions, node, "Function blocks with background jobs require module-level named instances."));
4627
4711
  return;
4628
4712
  }
4629
4713
  const name = declaration.name.text;
4630
4714
  if (polls?.length) {
4631
- const entry = `tsplcContinuation${context.sequence()}`;
4715
+ const entry = context.names.name("tsplcContinuation", declaration);
4632
4716
  const calls = polls.map((poll) => instance.first === undefined ? `${name}.${poll}();` : `for(let element:DINT=${instance.first};element<=${instance.last};element++){${name}[element].${poll}();}`);
4633
4717
  entries.push(from(node, `export function ${entry}():void{${calls.join("")}}`));
4634
4718
  result.programs[entry] = {
@@ -4641,7 +4725,7 @@ function addInstanceEntries(context, source) {
4641
4725
  });
4642
4726
  }
4643
4727
  for (const job of jobs ?? []) {
4644
- const entry = `tsplcBackground${context.sequence()}`;
4728
+ const entry = context.names.name(`tsplcBackground_${job.method}`, declaration);
4645
4729
  entries.push(from(node, `export function ${entry}():void{${name}.${job.method}();}`));
4646
4730
  result.programs[entry] = {
4647
4731
  module: resolve5(source.fileName),
@@ -4649,7 +4733,7 @@ function addInstanceEntries(context, source) {
4649
4733
  };
4650
4734
  result.schedules.set(entry, { ...job.schedule, worker: name });
4651
4735
  }
4652
- ts14.forEachChild(node, visit);
4736
+ ts15.forEachChild(node, visit);
4653
4737
  };
4654
4738
  visit(source);
4655
4739
  if (entries.length) {
@@ -4658,12 +4742,12 @@ function addInstanceEntries(context, source) {
4658
4742
  }
4659
4743
  }
4660
4744
  function allocatedInstances(checker, source, node) {
4661
- if (ts14.isNewExpression(node)) {
4745
+ if (ts15.isNewExpression(node)) {
4662
4746
  return { block: node.expression };
4663
4747
  }
4664
- const type = ts14.isCallExpression(node) ? node.typeArguments?.[0] : undefined;
4665
- const [element, length, lower] = type && ts14.isTypeReferenceNode(type) && type.typeName.getText(source) === "FixedArray" ? type.typeArguments ?? [] : [];
4666
- if (!element || !ts14.isTypeReferenceNode(element) || !length) {
4748
+ const type = ts15.isCallExpression(node) ? node.typeArguments?.[0] : undefined;
4749
+ const [element, length, lower] = type && ts15.isTypeReferenceNode(type) && type.typeName.getText(source) === "FixedArray" ? type.typeArguments ?? [] : [];
4750
+ if (!element || !ts15.isTypeReferenceNode(element) || !length) {
4667
4751
  return;
4668
4752
  }
4669
4753
  const integer = (node) => {
@@ -4680,16 +4764,16 @@ function allocatedInstances(checker, source, node) {
4680
4764
 
4681
4765
  // packages/compiler/src/frontend/const-functions.ts
4682
4766
  import { error as error5 } from "@tsplc/compiler/ir";
4683
- import ts15 from "typescript";
4767
+ import ts16 from "typescript";
4684
4768
  var functionBody = (body, result) => {
4685
- if (ts15.isBlock(body)) {
4769
+ if (ts16.isBlock(body)) {
4686
4770
  return copied(body);
4687
4771
  }
4688
- return result?.kind === ts15.SyntaxKind.VoidKeyword ? mapped`{ ${copied(body)}; }` : mapped`{ return ${copied(body)}; }`;
4772
+ return result?.kind === ts16.SyntaxKind.VoidKeyword ? mapped`{ ${copied(body)}; }` : mapped`{ return ${copied(body)}; }`;
4689
4773
  };
4690
4774
  var lowerConstFunctions = (program, positions) => {
4691
4775
  const checker = program.getTypeChecker();
4692
- const printer = ts15.createPrinter();
4776
+ const printer = ts16.createPrinter();
4693
4777
  const sources = new Map;
4694
4778
  const diagnostics = [];
4695
4779
  for (const source of runtimeSources(program)) {
@@ -4698,14 +4782,14 @@ var lowerConstFunctions = (program, positions) => {
4698
4782
  }
4699
4783
  const edits = [];
4700
4784
  for (const statement of source.statements) {
4701
- const routines = ts15.isClassDeclaration(statement) ? statement.members.filter(ts15.isMethodDeclaration) : [statement];
4785
+ const routines = ts16.isClassDeclaration(statement) ? statement.members.filter(ts16.isMethodDeclaration) : [statement];
4702
4786
  for (const routine of routines) {
4703
- if (!ts15.isFunctionDeclaration(routine) && !ts15.isMethodDeclaration(routine) || routine.type || !routine.body || !routine.modifiers?.some((item) => item.kind === ts15.SyntaxKind.AsyncKeyword)) {
4787
+ if (!ts16.isFunctionDeclaration(routine) && !ts16.isMethodDeclaration(routine) || routine.type || !routine.body || !routine.modifiers?.some((item) => item.kind === ts16.SyntaxKind.AsyncKeyword)) {
4704
4788
  continue;
4705
4789
  }
4706
4790
  const signature = checker.getSignatureFromDeclaration(routine);
4707
4791
  const result = signature && checker.getAwaitedType(checker.getReturnTypeOfSignature(signature));
4708
- if (result && result.flags & ts15.TypeFlags.Void) {
4792
+ if (result && result.flags & ts16.TypeFlags.Void) {
4709
4793
  const position = routine.body.getStart(source);
4710
4794
  edits.push({
4711
4795
  start: position,
@@ -4716,32 +4800,32 @@ var lowerConstFunctions = (program, positions) => {
4716
4800
  }
4717
4801
  }
4718
4802
  for (const statement of source.statements) {
4719
- if (!ts15.isVariableStatement(statement) || !statement.declarationList.declarations.some((declaration) => declaration.initializer && ts15.isArrowFunction(declaration.initializer))) {
4803
+ if (!ts16.isVariableStatement(statement) || !statement.declarationList.declarations.some((declaration) => declaration.initializer && ts16.isArrowFunction(declaration.initializer))) {
4720
4804
  continue;
4721
4805
  }
4722
- const print = (node) => printer.printNode(ts15.EmitHint.Unspecified, node, source);
4806
+ const print = (node) => printer.printNode(ts16.EmitHint.Unspecified, node, source);
4723
4807
  const declarations = [];
4724
4808
  for (const declaration of statement.declarationList.declarations) {
4725
4809
  const arrow = declaration.initializer;
4726
- if (!arrow || !ts15.isArrowFunction(arrow)) {
4727
- declarations.push(from(declaration, print(ts15.factory.updateVariableStatement(statement, statement.modifiers, ts15.factory.updateVariableDeclarationList(statement.declarationList, [declaration])))));
4810
+ if (!arrow || !ts16.isArrowFunction(arrow)) {
4811
+ declarations.push(from(declaration, print(ts16.factory.updateVariableStatement(statement, statement.modifiers, ts16.factory.updateVariableDeclarationList(statement.declarationList, [declaration])))));
4728
4812
  continue;
4729
4813
  }
4730
- if (!(statement.declarationList.flags & ts15.NodeFlags.Const) || !ts15.isIdentifier(declaration.name)) {
4814
+ if (!(statement.declarationList.flags & ts16.NodeFlags.Const) || !ts16.isIdentifier(declaration.name)) {
4731
4815
  diagnostics.push(error5("PLC1007", "PLC routines require named const bindings; mutable function values are unsupported.", positions.node(declaration)));
4732
4816
  continue;
4733
4817
  }
4734
- const contextual = declaration.type && ts15.isFunctionTypeNode(declaration.type) ? declaration.type : undefined;
4818
+ const contextual = declaration.type && ts16.isFunctionTypeNode(declaration.type) ? declaration.type : undefined;
4735
4819
  const signature = checker.getTypeAtLocation(declaration.name).getCallSignatures()[0];
4736
- const returnsVoid = signature && Boolean(checker.getReturnTypeOfSignature(signature).flags & ts15.TypeFlags.Void);
4820
+ const returnsVoid = signature && Boolean(checker.getReturnTypeOfSignature(signature).flags & ts16.TypeFlags.Void);
4737
4821
  const inferredResult = signature && checker.getAwaitedType(checker.getReturnTypeOfSignature(signature));
4738
- const asyncVoid = arrow.modifiers?.some((item) => item.kind === ts15.SyntaxKind.AsyncKeyword) && inferredResult && inferredResult.flags & ts15.TypeFlags.Void;
4739
- const inferredType = asyncVoid ? ts15.factory.createTypeReferenceNode("Promise", [
4740
- ts15.factory.createKeywordTypeNode(ts15.SyntaxKind.VoidKeyword)
4822
+ const asyncVoid = arrow.modifiers?.some((item) => item.kind === ts16.SyntaxKind.AsyncKeyword) && inferredResult && inferredResult.flags & ts16.TypeFlags.Void;
4823
+ const inferredType = asyncVoid ? ts16.factory.createTypeReferenceNode("Promise", [
4824
+ ts16.factory.createKeywordTypeNode(ts16.SyntaxKind.VoidKeyword)
4741
4825
  ]) : undefined;
4742
- const result = arrow.type ?? contextual?.type ?? (returnsVoid ? ts15.factory.createKeywordTypeNode(ts15.SyntaxKind.VoidKeyword) : inferredType);
4743
- const parameters = arrow.parameters.map((parameter, index) => ts15.factory.updateParameterDeclaration(parameter, parameter.modifiers, parameter.dotDotDotToken, parameter.name, parameter.questionToken, parameter.type ?? contextual?.parameters[index]?.type, parameter.initializer));
4744
- const head = print(ts15.factory.createFunctionDeclaration([...statement.modifiers ?? [], ...arrow.modifiers ?? []], undefined, declaration.name, arrow.typeParameters ?? contextual?.typeParameters, parameters, result, ts15.factory.createBlock([]))).replace(/\{\s*\}$/, "");
4826
+ const result = arrow.type ?? contextual?.type ?? (returnsVoid ? ts16.factory.createKeywordTypeNode(ts16.SyntaxKind.VoidKeyword) : inferredType);
4827
+ const parameters = arrow.parameters.map((parameter, index) => ts16.factory.updateParameterDeclaration(parameter, parameter.modifiers, parameter.dotDotDotToken, parameter.name, parameter.questionToken, parameter.type ?? contextual?.parameters[index]?.type, parameter.initializer));
4828
+ const head = print(ts16.factory.createFunctionDeclaration([...statement.modifiers ?? [], ...arrow.modifiers ?? []], undefined, declaration.name, arrow.typeParameters ?? contextual?.typeParameters, parameters, result, ts16.factory.createBlock([]))).replace(/\{\s*\}$/, "");
4745
4829
  declarations.push(from(declaration, mapped`${head}${functionBody(arrow.body, result)}`));
4746
4830
  }
4747
4831
  edits.push({
@@ -4759,17 +4843,17 @@ var lowerConstFunctions = (program, positions) => {
4759
4843
  };
4760
4844
 
4761
4845
  // packages/compiler/src/frontend/control-flow.ts
4762
- import ts16 from "typescript";
4846
+ import ts17 from "typescript";
4763
4847
  var unique = (pending) => [
4764
4848
  ...new Map(pending.map((item) => [item.flag, item])).values()
4765
4849
  ];
4766
4850
  var anyOf = (pending) => unique(pending).map((item) => item.flag).join(" || ");
4767
4851
  var unbraced2 = (statements) => {
4768
4852
  const [only, ...others] = statements;
4769
- return only && !others.length && ts16.isBlock(only) ? only.statements : statements;
4853
+ return only && !others.length && ts17.isBlock(only) ? only.statements : statements;
4770
4854
  };
4771
- var isJump = (statement) => statement !== undefined && (ts16.isBreakStatement(statement) || ts16.isContinueStatement(statement) || ts16.isReturnStatement(statement) || ts16.isThrowStatement(statement));
4772
- var containsAwaitOrThrow = (node) => ts16.isAwaitExpression(node) || ts16.isThrowStatement(node) || !ts16.isFunctionLike(node) && (ts16.forEachChild(node, containsAwaitOrThrow) ?? false);
4855
+ var isJump = (statement) => statement !== undefined && (ts17.isBreakStatement(statement) || ts17.isContinueStatement(statement) || ts17.isReturnStatement(statement) || ts17.isThrowStatement(statement));
4856
+ var containsAwaitOrThrow = (node) => ts17.isAwaitExpression(node) || ts17.isThrowStatement(node) || !ts17.isFunctionLike(node) && (ts17.forEachChild(node, containsAwaitOrThrow) ?? false);
4773
4857
  var isNative = (kind, target, crossing) => {
4774
4858
  if (crossing.some((item) => item.kind === "finally" && item.region !== "finally")) {
4775
4859
  return false;
@@ -4847,29 +4931,29 @@ var lower = (node, routine) => {
4847
4931
  return lowered;
4848
4932
  };
4849
4933
  var lowerStatement = (node, routine) => {
4850
- if (ts16.isLabeledStatement(node)) {
4934
+ if (ts17.isLabeledStatement(node)) {
4851
4935
  return labelled(node, routine);
4852
4936
  }
4853
- if (ts16.isIterationStatement(node, false)) {
4937
+ if (ts17.isIterationStatement(node, false)) {
4854
4938
  return loop(node, [], routine);
4855
4939
  }
4856
- if (ts16.isSwitchStatement(node)) {
4940
+ if (ts17.isSwitchStatement(node)) {
4857
4941
  return switchStatement(node, [], routine);
4858
4942
  }
4859
- if (ts16.isBlock(node)) {
4943
+ if (ts17.isBlock(node)) {
4860
4944
  const list = lowerList(node.statements, undefined, routine);
4861
4945
  return {
4862
4946
  text: from(node, mapped`{ ${joined(list.parts, " ")} }`),
4863
4947
  pending: list.pending
4864
4948
  };
4865
4949
  }
4866
- if (ts16.isIfStatement(node)) {
4950
+ if (ts17.isIfStatement(node)) {
4867
4951
  return ifStatement(node, routine);
4868
4952
  }
4869
- if (ts16.isTryStatement(node)) {
4953
+ if (ts17.isTryStatement(node)) {
4870
4954
  return node.finallyBlock ? finallyStatement(node, node.finallyBlock, routine) : tryStatement(node, routine);
4871
4955
  }
4872
- if (ts16.isBreakStatement(node) || ts16.isContinueStatement(node) || ts16.isReturnStatement(node)) {
4956
+ if (ts17.isBreakStatement(node) || ts17.isContinueStatement(node) || ts17.isReturnStatement(node)) {
4873
4957
  return jump(node, routine);
4874
4958
  }
4875
4959
  return { text: copied(node), pending: [] };
@@ -4877,10 +4961,10 @@ var lowerStatement = (node, routine) => {
4877
4961
  var labelled = (node, routine) => {
4878
4962
  routine.changes++;
4879
4963
  const { labels, inner } = unlabelled(node);
4880
- if (ts16.isIterationStatement(inner, false)) {
4964
+ if (ts17.isIterationStatement(inner, false)) {
4881
4965
  return loop(inner, labels, routine);
4882
4966
  }
4883
- if (ts16.isSwitchStatement(inner)) {
4967
+ if (ts17.isSwitchStatement(inner)) {
4884
4968
  return switchStatement(inner, labels, routine);
4885
4969
  }
4886
4970
  const target = { kind: "labelled", labels };
@@ -4893,7 +4977,7 @@ var labelled = (node, routine) => {
4893
4977
  };
4894
4978
  };
4895
4979
  var unlabelled = (node) => {
4896
- if (!ts16.isLabeledStatement(node.statement)) {
4980
+ if (!ts17.isLabeledStatement(node.statement)) {
4897
4981
  return { labels: [node.label.text], inner: node.statement };
4898
4982
  }
4899
4983
  const nested = unlabelled(node.statement);
@@ -4904,7 +4988,7 @@ var loop = (node, labels, routine) => {
4904
4988
  const target = { kind: "loop", labels };
4905
4989
  routine.stack.push(target);
4906
4990
  const body = node.statement;
4907
- const list = lowerList(ts16.isBlock(body) ? body.statements : [body], target, routine);
4991
+ const list = lowerList(ts17.isBlock(body) ? body.statements : [body], target, routine);
4908
4992
  routine.stack.pop();
4909
4993
  if (routine.changes === before && !list.pending.length) {
4910
4994
  return { text: copied(node), pending: [] };
@@ -4940,7 +5024,7 @@ var switchStatement = (node, labels, routine) => {
4940
5024
  const bodies = node.caseBlock.clauses.map((clause) => unbraced2(clause.statements));
4941
5025
  const pending = [];
4942
5026
  const clauses = node.caseBlock.clauses.map((clause, index) => {
4943
- const label = ts16.isCaseClause(clause) ? mapped`case ${copied(clause.expression)}:` : "default:";
5027
+ const label = ts17.isCaseClause(clause) ? mapped`case ${copied(clause.expression)}:` : "default:";
4944
5028
  if (!bodies[index]?.length) {
4945
5029
  return from(clause, label);
4946
5030
  }
@@ -4959,7 +5043,7 @@ var switchStatement = (node, labels, routine) => {
4959
5043
  }
4960
5044
  const last = chain.at(-1) ?? [];
4961
5045
  const end = last.at(-1);
4962
- const ending = end && ts16.isBreakStatement(end) && !end.label ? last.slice(0, -1) : last;
5046
+ const ending = end && ts17.isBreakStatement(end) && !end.label ? last.slice(0, -1) : last;
4963
5047
  const pieces = [...chain.slice(0, -1), ending];
4964
5048
  const items = pieces.length === 1 ? statementItems(ending, routine) : pieces.map((piece) => ({
4965
5049
  origin: piece[0] ?? clause,
@@ -4973,7 +5057,7 @@ var switchStatement = (node, labels, routine) => {
4973
5057
  }));
4974
5058
  const list = lowerItems(items, undefined);
4975
5059
  pending.push(...list.pending);
4976
- const returns = end !== undefined && (ts16.isReturnStatement(end) || ts16.isThrowStatement(end)) && !list.pending.length;
5060
+ const returns = end !== undefined && (ts17.isReturnStatement(end) || ts17.isThrowStatement(end)) && !list.pending.length;
4977
5061
  const body = joined(list.parts, " ");
4978
5062
  return from(clause, returns ? mapped`${label} { ${body} }` : mapped`${label} { ${body} } break;`);
4979
5063
  });
@@ -5070,8 +5154,8 @@ var caughtAttempt = (node, attempt, caught, routine) => {
5070
5154
  };
5071
5155
  };
5072
5156
  var jump = (node, routine) => {
5073
- const kind = ts16.isBreakStatement(node) ? "break" : ts16.isContinueStatement(node) ? "continue" : "return";
5074
- const label = ts16.isBreakStatement(node) || ts16.isContinueStatement(node) ? node.label?.text : undefined;
5157
+ const kind = ts17.isBreakStatement(node) ? "break" : ts17.isContinueStatement(node) ? "continue" : "return";
5158
+ const label = ts17.isBreakStatement(node) || ts17.isContinueStatement(node) ? node.label?.text : undefined;
5075
5159
  const index = targetIndex(kind, label, routine.stack);
5076
5160
  if (index === undefined) {
5077
5161
  return { text: copied(node), pending: [] };
@@ -5087,7 +5171,7 @@ var jump = (node, routine) => {
5087
5171
  }
5088
5172
  routine.changes++;
5089
5173
  const flag = flagFor(kind, target, routine);
5090
- const value = ts16.isReturnStatement(node) && node.expression && routine.result?.value ? mapped`${routine.result.value} = ${copied(node.expression)}; ` : "";
5174
+ const value = ts17.isReturnStatement(node) && node.expression && routine.result?.value ? mapped`${routine.result.value} = ${copied(node.expression)}; ` : "";
5091
5175
  const exit = innermostExit(crossing) === "loop" ? " break;" : "";
5092
5176
  return {
5093
5177
  text: from(node, mapped`{ ${flag} = true; ${value}${exit} }`),
@@ -5109,16 +5193,16 @@ var flagFor = (kind, target, routine) => {
5109
5193
  target.breakFlag ??= routine.name("tsplcBreak");
5110
5194
  return target.breakFlag;
5111
5195
  };
5112
- var isRoutine = (node) => ts16.isFunctionDeclaration(node) || ts16.isMethodDeclaration(node) || ts16.isGetAccessorDeclaration(node) || ts16.isSetAccessorDeclaration(node) || ts16.isConstructorDeclaration(node) || ts16.isArrowFunction(node) || ts16.isFunctionExpression(node);
5196
+ var isRoutine = (node) => ts17.isFunctionDeclaration(node) || ts17.isMethodDeclaration(node) || ts17.isGetAccessorDeclaration(node) || ts17.isSetAccessorDeclaration(node) || ts17.isConstructorDeclaration(node) || ts17.isArrowFunction(node) || ts17.isFunctionExpression(node);
5113
5197
  var resultType = (node, checker) => {
5114
- if (ts16.isConstructorDeclaration(node) || ts16.isSetAccessorDeclaration(node)) {
5198
+ if (ts17.isConstructorDeclaration(node) || ts17.isSetAccessorDeclaration(node)) {
5115
5199
  return;
5116
5200
  }
5117
5201
  const annotation = node.type;
5118
- const isAsync = node.modifiers?.some((modifier) => modifier.kind === ts16.SyntaxKind.AsyncKeyword);
5202
+ const isAsync = node.modifiers?.some((modifier) => modifier.kind === ts17.SyntaxKind.AsyncKeyword);
5119
5203
  if (annotation) {
5120
- const inner = isAsync && ts16.isTypeReferenceNode(annotation) && annotation.typeName.getText() === "Promise" ? annotation.typeArguments?.[0] : annotation;
5121
- if (!inner || inner.kind === ts16.SyntaxKind.VoidKeyword) {
5204
+ const inner = isAsync && ts17.isTypeReferenceNode(annotation) && annotation.typeName.getText() === "Promise" ? annotation.typeArguments?.[0] : annotation;
5205
+ if (!inner || inner.kind === ts17.SyntaxKind.VoidKeyword) {
5122
5206
  return;
5123
5207
  }
5124
5208
  return inner.getText();
@@ -5129,7 +5213,7 @@ var resultType = (node, checker) => {
5129
5213
  }
5130
5214
  const returns = checker.getReturnTypeOfSignature(signature);
5131
5215
  const awaited = isAsync ? checker.getAwaitedType(returns) : returns;
5132
- if (!awaited || awaited.flags & ts16.TypeFlags.Void) {
5216
+ if (!awaited || awaited.flags & ts17.TypeFlags.Void) {
5133
5217
  return;
5134
5218
  }
5135
5219
  return checker.typeToString(awaited);
@@ -5155,14 +5239,14 @@ var lowerControlFlow = (program) => {
5155
5239
  const uses = new Set;
5156
5240
  const name = (base) => `${base}${++counter}`;
5157
5241
  const visit = (node) => {
5158
- if (!isRoutine(node) || !node.body || !ts16.isBlock(node.body)) {
5159
- ts16.forEachChild(node, visit);
5242
+ if (!isRoutine(node) || !node.body || !ts17.isBlock(node.body)) {
5243
+ ts17.forEachChild(node, visit);
5160
5244
  return;
5161
5245
  }
5162
5246
  const body = node.body;
5163
5247
  const routine = {
5164
5248
  source,
5165
- async: Boolean(node.modifiers?.some((modifier) => modifier.kind === ts16.SyntaxKind.AsyncKeyword)),
5249
+ async: Boolean(node.modifiers?.some((modifier) => modifier.kind === ts17.SyntaxKind.AsyncKeyword)),
5166
5250
  stack: [],
5167
5251
  resultType: resultType(node, checker),
5168
5252
  changes: 0,
@@ -5171,7 +5255,7 @@ var lowerControlFlow = (program) => {
5171
5255
  };
5172
5256
  const list = lowerList(body.statements, undefined, routine);
5173
5257
  if (!routine.changes) {
5174
- ts16.forEachChild(node, visit);
5258
+ ts17.forEachChild(node, visit);
5175
5259
  return;
5176
5260
  }
5177
5261
  const declarations = [];
@@ -5207,15 +5291,16 @@ var lowerControlFlow = (program) => {
5207
5291
  };
5208
5292
 
5209
5293
  // packages/compiler/src/frontend/elaborate/index.ts
5210
- import { dirname as dirname5, join as join2, resolve as resolve6 } from "node:path";
5294
+ import { dirname as dirname5, join as join2, relative as relative6, resolve as resolve6 } from "node:path";
5211
5295
  import {
5212
- error as error6
5296
+ error as error6,
5297
+ identityDigest as identityDigest6
5213
5298
  } from "@tsplc/compiler/ir";
5214
5299
  import { generatedDirectory } from "@tsplc/config/project-files";
5215
- import ts33 from "typescript";
5300
+ import ts34 from "typescript";
5216
5301
 
5217
5302
  // packages/compiler/src/frontend/elaborate/generics.ts
5218
- import ts17 from "typescript";
5303
+ import ts18 from "typescript";
5219
5304
  var typeQueries = new Set([
5220
5305
  "getTypeAtLocation",
5221
5306
  "getTypeOfSymbol",
@@ -5227,7 +5312,7 @@ var typeQueries = new Set([
5227
5312
  "getIndexTypeOfType",
5228
5313
  "getBaseTypeOfLiteralType"
5229
5314
  ]);
5230
- var isTypeReference = (type) => Boolean(type.flags & ts17.TypeFlags.Object) && ("objectFlags" in type) && typeof type.objectFlags === "number" && Boolean(type.objectFlags & ts17.ObjectFlags.Reference);
5315
+ var isTypeReference = (type) => Boolean(type.flags & ts18.TypeFlags.Object) && ("objectFlags" in type) && typeof type.objectFlags === "number" && Boolean(type.objectFlags & ts18.ObjectFlags.Reference);
5231
5316
 
5232
5317
  class GenericTypes {
5233
5318
  base;
@@ -5279,7 +5364,7 @@ class GenericTypes {
5279
5364
  if (!this.scopes.length) {
5280
5365
  return type;
5281
5366
  }
5282
- if (type.flags & ts17.TypeFlags.TypeParameter) {
5367
+ if (type.flags & ts18.TypeFlags.TypeParameter) {
5283
5368
  for (let index = this.scopes.length - 1;index >= 0; index--) {
5284
5369
  const found = this.scopes[index]?.get(type);
5285
5370
  if (found) {
@@ -5321,7 +5406,7 @@ import {
5321
5406
  import { tmpdir } from "node:os";
5322
5407
  import { join } from "node:path";
5323
5408
  import { fileURLToPath } from "node:url";
5324
- import ts18 from "typescript";
5409
+ import ts19 from "typescript";
5325
5410
  import { z as z2 } from "zod";
5326
5411
 
5327
5412
  // packages/compiler/src/frontend/elaborate/capture-protocol.ts
@@ -5423,31 +5508,31 @@ var bindingNames = (source) => {
5423
5508
  functions: []
5424
5509
  };
5425
5510
  const bind = (name) => {
5426
- if (ts18.isIdentifier(name)) {
5511
+ if (ts19.isIdentifier(name)) {
5427
5512
  found.values.push(name.text);
5428
5513
  } else {
5429
5514
  for (const element of name.elements) {
5430
- if (!ts18.isOmittedExpression(element)) {
5515
+ if (!ts19.isOmittedExpression(element)) {
5431
5516
  bind(element.name);
5432
5517
  }
5433
5518
  }
5434
5519
  }
5435
5520
  };
5436
5521
  for (const statement of source.statements) {
5437
- if (ts18.isVariableStatement(statement)) {
5522
+ if (ts19.isVariableStatement(statement)) {
5438
5523
  for (const declaration of statement.declarationList.declarations) {
5439
5524
  bind(declaration.name);
5440
5525
  }
5441
- } else if (ts18.isClassDeclaration(statement) && statement.name) {
5526
+ } else if (ts19.isClassDeclaration(statement) && statement.name) {
5442
5527
  found.classes.push(statement.name.text);
5443
- } else if (ts18.isFunctionDeclaration(statement) && statement.name && statement.body) {
5528
+ } else if (ts19.isFunctionDeclaration(statement) && statement.name && statement.body) {
5444
5529
  found.functions.push(statement.name.text);
5445
5530
  }
5446
5531
  }
5447
5532
  for (const statement of source.statements) {
5448
- if (ts18.isVariableStatement(statement)) {
5533
+ if (ts19.isVariableStatement(statement)) {
5449
5534
  for (const declaration of statement.declarationList.declarations) {
5450
- if (ts18.isIdentifier(declaration.name) && declaration.initializer && (ts18.isArrowFunction(declaration.initializer) || ts18.isFunctionExpression(declaration.initializer))) {
5535
+ if (ts19.isIdentifier(declaration.name) && declaration.initializer && (ts19.isArrowFunction(declaration.initializer) || ts19.isFunctionExpression(declaration.initializer))) {
5451
5536
  found.values = found.values.filter((name) => name !== declaration.name.getText());
5452
5537
  found.functions.push(declaration.name.text);
5453
5538
  }
@@ -5459,7 +5544,7 @@ var bindingNames = (source) => {
5459
5544
  var closureSites = (source, checker) => {
5460
5545
  const sites = [];
5461
5546
  const visit = (node, enclosing) => {
5462
- const closure = ts18.isArrowFunction(node) || ts18.isFunctionExpression(node);
5547
+ const closure = ts19.isArrowFunction(node) || ts19.isFunctionExpression(node);
5463
5548
  if (closure && !moduleFunction(node)) {
5464
5549
  sites.push({
5465
5550
  start: node.getStart(source),
@@ -5467,8 +5552,8 @@ var closureSites = (source, checker) => {
5467
5552
  captures: enclosing ? captures(node, enclosing, checker) : []
5468
5553
  });
5469
5554
  }
5470
- const scope = ts18.isFunctionLike(node) || ts18.isClassLike(node) ? node : enclosing;
5471
- ts18.forEachChild(node, (child) => visit(child, scope));
5555
+ const scope = ts19.isFunctionLike(node) || ts19.isClassLike(node) ? node : enclosing;
5556
+ ts19.forEachChild(node, (child) => visit(child, scope));
5472
5557
  };
5473
5558
  visit(source, undefined);
5474
5559
  return sites;
@@ -5476,18 +5561,18 @@ var closureSites = (source, checker) => {
5476
5561
  var captures = (closure, enclosing, checker) => {
5477
5562
  const names = new Set;
5478
5563
  const visit = (node) => {
5479
- if (node.kind === ts18.SyntaxKind.ThisKeyword && ts18.isArrowFunction(closure)) {
5564
+ if (node.kind === ts19.SyntaxKind.ThisKeyword && ts19.isArrowFunction(closure)) {
5480
5565
  names.add("this");
5481
5566
  }
5482
- if (ts18.isIdentifier(node) && !isPropertyName(node)) {
5483
- const symbol = ts18.isShorthandPropertyAssignment(node.parent) ? checker.getShorthandAssignmentValueSymbol(node.parent) : checker.getSymbolAtLocation(node);
5567
+ if (ts19.isIdentifier(node) && !isPropertyName(node)) {
5568
+ const symbol = ts19.isShorthandPropertyAssignment(node.parent) ? checker.getShorthandAssignmentValueSymbol(node.parent) : checker.getSymbolAtLocation(node);
5484
5569
  const declaration = symbol?.valueDeclaration;
5485
- if (declaration && !within(declaration, closure) && within(declaration, enclosing) && !ts18.isClassLike(declaration)) {
5570
+ if (declaration && !within(declaration, closure) && within(declaration, enclosing) && !ts19.isClassLike(declaration)) {
5486
5571
  names.add(node.text);
5487
5572
  }
5488
5573
  }
5489
- if (!ts18.isTypeNode(node)) {
5490
- ts18.forEachChild(node, visit);
5574
+ if (!ts19.isTypeNode(node)) {
5575
+ ts19.forEachChild(node, visit);
5491
5576
  }
5492
5577
  };
5493
5578
  visit(closure.body);
@@ -5496,10 +5581,10 @@ var captures = (closure, enclosing, checker) => {
5496
5581
  var moduleFunction = (node) => {
5497
5582
  const declaration = node.parent;
5498
5583
  const statement = declaration?.parent?.parent;
5499
- return ts18.isVariableDeclaration(declaration) && statement !== undefined && ts18.isVariableStatement(statement) && ts18.isSourceFile(statement.parent);
5584
+ return ts19.isVariableDeclaration(declaration) && statement !== undefined && ts19.isVariableStatement(statement) && ts19.isSourceFile(statement.parent);
5500
5585
  };
5501
5586
  var within = (node, container) => node.pos >= container.pos && node.end <= container.end;
5502
- var isPropertyName = (node) => ts18.isPropertyAccessExpression(node.parent) && node.parent.name === node || ts18.isPropertyAssignment(node.parent) && node.parent.name === node;
5587
+ var isPropertyName = (node) => ts19.isPropertyAccessExpression(node.parent) && node.parent.name === node || ts19.isPropertyAssignment(node.parent) && node.parent.name === node;
5503
5588
  var captureGraph = (entry, sources, checker) => {
5504
5589
  const files = sources.filter((source) => !source.isDeclarationFile);
5505
5590
  const request = {
@@ -5538,9 +5623,9 @@ ${z2.prettifyError(graph.error)}`);
5538
5623
  };
5539
5624
 
5540
5625
  // packages/compiler/src/frontend/elaborate/imports.ts
5541
- import { dirname as dirname4, relative as relative3 } from "node:path";
5626
+ import { dirname as dirname4, relative as relative4 } from "node:path";
5542
5627
  var importPath = (from, to) => {
5543
- const path = relative3(dirname4(from), to).replace(/\\/g, "/").replace(/\.tsx?$/, "");
5628
+ const path = relative4(dirname4(from), to).replace(/\\/g, "/").replace(/\.tsx?$/, "");
5544
5629
  return path.startsWith("./") || path.startsWith("../") ? path : `./${path}`;
5545
5630
  };
5546
5631
 
@@ -5578,7 +5663,9 @@ class EntryImports {
5578
5663
  }
5579
5664
 
5580
5665
  // packages/compiler/src/frontend/elaborate/model.ts
5581
- import ts19 from "typescript";
5666
+ import { relative as relative5 } from "node:path";
5667
+ import { identityDigest as identityDigest3 } from "@tsplc/compiler/ir";
5668
+ import ts20 from "typescript";
5582
5669
  var tsPath = (owner) => owner.root.name + owner.steps.map(stepPath).join("");
5583
5670
  var stepPath = (step) => {
5584
5671
  if (step.kind === "index") {
@@ -5614,11 +5701,16 @@ class Model {
5614
5701
  program;
5615
5702
  nodes;
5616
5703
  roots = [];
5617
- constructor(graph, checker, program, entry) {
5704
+ projectRoot;
5705
+ constructor(graph, checker, program, entry, projectRoot) {
5618
5706
  this.graph = graph;
5619
5707
  this.checker = checker;
5620
5708
  this.program = program;
5621
- this.nodes = graph.nodes.map((captured, id) => ({ id, captured }));
5709
+ this.nodes = graph.nodes.map((captured, id) => ({
5710
+ id,
5711
+ reference: id,
5712
+ captured
5713
+ }));
5622
5714
  const ordered = [
5623
5715
  ...graph.bindings.filter((binding) => binding.file !== entry),
5624
5716
  ...graph.bindings.filter((binding) => binding.file === entry)
@@ -5629,12 +5721,33 @@ class Model {
5629
5721
  file: binding.file,
5630
5722
  name: binding.name,
5631
5723
  declaration,
5632
- exported: Boolean(ts19.getCombinedModifierFlags(declaration) & ts19.ModifierFlags.Export),
5724
+ exported: Boolean(ts20.getCombinedModifierFlags(declaration) & ts20.ModifierFlags.Export),
5633
5725
  value: binding.value
5634
5726
  };
5635
5727
  this.roots.push(root);
5636
5728
  this.own(binding.value, { root, steps: [] }, checker.getTypeAtLocation(declaration.name));
5637
5729
  }
5730
+ this.projectRoot = projectRoot;
5731
+ this.assignReferences();
5732
+ }
5733
+ identity(node) {
5734
+ return node.owner && `${relative5(this.projectRoot, node.owner.root.file).replace(/\\/g, "/")}:${tsPath(node.owner)}`;
5735
+ }
5736
+ assignReferences() {
5737
+ const taken = new Map;
5738
+ for (const node of this.nodes) {
5739
+ const identity = this.identity(node);
5740
+ if (!identity || !node.owner) {
5741
+ continue;
5742
+ }
5743
+ const reference = Number.parseInt(identityDigest3(identity), 16) & 2147483647;
5744
+ const other = taken.get(reference);
5745
+ if (other?.owner) {
5746
+ throw new Error(`${tsPath(other.owner)} and ${tsPath(node.owner)} would hold the same reference id; rename one of them.`);
5747
+ }
5748
+ taken.set(reference, node);
5749
+ node.reference = reference;
5750
+ }
5638
5751
  }
5639
5752
  node(value) {
5640
5753
  if (value.kind !== "node") {
@@ -5649,11 +5762,11 @@ class Model {
5649
5762
  binding(file, name) {
5650
5763
  const source = this.program.getSourceFile(file);
5651
5764
  const named = (declaration) => {
5652
- if (ts19.isIdentifier(declaration.name)) {
5765
+ if (ts20.isIdentifier(declaration.name)) {
5653
5766
  return declaration.name.text === name ? declaration : undefined;
5654
5767
  }
5655
5768
  for (const element of declaration.name.elements) {
5656
- const found = ts19.isBindingElement(element) && named(element);
5769
+ const found = ts20.isBindingElement(element) && named(element);
5657
5770
  if (found) {
5658
5771
  return found;
5659
5772
  }
@@ -5661,7 +5774,7 @@ class Model {
5661
5774
  return;
5662
5775
  };
5663
5776
  for (const statement of source?.statements ?? []) {
5664
- if (ts19.isVariableStatement(statement)) {
5777
+ if (ts20.isVariableStatement(statement)) {
5665
5778
  for (const declaration of statement.declarationList.declarations) {
5666
5779
  const found = named(declaration);
5667
5780
  if (found) {
@@ -5692,7 +5805,7 @@ class Model {
5692
5805
  throw new Error("Not a class instance.");
5693
5806
  }
5694
5807
  const source = this.program.getSourceFile(captured.file);
5695
- const found = source?.statements.find((statement) => ts19.isClassDeclaration(statement) && statement.name?.text === captured.name);
5808
+ const found = source?.statements.find((statement) => ts20.isClassDeclaration(statement) && statement.name?.text === captured.name);
5696
5809
  if (!found) {
5697
5810
  throw new Error(`${captured.file}: no class ${captured.name}.`);
5698
5811
  }
@@ -5702,10 +5815,10 @@ class Model {
5702
5815
  return this.fields(declaration).find((field) => field.name.getText() === name);
5703
5816
  }
5704
5817
  ancestry(declaration) {
5705
- const base = declaration.heritageClauses?.find((clause) => clause.token === ts19.SyntaxKind.ExtendsKeyword)?.types[0]?.expression;
5818
+ const base = declaration.heritageClauses?.find((clause) => clause.token === ts20.SyntaxKind.ExtendsKeyword)?.types[0]?.expression;
5706
5819
  const symbol = base && this.checker.getSymbolAtLocation(base);
5707
- const resolved = symbol && symbol.flags & ts19.SymbolFlags.Alias ? this.checker.getAliasedSymbol(symbol) : symbol;
5708
- const parent = resolved?.declarations?.find(ts19.isClassDeclaration);
5820
+ const resolved = symbol && symbol.flags & ts20.SymbolFlags.Alias ? this.checker.getAliasedSymbol(symbol) : symbol;
5821
+ const parent = resolved?.declarations?.find(ts20.isClassDeclaration);
5709
5822
  return parent ? [declaration, ...this.ancestry(parent)] : [declaration];
5710
5823
  }
5711
5824
  members(declaration) {
@@ -5716,11 +5829,11 @@ class Model {
5716
5829
  }
5717
5830
  ownFields(declaration) {
5718
5831
  return declaration.members.flatMap((member) => {
5719
- if (ts19.isPropertyDeclaration(member)) {
5832
+ if (ts20.isPropertyDeclaration(member)) {
5720
5833
  return [member];
5721
5834
  }
5722
- if (ts19.isConstructorDeclaration(member)) {
5723
- return member.parameters.filter((parameter) => ts19.isParameterPropertyDeclaration(parameter, member));
5835
+ if (ts20.isConstructorDeclaration(member)) {
5836
+ return member.parameters.filter((parameter) => ts20.isParameterPropertyDeclaration(parameter, member));
5724
5837
  }
5725
5838
  return [];
5726
5839
  });
@@ -5742,7 +5855,7 @@ class Model {
5742
5855
  return property && this.checker.getTypeOfSymbol(property);
5743
5856
  }
5744
5857
  variant(type, value) {
5745
- const candidates = (type.isUnion() ? type.types : [type]).filter((member) => !(member.flags & ts19.TypeFlags.Undefined));
5858
+ const candidates = (type.isUnion() ? type.types : [type]).filter((member) => !(member.flags & ts20.TypeFlags.Undefined));
5746
5859
  const [first] = candidates;
5747
5860
  if (!first) {
5748
5861
  return type;
@@ -5761,7 +5874,7 @@ class Model {
5761
5874
  }
5762
5875
  elementType(type) {
5763
5876
  const target = this.checker.getNonNullableType(type);
5764
- return this.checker.getIndexTypeOfType(target, ts19.IndexKind.Number) ?? (this.checker.isTupleType(target) ? this.checker.getTypeArguments(target)[0] : undefined);
5877
+ return this.checker.getIndexTypeOfType(target, ts20.IndexKind.Number) ?? (this.checker.isTupleType(target) ? this.checker.getTypeArguments(target)[0] : undefined);
5765
5878
  }
5766
5879
  own(value, owner, type) {
5767
5880
  const queue = [{ owner, type, value }];
@@ -5785,7 +5898,7 @@ class Model {
5785
5898
  }
5786
5899
 
5787
5900
  // packages/compiler/src/frontend/elaborate/retention.ts
5788
- import ts20 from "typescript";
5901
+ import ts21 from "typescript";
5789
5902
 
5790
5903
  // packages/compiler/src/frontend/elaborate/values.ts
5791
5904
  var constant = (value) => ({
@@ -5810,14 +5923,14 @@ var primitive = (type) => {
5810
5923
  if (type.isIntersection()) {
5811
5924
  return type.types.some(primitive);
5812
5925
  }
5813
- return !(type.flags & (ts20.TypeFlags.Object | ts20.TypeFlags.NonPrimitive));
5926
+ return !(type.flags & (ts21.TypeFlags.Object | ts21.TypeFlags.NonPrimitive));
5814
5927
  };
5815
5928
  var retainedDeclaration = (call) => {
5816
5929
  const parent = call.parent;
5817
- if (ts20.isPropertyDeclaration(parent) && parent.initializer === call) {
5930
+ if (ts21.isPropertyDeclaration(parent) && parent.initializer === call) {
5818
5931
  return parent;
5819
5932
  }
5820
- if (ts20.isVariableDeclaration(parent) && parent.initializer === call && ts20.isVariableDeclarationList(parent.parent) && ts20.isVariableStatement(parent.parent.parent) && ts20.isSourceFile(parent.parent.parent.parent)) {
5933
+ if (ts21.isVariableDeclaration(parent) && parent.initializer === call && ts21.isVariableDeclarationList(parent.parent) && ts21.isVariableStatement(parent.parent.parent) && ts21.isSourceFile(parent.parent.parent.parent)) {
5821
5934
  return parent;
5822
5935
  }
5823
5936
  return;
@@ -5825,9 +5938,9 @@ var retainedDeclaration = (call) => {
5825
5938
  var retainedDeclarations = (sources, checker, sdk) => {
5826
5939
  const found = new Set;
5827
5940
  const visit = (node) => {
5828
- if (ts20.isCallExpression(node) && namesSdk(checker, sdk, node.expression, "retain")) {
5941
+ if (ts21.isCallExpression(node) && namesSdk(checker, sdk, node.expression, "retain")) {
5829
5942
  const symbol = checker.getSymbolAtLocation(node.expression);
5830
- if (!symbol || !(symbol.flags & ts20.SymbolFlags.Alias)) {
5943
+ if (!symbol || !(symbol.flags & ts21.SymbolFlags.Alias)) {
5831
5944
  throw new SpecializeError(node, 'Setup runs under Bun, where the global retain has no value: import { retain } from "@tsplc/compiler/retain".');
5832
5945
  }
5833
5946
  const [argument] = node.arguments;
@@ -5839,7 +5952,7 @@ var retainedDeclarations = (sources, checker, sdk) => {
5839
5952
  found.add(declaration);
5840
5953
  }
5841
5954
  }
5842
- ts20.forEachChild(node, visit);
5955
+ ts21.forEachChild(node, visit);
5843
5956
  };
5844
5957
  for (const source of sources) {
5845
5958
  visit(source);
@@ -5916,18 +6029,19 @@ class Retention {
5916
6029
  }
5917
6030
 
5918
6031
  // packages/compiler/src/frontend/elaborate/specialize.ts
5919
- import ts32 from "typescript";
6032
+ import { identityDigest as identityDigest5 } from "@tsplc/compiler/ir";
6033
+ import ts33 from "typescript";
5920
6034
 
5921
6035
  // packages/compiler/src/frontend/elaborate/dialect.ts
5922
6036
  import { canAssign as canAssign2, integerType, primitiveTypes as primitiveTypes3 } from "@tsplc/compiler/ir";
5923
- import ts23 from "typescript";
6037
+ import ts24 from "typescript";
5924
6038
 
5925
6039
  // packages/compiler/src/frontend/elaborate/references.ts
5926
- import ts22 from "typescript";
6040
+ import ts23 from "typescript";
5927
6041
 
5928
6042
  // packages/compiler/src/frontend/elaborate/layouts.ts
5929
6043
  import { primitiveTypes as primitiveTypes2 } from "@tsplc/compiler/ir";
5930
- import ts21 from "typescript";
6044
+ import ts22 from "typescript";
5931
6045
  var iecNames = new Set(primitiveTypes2.map((type) => type.id));
5932
6046
 
5933
6047
  class Layouts {
@@ -5947,7 +6061,7 @@ class Layouts {
5947
6061
  this.kept = kept;
5948
6062
  for (const source of keptSources) {
5949
6063
  for (const statement of source.statements) {
5950
- if ((ts21.isTypeAliasDeclaration(statement) || ts21.isInterfaceDeclaration(statement)) && isExported(statement)) {
6064
+ if ((ts22.isTypeAliasDeclaration(statement) || ts22.isInterfaceDeclaration(statement)) && isExported(statement)) {
5951
6065
  const symbol = checker.getSymbolAtLocation(statement.name);
5952
6066
  if (symbol) {
5953
6067
  this.keptTypes.set(checker.getDeclaredTypeOfSymbol(symbol), {
@@ -6021,7 +6135,7 @@ class Layouts {
6021
6135
  }
6022
6136
  const variants = type.types.filter((part) => !isAbsent(part));
6023
6137
  const [first, ...others] = variants;
6024
- if (!first || !others.length || variants.some((part) => !(part.flags & ts21.TypeFlags.Object))) {
6138
+ if (!first || !others.length || variants.some((part) => !(part.flags & ts22.TypeFlags.Object))) {
6025
6139
  return;
6026
6140
  }
6027
6141
  const literal = (variant, name) => {
@@ -6083,17 +6197,17 @@ class Layouts {
6083
6197
  if (alias && iecNames.has(alias)) {
6084
6198
  return alias;
6085
6199
  }
6086
- if (type.flags & ts21.TypeFlags.BooleanLike) {
6200
+ if (type.flags & ts22.TypeFlags.BooleanLike) {
6087
6201
  return "boolean";
6088
6202
  }
6089
6203
  const enumDeclaration = this.enumDeclaration(type);
6090
6204
  if (enumDeclaration) {
6091
6205
  return this.enumName(enumDeclaration);
6092
6206
  }
6093
- if (type.flags & ts21.TypeFlags.NumberLike) {
6207
+ if (type.flags & ts22.TypeFlags.NumberLike) {
6094
6208
  return "number";
6095
6209
  }
6096
- if (type.flags & ts21.TypeFlags.BigIntLike) {
6210
+ if (type.flags & ts22.TypeFlags.BigIntLike) {
6097
6211
  return "LINT";
6098
6212
  }
6099
6213
  const literal = this.literalEnum(type);
@@ -6104,7 +6218,7 @@ class Layouts {
6104
6218
  if (named) {
6105
6219
  return named;
6106
6220
  }
6107
- if (type.flags & ts21.TypeFlags.StringLike) {
6221
+ if (type.flags & ts22.TypeFlags.StringLike) {
6108
6222
  return "string";
6109
6223
  }
6110
6224
  const tagged = this.tagged(type);
@@ -6130,7 +6244,7 @@ class Layouts {
6130
6244
  if (enumKey) {
6131
6245
  return enumKey;
6132
6246
  }
6133
- if (type.flags & ts21.TypeFlags.Object) {
6247
+ if (type.flags & ts22.TypeFlags.Object) {
6134
6248
  return this.record(type, value, hint);
6135
6249
  }
6136
6250
  throw new Error(`${checker.typeToString(type)} has no PLC layout.`);
@@ -6138,22 +6252,22 @@ class Layouts {
6138
6252
  enumDeclaration(type) {
6139
6253
  const parts = type.isUnion() ? type.types : [type];
6140
6254
  const [first] = parts;
6141
- if (!first || !parts.every((part) => part.flags & ts21.TypeFlags.EnumLike)) {
6255
+ if (!first || !parts.every((part) => part.flags & ts22.TypeFlags.EnumLike)) {
6142
6256
  return;
6143
6257
  }
6144
6258
  const symbol = first.symbol;
6145
- const declaration = symbol?.declarations?.find(ts21.isEnumDeclaration) ?? symbol?.valueDeclaration?.parent;
6146
- return declaration && ts21.isEnumDeclaration(declaration) ? declaration : undefined;
6259
+ const declaration = symbol?.declarations?.find(ts22.isEnumDeclaration) ?? symbol?.valueDeclaration?.parent;
6260
+ return declaration && ts22.isEnumDeclaration(declaration) ? declaration : undefined;
6147
6261
  }
6148
6262
  iecName(declaration) {
6149
6263
  return iecTypeName(annotation(declaration));
6150
6264
  }
6151
6265
  elementIec(declaration) {
6152
6266
  const node = annotation(declaration);
6153
- if (node && ts21.isArrayTypeNode(node)) {
6267
+ if (node && ts22.isArrayTypeNode(node)) {
6154
6268
  return iecTypeName(node.elementType);
6155
6269
  }
6156
- if (node && ts21.isTypeReferenceNode(node)) {
6270
+ if (node && ts22.isTypeReferenceNode(node)) {
6157
6271
  return iecTypeName(node.typeArguments?.[0]);
6158
6272
  }
6159
6273
  return;
@@ -6204,7 +6318,7 @@ class Layouts {
6204
6318
  if (!symbol || !declaration) {
6205
6319
  return;
6206
6320
  }
6207
- if (!ts21.isTypeAliasDeclaration(declaration) && !ts21.isInterfaceDeclaration(declaration)) {
6321
+ if (!ts22.isTypeAliasDeclaration(declaration) && !ts22.isInterfaceDeclaration(declaration)) {
6208
6322
  return;
6209
6323
  }
6210
6324
  const file = declaration.getSourceFile().fileName;
@@ -6289,16 +6403,16 @@ var recordTypes = (type) => {
6289
6403
  };
6290
6404
  var annotation = (declaration) => declaration && declaration.type;
6291
6405
  var arrayElement = (node) => {
6292
- if (node && ts21.isArrayTypeNode(node)) {
6406
+ if (node && ts22.isArrayTypeNode(node)) {
6293
6407
  return node.elementType;
6294
6408
  }
6295
- if (node && ts21.isTypeReferenceNode(node) && ["Array", "ReadonlyArray"].includes(node.typeName.getText())) {
6409
+ if (node && ts22.isTypeReferenceNode(node) && ["Array", "ReadonlyArray"].includes(node.typeName.getText())) {
6296
6410
  return node.typeArguments?.[0];
6297
6411
  }
6298
6412
  return;
6299
6413
  };
6300
- var iecTypeName = (node) => node && ts21.isTypeReferenceNode(node) && iecNames.has(node.typeName.getText()) ? node.typeName.getText() : undefined;
6301
- var isExported = (declaration) => Boolean(ts21.getCombinedModifierFlags(declaration) & ts21.ModifierFlags.Export);
6414
+ var iecTypeName = (node) => node && ts22.isTypeReferenceNode(node) && iecNames.has(node.typeName.getText()) ? node.typeName.getText() : undefined;
6415
+ var isExported = (declaration) => Boolean(ts22.getCombinedModifierFlags(declaration) & ts22.ModifierFlags.Export);
6302
6416
  var isReadonlyArray = (type) => type.getSymbol()?.name === "ReadonlyArray";
6303
6417
  var pascalCase = (text) => text.replace(/(^|[^A-Za-z0-9]+)([A-Za-z0-9])/g, (_, __, letter) => letter.toUpperCase());
6304
6418
  var unusedName = (base, taken) => {
@@ -6316,9 +6430,9 @@ var enumMember = (value) => {
6316
6430
  const name = pascalCase(value);
6317
6431
  return /^[A-Za-z_]/.test(name) ? name : `_${name}`;
6318
6432
  };
6319
- var isAbsent = (type) => Boolean(type.flags & (ts21.TypeFlags.Undefined | ts21.TypeFlags.Null));
6433
+ var isAbsent = (type) => Boolean(type.flags & (ts22.TypeFlags.Undefined | ts22.TypeFlags.Null));
6320
6434
  var bothAbsent = (checker, type) => {
6321
- if (type.isUnion() && type.types.some((part) => part.flags & ts21.TypeFlags.Null) && type.types.some((part) => part.flags & ts21.TypeFlags.Undefined)) {
6435
+ if (type.isUnion() && type.types.some((part) => part.flags & ts22.TypeFlags.Null) && type.types.some((part) => part.flags & ts22.TypeFlags.Undefined)) {
6322
6436
  throw new Error(`${checker.typeToString(type)}: null and undefined are one empty value in the PLC; use one of them.`);
6323
6437
  }
6324
6438
  };
@@ -6330,15 +6444,15 @@ var referenceType = (type) => {
6330
6444
  return defined.length > 0 && defined.every(isInstanceType);
6331
6445
  };
6332
6446
  var parts = (type) => type.isUnion() ? type.types : [type];
6333
- var isInstanceType = (type) => Boolean(type.flags & ts22.TypeFlags.Object) && type.getConstructSignatures().length === 0 && classesOf(type).length > 0;
6334
- var classesOf = (type) => type.getSymbol()?.declarations?.filter(ts22.isClassDeclaration) ?? [];
6447
+ var isInstanceType = (type) => Boolean(type.flags & ts23.TypeFlags.Object) && type.getConstructSignatures().length === 0 && classesOf(type).length > 0;
6448
+ var classesOf = (type) => type.getSymbol()?.declarations?.filter(ts23.isClassDeclaration) ?? [];
6335
6449
  var referable = (node) => node.captured.kind === "instance" || node.captured.kind === "object" || node.captured.kind === "array";
6336
6450
  var referenceIndex = (value) => {
6337
6451
  if (value.kind === "choice") {
6338
6452
  return value.index;
6339
6453
  }
6340
6454
  if (value.kind === "static" && referable(value.node)) {
6341
- return String(value.node.id);
6455
+ return String(value.node.reference);
6342
6456
  }
6343
6457
  if (value.kind === "const" && value.value === undefined) {
6344
6458
  return "-1";
@@ -6352,9 +6466,9 @@ var optionsOf = (value) => {
6352
6466
  return value.kind === "static" ? [value.node] : [];
6353
6467
  };
6354
6468
  var absentOf = (value) => value.kind === "choice" ? value.optional : value.kind === "const";
6355
- var union = (nodes) => [...new Set(nodes)].sort((left, right) => left.id - right.id);
6469
+ var union = (nodes) => [...new Set(nodes)].sort((left, right) => left.reference - right.reference);
6356
6470
  var maybeAbsent = (type) => parts(type).some(isAbsent);
6357
- var unparenthesized2 = (node) => ts22.isParenthesizedExpression(node) || ts22.isNonNullExpression(node) ? unparenthesized2(node.expression) : node;
6471
+ var unparenthesized2 = (node) => ts23.isParenthesizedExpression(node) || ts23.isNonNullExpression(node) ? unparenthesized2(node.expression) : node;
6358
6472
  var chain = (frame, arms) => {
6359
6473
  arms.forEach((arm, index) => {
6360
6474
  if (index === 0) {
@@ -6447,7 +6561,7 @@ class References {
6447
6561
  case "choice":
6448
6562
  return mapped`(${choice.index} === ${other.index})`;
6449
6563
  case "static":
6450
- return choice.options.includes(other.node) ? mapped`(${choice.index} === ${other.node.id})` : false;
6564
+ return choice.options.includes(other.node) ? mapped`(${choice.index} === ${other.node.reference})` : false;
6451
6565
  case "const":
6452
6566
  return other.value === undefined && choice.optional ? mapped`(${choice.index} < 0)` : false;
6453
6567
  case "code":
@@ -6465,7 +6579,7 @@ class References {
6465
6579
  if (value.kind === "virtual") {
6466
6580
  return true;
6467
6581
  }
6468
- return value.kind === "code" && value.declared !== undefined && Boolean(this.checker.getNonNullableType(value.declared).flags & ts22.TypeFlags.Object);
6582
+ return value.kind === "code" && value.declared !== undefined && Boolean(this.checker.getNonNullableType(value.declared).flags & ts23.TypeFlags.Object);
6469
6583
  }
6470
6584
  held(choice, frame) {
6471
6585
  if (!choice.place) {
@@ -6515,11 +6629,11 @@ class References {
6515
6629
  }
6516
6630
  frame.emitter.line(target.setter ? mapped`${target.setter}(${index});` : mapped`${target.index} = ${index};`);
6517
6631
  };
6518
- if (operator === ts22.SyntaxKind.EqualsToken) {
6632
+ if (operator === ts23.SyntaxKind.EqualsToken) {
6519
6633
  store();
6520
6634
  return target;
6521
6635
  }
6522
- if (operator === ts22.SyntaxKind.QuestionQuestionEqualsToken) {
6636
+ if (operator === ts23.SyntaxKind.QuestionQuestionEqualsToken) {
6523
6637
  frame.emitter.open(mapped`if (${target.index} < 0) {`);
6524
6638
  store();
6525
6639
  frame.emitter.close();
@@ -6529,7 +6643,7 @@ class References {
6529
6643
  }
6530
6644
  target(node, frame) {
6531
6645
  const place = unparenthesized2(node);
6532
- if (!ts22.isPropertyAccessExpression(place) || place.expression.kind === ts22.SyntaxKind.ThisKeyword || place.expression.kind === ts22.SyntaxKind.SuperKeyword || !referenceType(this.checker.getTypeAtLocation(place.expression))) {
6646
+ if (!ts23.isPropertyAccessExpression(place) || place.expression.kind === ts23.SyntaxKind.ThisKeyword || place.expression.kind === ts23.SyntaxKind.SuperKeyword || !referenceType(this.checker.getTypeAtLocation(place.expression))) {
6533
6647
  return this.expressions.expression(node, frame);
6534
6648
  }
6535
6649
  const object = this.expressions.expression(place.expression, frame);
@@ -6548,7 +6662,7 @@ class References {
6548
6662
  lines: frame.emitter.detached({ nested: true }, () => write(option)).lines
6549
6663
  }));
6550
6664
  chain(frame, arms.filter((arm) => arm.lines.length > 0).map((arm) => ({
6551
- test: mapped`${choice.index} === ${arm.option.id}`,
6665
+ test: mapped`${choice.index} === ${arm.option.reference}`,
6552
6666
  body: () => frame.emitter.append(arm.lines)
6553
6667
  })));
6554
6668
  }
@@ -6561,7 +6675,7 @@ class References {
6561
6675
  }
6562
6676
  memberType(option, name) {
6563
6677
  if (option.captured.kind === "instance") {
6564
- const accessor = this.model.members(this.model.classOf(option)).find((member) => ts22.isGetAccessorDeclaration(member) && member.name.getText() === name);
6678
+ const accessor = this.model.members(this.model.classOf(option)).find((member) => ts23.isGetAccessorDeclaration(member) && member.name.getText() === name);
6565
6679
  const signature = accessor && this.checker.getSignatureFromDeclaration(accessor);
6566
6680
  if (signature) {
6567
6681
  return this.checker.getReturnTypeOfSignature(signature);
@@ -6578,7 +6692,7 @@ class References {
6578
6692
  if (!first) {
6579
6693
  return constant(undefined);
6580
6694
  }
6581
- const test = (option) => mapped`${choice.index} === ${option.id}`;
6695
+ const test = (option) => mapped`${choice.index} === ${option.reference}`;
6582
6696
  const known = first.value;
6583
6697
  if (known.kind === "const" && arms.every((arm) => arm.value.kind === "const" && arm.value.value === known.value)) {
6584
6698
  chain(frame, arms.filter((arm) => arm.lines.length > 0).map((arm) => ({
@@ -6605,7 +6719,7 @@ class References {
6605
6719
  });
6606
6720
  }
6607
6721
  const sample = arms.map((arm) => arm.value).find((value) => value.kind === "code");
6608
- const declared = type ?? (sample?.kind === "code" ? sample.declared : undefined) ?? (ts22.isExpression(at) ? this.checker.getTypeAtLocation(at) : undefined);
6722
+ const declared = type ?? (sample?.kind === "code" ? sample.declared : undefined) ?? (ts23.isExpression(at) ? this.checker.getTypeAtLocation(at) : undefined);
6609
6723
  if (!declared || arms.some((arm) => arm.value.kind !== "const" && arm.value.kind !== "code")) {
6610
6724
  throw new SpecializeError(at, "This can't be read through a reference chosen at run time: read a value, or call the method where it is named.");
6611
6725
  }
@@ -6701,7 +6815,7 @@ class References {
6701
6815
  }
6702
6816
  method(choice, name, node, frame, expected) {
6703
6817
  const [sample] = choice.options;
6704
- const declaration = sample?.captured.kind === "instance" ? this.model.members(this.model.classOf(sample)).find((member) => ts22.isMethodDeclaration(member) && member.name.getText() === name) : undefined;
6818
+ const declaration = sample?.captured.kind === "instance" ? this.model.members(this.model.classOf(sample)).find((member) => ts23.isMethodDeclaration(member) && member.name.getText() === name) : undefined;
6705
6819
  const args = this.expressions.inOrder(node.arguments, (argument, index) => {
6706
6820
  const parameter = declaration?.parameters[index];
6707
6821
  return this.expressions.expression(argument, frame, parameter && this.checker.getTypeAtLocation(parameter));
@@ -6709,7 +6823,7 @@ class References {
6709
6823
  return this.dispatch(choice, frame, node, undefined, (option) => {
6710
6824
  const method = this.expressions.member({ kind: "static", node: option }, name, node.expression, frame);
6711
6825
  const result = this.expressions.invoke(method, args, node, frame, expected);
6712
- if (result.kind === "code" && (!result.declared || result.declared.flags & ts22.TypeFlags.Void)) {
6826
+ if (result.kind === "code" && (!result.declared || result.declared.flags & ts23.TypeFlags.Void)) {
6713
6827
  frame.emitter.line(mapped`${result.text};`);
6714
6828
  return constant(undefined);
6715
6829
  }
@@ -6834,7 +6948,7 @@ class DialectText {
6834
6948
  }), ", ")} }`;
6835
6949
  }
6836
6950
  returnText(value, declared, iec) {
6837
- const target = iec ?? (declared && declared.flags & ts23.TypeFlags.Number ? "DINT" : undefined);
6951
+ const target = iec ?? (declared && declared.flags & ts24.TypeFlags.Number ? "DINT" : undefined);
6838
6952
  const from = value.kind === "code" ? value.iec : undefined;
6839
6953
  if (target && from && from !== target && integerTypes.has(from) && integerTypes.has(target) && !needsConversion(from, target)) {
6840
6954
  this.imports.addSdk("@tsplc/compiler/types", "exact");
@@ -6847,7 +6961,7 @@ class DialectText {
6847
6961
  if (index !== undefined) {
6848
6962
  return index;
6849
6963
  }
6850
- const target = iec ?? (declared && declared.flags & ts23.TypeFlags.Number ? "DINT" : undefined);
6964
+ const target = iec ?? (declared && declared.flags & ts24.TypeFlags.Number ? "DINT" : undefined);
6851
6965
  if (target && value.kind === "code" && needsConversion(value.iec ?? "DINT", target)) {
6852
6966
  this.imports.addSdk("@tsplc/compiler/types", "wrap");
6853
6967
  return mapped`wrap<${target}>(${this.code(value, undefined)})`;
@@ -6883,9 +6997,9 @@ class DialectText {
6883
6997
  }
6884
6998
  if (value.kind === "code" && value.declared) {
6885
6999
  const declared = value.declared;
6886
- if (this.layouts.isOptionalRecord(declared) && !ts23.isPrefixUnaryExpression(at)) {
7000
+ if (this.layouts.isOptionalRecord(declared) && !ts24.isPrefixUnaryExpression(at)) {
6887
7001
  const type = this.checker.getTypeAtLocation(at);
6888
- if (!(type.flags & ts23.TypeFlags.BooleanLike)) {
7002
+ if (!(type.flags & ts24.TypeFlags.BooleanLike)) {
6889
7003
  return mapped`${value.text}.has`;
6890
7004
  }
6891
7005
  }
@@ -6942,13 +7056,14 @@ var needsConversion = (from, to) => {
6942
7056
  };
6943
7057
 
6944
7058
  // packages/compiler/src/frontend/elaborate/expressions.ts
6945
- import ts28 from "typescript";
7059
+ import { identityDigest as identityDigest4 } from "@tsplc/compiler/ir";
7060
+ import ts29 from "typescript";
6946
7061
 
6947
7062
  // packages/compiler/src/frontend/elaborate/assignments.ts
6948
- import ts25 from "typescript";
7063
+ import ts26 from "typescript";
6949
7064
 
6950
7065
  // packages/compiler/src/frontend/elaborate/writes.ts
6951
- import ts24 from "typescript";
7066
+ import ts25 from "typescript";
6952
7067
 
6953
7068
  class ScanWrites {
6954
7069
  checker;
@@ -6969,45 +7084,45 @@ class ScanWrites {
6969
7084
  });
6970
7085
  }
6971
7086
  collectAssignments(node, inConstructor) {
6972
- const constructing = ts24.isConstructorDeclaration(node) || inConstructor && !ts24.isArrowFunction(node) && !ts24.isFunctionExpression(node);
7087
+ const constructing = ts25.isConstructorDeclaration(node) || inConstructor && !ts25.isArrowFunction(node) && !ts25.isFunctionExpression(node);
6973
7088
  if (!constructing) {
6974
7089
  const write = (target) => {
6975
7090
  const place = unwrapped(target);
6976
- if (ts24.isArrayLiteralExpression(place)) {
7091
+ if (ts25.isArrayLiteralExpression(place)) {
6977
7092
  for (const element of place.elements) {
6978
- write(ts24.isSpreadElement(element) ? element.expression : element);
7093
+ write(ts25.isSpreadElement(element) ? element.expression : element);
6979
7094
  }
6980
7095
  return;
6981
7096
  }
6982
- if (ts24.isObjectLiteralExpression(place)) {
7097
+ if (ts25.isObjectLiteralExpression(place)) {
6983
7098
  for (const property of place.properties) {
6984
- if (ts24.isPropertyAssignment(property)) {
7099
+ if (ts25.isPropertyAssignment(property)) {
6985
7100
  write(property.initializer);
6986
7101
  }
6987
7102
  }
6988
7103
  return;
6989
7104
  }
6990
- if (ts24.isBinaryExpression(place) && place.operatorToken.kind === ts24.SyntaxKind.EqualsToken) {
7105
+ if (ts25.isBinaryExpression(place) && place.operatorToken.kind === ts25.SyntaxKind.EqualsToken) {
6991
7106
  write(place.left);
6992
7107
  return;
6993
7108
  }
6994
- if (ts24.isPropertyAccessExpression(place)) {
7109
+ if (ts25.isPropertyAccessExpression(place)) {
6995
7110
  this.markAssigned(place.name);
6996
- } else if (ts24.isElementAccessExpression(place)) {
7111
+ } else if (ts25.isElementAccessExpression(place)) {
6997
7112
  const base = indexed(place.expression);
6998
- if (ts24.isPropertyAccessExpression(base)) {
7113
+ if (ts25.isPropertyAccessExpression(base)) {
6999
7114
  this.markAssigned(base.name);
7000
7115
  }
7001
7116
  }
7002
7117
  };
7003
- if (ts24.isBinaryExpression(node) && isAssignment(node.operatorToken.kind)) {
7118
+ if (ts25.isBinaryExpression(node) && isAssignment(node.operatorToken.kind)) {
7004
7119
  write(node.left);
7005
7120
  }
7006
7121
  if (isUpdate(node)) {
7007
7122
  write(node.operand);
7008
7123
  }
7009
7124
  }
7010
- ts24.forEachChild(node, (child) => this.collectAssignments(child, constructing));
7125
+ ts25.forEachChild(node, (child) => this.collectAssignments(child, constructing));
7011
7126
  }
7012
7127
  markAssigned(name) {
7013
7128
  const symbol = this.checker.getSymbolAtLocation(name);
@@ -7024,14 +7139,14 @@ class ScanWrites {
7024
7139
  }
7025
7140
  }
7026
7141
  var ownSymbol = (declaration) => declaration.symbol;
7027
- var unwrapped = (target) => ts24.isParenthesizedExpression(target) || ts24.isNonNullExpression(target) ? unwrapped(target.expression) : target;
7028
- var indexed = (node) => ts24.isElementAccessExpression(node) ? indexed(node.expression) : node;
7029
- var isUpdate = (node) => (ts24.isPrefixUnaryExpression(node) || ts24.isPostfixUnaryExpression(node)) && (node.operator === ts24.SyntaxKind.PlusPlusToken || node.operator === ts24.SyntaxKind.MinusMinusToken);
7030
- var isAssignment = (kind) => kind >= ts24.SyntaxKind.FirstAssignment && kind <= ts24.SyntaxKind.LastAssignment;
7142
+ var unwrapped = (target) => ts25.isParenthesizedExpression(target) || ts25.isNonNullExpression(target) ? unwrapped(target.expression) : target;
7143
+ var indexed = (node) => ts25.isElementAccessExpression(node) ? indexed(node.expression) : node;
7144
+ var isUpdate = (node) => (ts25.isPrefixUnaryExpression(node) || ts25.isPostfixUnaryExpression(node)) && (node.operator === ts25.SyntaxKind.PlusPlusToken || node.operator === ts25.SyntaxKind.MinusMinusToken);
7145
+ var isAssignment = (kind) => kind >= ts25.SyntaxKind.FirstAssignment && kind <= ts25.SyntaxKind.LastAssignment;
7031
7146
  var assignsName = (body, binding, checker) => {
7032
7147
  const declared = new Set;
7033
7148
  const collect = (name) => {
7034
- if (ts24.isIdentifier(name)) {
7149
+ if (ts25.isIdentifier(name)) {
7035
7150
  const symbol = checker.getSymbolAtLocation(name);
7036
7151
  if (symbol) {
7037
7152
  declared.add(symbol);
@@ -7039,7 +7154,7 @@ var assignsName = (body, binding, checker) => {
7039
7154
  return;
7040
7155
  }
7041
7156
  for (const element of name.elements) {
7042
- if (!ts24.isOmittedExpression(element)) {
7157
+ if (!ts25.isOmittedExpression(element)) {
7043
7158
  collect(element.name);
7044
7159
  }
7045
7160
  }
@@ -7049,39 +7164,39 @@ var assignsName = (body, binding, checker) => {
7049
7164
  };
7050
7165
  var assignsSymbol = (body, declared, checker) => {
7051
7166
  const target = (node) => {
7052
- const symbol = ts24.isIdentifier(node) ? checker.getSymbolAtLocation(node) : undefined;
7167
+ const symbol = ts25.isIdentifier(node) ? checker.getSymbolAtLocation(node) : undefined;
7053
7168
  return symbol !== undefined && declared.has(symbol);
7054
7169
  };
7055
- const visit = (node) => ts24.isBinaryExpression(node) && isAssignment(node.operatorToken.kind) && target(node.left) || isUpdate(node) && target(node.operand) || (ts24.forEachChild(node, visit) ?? false);
7170
+ const visit = (node) => ts25.isBinaryExpression(node) && isAssignment(node.operatorToken.kind) && target(node.left) || isUpdate(node) && target(node.operand) || (ts25.forEachChild(node, visit) ?? false);
7056
7171
  return visit(body);
7057
7172
  };
7058
7173
  var writesThrough = (body, symbol, checker) => {
7059
- const root = (node) => ts24.isPropertyAccessExpression(node) || ts24.isElementAccessExpression(node) || ts24.isParenthesizedExpression(node) || ts24.isNonNullExpression(node) ? root(node.expression) : node;
7060
- const named = (node) => ts24.isIdentifier(node) && checker.getSymbolAtLocation(node) === symbol;
7174
+ const root = (node) => ts25.isPropertyAccessExpression(node) || ts25.isElementAccessExpression(node) || ts25.isParenthesizedExpression(node) || ts25.isNonNullExpression(node) ? root(node.expression) : node;
7175
+ const named = (node) => ts25.isIdentifier(node) && checker.getSymbolAtLocation(node) === symbol;
7061
7176
  const throughIt = (target) => target !== root(target) && named(root(target));
7062
- const visit = (node) => ts24.isBinaryExpression(node) && isAssignment(node.operatorToken.kind) && throughIt(node.left) || isUpdate(node) && throughIt(node.operand) || ts24.isCallExpression(node) && node.arguments.some(named) || (ts24.forEachChild(node, visit) ?? false);
7177
+ const visit = (node) => ts25.isBinaryExpression(node) && isAssignment(node.operatorToken.kind) && throughIt(node.left) || isUpdate(node) && throughIt(node.operand) || ts25.isCallExpression(node) && node.arguments.some(named) || (ts25.forEachChild(node, visit) ?? false);
7063
7178
  return visit(body);
7064
7179
  };
7065
7180
  var aliasWindow = (name, checker) => {
7066
7181
  const symbol = checker.getSymbolAtLocation(name);
7067
7182
  const scope = enclosingScope(name);
7068
- const binding = ts24.isBindingElement(name.parent) ? name.parent : undefined;
7069
- const declaration = binding ? ts24.findAncestor(binding, ts24.isVariableDeclaration) : name.parent;
7070
- if (!symbol || !scope || !declaration || !ts24.isVariableDeclaration(declaration) || !declaration.initializer || binding && !ts24.isVariableDeclaration(binding.parent.parent)) {
7183
+ const binding = ts25.isBindingElement(name.parent) ? name.parent : undefined;
7184
+ const declaration = binding ? ts25.findAncestor(binding, ts25.isVariableDeclaration) : name.parent;
7185
+ if (!symbol || !scope || !declaration || !ts25.isVariableDeclaration(declaration) || !declaration.initializer || binding && !ts25.isVariableDeclaration(binding.parent.parent)) {
7071
7186
  return;
7072
7187
  }
7073
7188
  const uses = [];
7074
7189
  const collect = (node) => {
7075
- if (ts24.isIdentifier(node) && node !== name && checker.getSymbolAtLocation(node) === symbol) {
7190
+ if (ts25.isIdentifier(node) && node !== name && checker.getSymbolAtLocation(node) === symbol) {
7076
7191
  uses.push(node);
7077
7192
  }
7078
- ts24.forEachChild(node, collect);
7193
+ ts25.forEachChild(node, collect);
7079
7194
  };
7080
7195
  collect(scope);
7081
7196
  const contains = (outer, inner) => outer.pos <= inner.pos && inner.end <= outer.end;
7082
7197
  const reentered = (use) => {
7083
7198
  for (let node = use.parent;node && node !== scope; node = node.parent) {
7084
- if ((ts24.isIterationStatement(node, false) || ts24.isFunctionLike(node)) && !contains(node, declaration)) {
7199
+ if ((ts25.isIterationStatement(node, false) || ts25.isFunctionLike(node)) && !contains(node, declaration)) {
7085
7200
  return true;
7086
7201
  }
7087
7202
  }
@@ -7097,22 +7212,22 @@ var aliasWindow = (name, checker) => {
7097
7212
  };
7098
7213
  };
7099
7214
  var runsBetween = ({ scope, from, until }, matches) => {
7100
- const visit = (node) => node.getStart() >= from && node.end <= until && matches(node) || (ts24.forEachChild(node, visit) ?? false);
7215
+ const visit = (node) => node.getStart() >= from && node.end <= until && matches(node) || (ts25.forEachChild(node, visit) ?? false);
7101
7216
  return visit(scope);
7102
7217
  };
7103
7218
  var pathNames = (place) => {
7104
7219
  const node = unwrapped(place);
7105
- if (ts24.isIdentifier(node)) {
7220
+ if (ts25.isIdentifier(node)) {
7106
7221
  return [node.text];
7107
7222
  }
7108
- if (node.kind === ts24.SyntaxKind.ThisKeyword) {
7223
+ if (node.kind === ts25.SyntaxKind.ThisKeyword) {
7109
7224
  return [];
7110
7225
  }
7111
- if (ts24.isPropertyAccessExpression(node)) {
7226
+ if (ts25.isPropertyAccessExpression(node)) {
7112
7227
  const base = pathNames(node.expression);
7113
7228
  return base && [...base, node.name.text];
7114
7229
  }
7115
- if (ts24.isElementAccessExpression(node)) {
7230
+ if (ts25.isElementAccessExpression(node)) {
7116
7231
  return pathNames(node.expression);
7117
7232
  }
7118
7233
  return;
@@ -7122,7 +7237,7 @@ var writesIn = (window) => {
7122
7237
  runsBetween(window, (node) => {
7123
7238
  if (isUpdate(node)) {
7124
7239
  targets.push(node.operand);
7125
- } else if (ts24.isBinaryExpression(node) && isAssignment(node.operatorToken.kind)) {
7240
+ } else if (ts25.isBinaryExpression(node) && isAssignment(node.operatorToken.kind)) {
7126
7241
  targets.push(node.left);
7127
7242
  }
7128
7243
  return false;
@@ -7136,17 +7251,17 @@ var stableAlias = (name, checker) => {
7136
7251
  }
7137
7252
  const read = new Set;
7138
7253
  const readNames = (node) => {
7139
- if (ts24.isIdentifier(node) || ts24.isPrivateIdentifier(node)) {
7254
+ if (ts25.isIdentifier(node) || ts25.isPrivateIdentifier(node)) {
7140
7255
  read.add(node.text);
7141
7256
  }
7142
- ts24.forEachChild(node, readNames);
7257
+ ts25.forEachChild(node, readNames);
7143
7258
  };
7144
7259
  readNames(window.source);
7145
7260
  const writesRead = (target) => {
7146
7261
  const names = pathNames(target);
7147
7262
  return names === undefined || names.some((written) => read.has(written));
7148
7263
  };
7149
- return !writesIn(window).some(writesRead) && !runsBetween(window, (node) => ts24.isCallExpression(node) || ts24.isNewExpression(node) || ts24.isAwaitExpression(node) || ts24.isYieldExpression(node) || ts24.isTaggedTemplateExpression(node) || ts24.isDeleteExpression(node));
7264
+ return !writesIn(window).some(writesRead) && !runsBetween(window, (node) => ts25.isCallExpression(node) || ts25.isNewExpression(node) || ts25.isAwaitExpression(node) || ts25.isYieldExpression(node) || ts25.isTaggedTemplateExpression(node) || ts25.isDeleteExpression(node));
7150
7265
  };
7151
7266
  var replacedWhileAliased = (name, checker) => {
7152
7267
  const window = aliasWindow(name, checker);
@@ -7163,7 +7278,7 @@ var replacedWhileAliased = (name, checker) => {
7163
7278
  };
7164
7279
  var enclosingScope = (node) => {
7165
7280
  for (let parent = node.parent;parent; parent = parent.parent) {
7166
- if (ts24.isBlock(parent) || ts24.isSourceFile(parent) || ts24.isCaseClause(parent) || ts24.isDefaultClause(parent) || ts24.isFunctionLike(parent)) {
7281
+ if (ts25.isBlock(parent) || ts25.isSourceFile(parent) || ts25.isCaseClause(parent) || ts25.isDefaultClause(parent) || ts25.isFunctionLike(parent)) {
7167
7282
  return parent;
7168
7283
  }
7169
7284
  }
@@ -7172,13 +7287,13 @@ var enclosingScope = (node) => {
7172
7287
 
7173
7288
  // packages/compiler/src/frontend/elaborate/assignments.ts
7174
7289
  var compoundOperators = new Map([
7175
- [ts25.SyntaxKind.PlusEqualsToken, "+"],
7176
- [ts25.SyntaxKind.MinusEqualsToken, "-"],
7177
- [ts25.SyntaxKind.AsteriskEqualsToken, "*"],
7178
- [ts25.SyntaxKind.BarEqualsToken, "|"],
7179
- [ts25.SyntaxKind.AmpersandEqualsToken, "&"]
7290
+ [ts26.SyntaxKind.PlusEqualsToken, "+"],
7291
+ [ts26.SyntaxKind.MinusEqualsToken, "-"],
7292
+ [ts26.SyntaxKind.AsteriskEqualsToken, "*"],
7293
+ [ts26.SyntaxKind.BarEqualsToken, "|"],
7294
+ [ts26.SyntaxKind.AmpersandEqualsToken, "&"]
7180
7295
  ]);
7181
- var containsWrite = (node) => ts25.isBinaryExpression(node) && isAssignment(node.operatorToken.kind) || isUpdate(node) || !ts25.isFunctionLike(node) && (ts25.forEachChild(node, containsWrite) ?? false);
7296
+ var containsWrite = (node) => ts26.isBinaryExpression(node) && isAssignment(node.operatorToken.kind) || isUpdate(node) || !ts26.isFunctionLike(node) && (ts26.forEachChild(node, containsWrite) ?? false);
7182
7297
 
7183
7298
  class AssignmentSpecializer {
7184
7299
  expressions;
@@ -7190,7 +7305,7 @@ class AssignmentSpecializer {
7190
7305
  this.dialect = context.dialect;
7191
7306
  }
7192
7307
  assign(node, frame) {
7193
- if (ts25.isArrayLiteralExpression(node.left) || ts25.isObjectLiteralExpression(node.left)) {
7308
+ if (ts26.isArrayLiteralExpression(node.left) || ts26.isObjectLiteralExpression(node.left)) {
7194
7309
  const value = this.expressions.expression(node.right, frame);
7195
7310
  this.destructure(node.left, value, frame);
7196
7311
  return value;
@@ -7211,7 +7326,7 @@ class AssignmentSpecializer {
7211
7326
  const text = this.placeText(target, node.left);
7212
7327
  const declared = target.kind === "code" ? target.declared : undefined;
7213
7328
  const operator = node.operatorToken.kind;
7214
- if (operator === ts25.SyntaxKind.QuestionQuestionEqualsToken) {
7329
+ if (operator === ts26.SyntaxKind.QuestionQuestionEqualsToken) {
7215
7330
  const value = this.expressions.expression(node.right, frame, declared && this.checker.getNonNullableType(declared));
7216
7331
  frame.emitter.open(mapped`if (${this.dialect.isUndefinedText(text, declared)}) {`);
7217
7332
  frame.emitter.line(this.store(target, this.dialect.wrapDefined(this.dialect.code(value, declared && this.checker.getNonNullableType(declared)), declared)));
@@ -7219,7 +7334,7 @@ class AssignmentSpecializer {
7219
7334
  return target;
7220
7335
  }
7221
7336
  const value = this.expressions.expression(node.right, frame, declared);
7222
- if (operator === ts25.SyntaxKind.EqualsToken) {
7337
+ if (operator === ts26.SyntaxKind.EqualsToken) {
7223
7338
  frame.emitter.line(this.store(target, this.dialect.assignmentText(value, declared, target.kind === "code" ? target.iec : undefined)));
7224
7339
  return target;
7225
7340
  }
@@ -7242,8 +7357,8 @@ class AssignmentSpecializer {
7242
7357
  }
7243
7358
  stepOn(target, node, frame, { used }) {
7244
7359
  const text = this.placeText(target, node.operand);
7245
- const before = used && ts25.isPostfixUnaryExpression(node) ? this.expressions.held(target, frame) : target;
7246
- frame.emitter.line(this.store(target, mapped`${text} ${node.operator === ts25.SyntaxKind.PlusPlusToken ? "+" : "-"} 1`));
7360
+ const before = used && ts26.isPostfixUnaryExpression(node) ? this.expressions.held(target, frame) : target;
7361
+ frame.emitter.line(this.store(target, mapped`${text} ${node.operator === ts26.SyntaxKind.PlusPlusToken ? "+" : "-"} 1`));
7247
7362
  return before;
7248
7363
  }
7249
7364
  destructure(pattern, value, frame) {
@@ -7254,27 +7369,27 @@ class AssignmentSpecializer {
7254
7369
  }
7255
7370
  }
7256
7371
  collect(pattern, value, frame, writes) {
7257
- if (ts25.isArrayLiteralExpression(pattern)) {
7372
+ if (ts26.isArrayLiteralExpression(pattern)) {
7258
7373
  pattern.elements.forEach((element, index) => {
7259
- if (ts25.isOmittedExpression(element)) {
7374
+ if (ts26.isOmittedExpression(element)) {
7260
7375
  return;
7261
7376
  }
7262
- if (ts25.isSpreadElement(element)) {
7377
+ if (ts26.isSpreadElement(element)) {
7263
7378
  throw new SpecializeError(element, "Assign the rest of an array element by element.");
7264
7379
  }
7265
7380
  this.collectTarget(element, this.expressions.element(value, constant(index), element, frame), frame, writes);
7266
7381
  });
7267
7382
  return;
7268
7383
  }
7269
- if (ts25.isObjectLiteralExpression(pattern)) {
7384
+ if (ts26.isObjectLiteralExpression(pattern)) {
7270
7385
  for (const property of pattern.properties) {
7271
- if (ts25.isShorthandPropertyAssignment(property)) {
7386
+ if (ts26.isShorthandPropertyAssignment(property)) {
7272
7387
  const part = this.expressions.member(value, property.name.text, property, frame);
7273
7388
  const target = property.objectAssignmentInitializer ? this.withDefault(part, property.objectAssignmentInitializer, frame) : part;
7274
7389
  this.collectTarget(property.name, target, frame, writes);
7275
7390
  continue;
7276
7391
  }
7277
- if (!ts25.isPropertyAssignment(property)) {
7392
+ if (!ts26.isPropertyAssignment(property)) {
7278
7393
  throw new SpecializeError(property, "Assign each field of a pattern by name.");
7279
7394
  }
7280
7395
  this.collectTarget(property.initializer, this.expressions.member(value, property.name.getText(), property, frame), frame, writes);
@@ -7284,11 +7399,11 @@ class AssignmentSpecializer {
7284
7399
  throw new SpecializeError(pattern, "Not a pattern.");
7285
7400
  }
7286
7401
  collectTarget(target, part, frame, writes) {
7287
- if (ts25.isBinaryExpression(target) && target.operatorToken.kind === ts25.SyntaxKind.EqualsToken) {
7402
+ if (ts26.isBinaryExpression(target) && target.operatorToken.kind === ts26.SyntaxKind.EqualsToken) {
7288
7403
  this.collectTarget(target.left, this.withDefault(part, target.right, frame), frame, writes);
7289
7404
  return;
7290
7405
  }
7291
- if (ts25.isArrayLiteralExpression(target) || ts25.isObjectLiteralExpression(target)) {
7406
+ if (ts26.isArrayLiteralExpression(target) || ts26.isObjectLiteralExpression(target)) {
7292
7407
  this.collect(target, part, frame, writes);
7293
7408
  return;
7294
7409
  }
@@ -7307,7 +7422,7 @@ class AssignmentSpecializer {
7307
7422
  return part;
7308
7423
  }
7309
7424
  const declared = part.declared;
7310
- if (!declared || !(declared.flags & ts25.TypeFlags.Union)) {
7425
+ if (!declared || !(declared.flags & ts26.TypeFlags.Union)) {
7311
7426
  return part;
7312
7427
  }
7313
7428
  const defined = this.checker.getNonNullableType(declared);
@@ -7340,7 +7455,7 @@ class AssignmentSpecializer {
7340
7455
  }
7341
7456
 
7342
7457
  // packages/compiler/src/frontend/elaborate/calls.ts
7343
- import ts26 from "typescript";
7458
+ import ts27 from "typescript";
7344
7459
 
7345
7460
  // packages/compiler/src/frontend/elaborate/array-searches.ts
7346
7461
  class ArraySearches {
@@ -7491,19 +7606,19 @@ class CallSpecializer {
7491
7606
  }
7492
7607
  call(node, frame, expected) {
7493
7608
  const callee = node.expression;
7494
- if (ts26.isPropertyAccessExpression(callee) || ts26.isPropertyAccessChain(callee)) {
7609
+ if (ts27.isPropertyAccessExpression(callee) || ts27.isPropertyAccessChain(callee)) {
7495
7610
  const name = callee.name.text;
7496
- if (ts26.isIdentifier(callee.expression) && callee.expression.text === "Array" && name === "from") {
7611
+ if (ts27.isIdentifier(callee.expression) && callee.expression.text === "Array" && name === "from") {
7497
7612
  return this.arrayFrom(node, frame);
7498
7613
  }
7499
- if (callee.expression.kind === ts26.SyntaxKind.SuperKeyword) {
7614
+ if (callee.expression.kind === ts27.SyntaxKind.SuperKeyword) {
7500
7615
  const method = this.expressions.superMember(callee, frame);
7501
7616
  return this.expressions.invoke(method, this.expressions.inOrder(node.arguments, (argument, index) => this.argument(argument, method, index, frame), frame), node, frame, expected);
7502
7617
  }
7503
- if (ts26.isIdentifier(callee.expression) && callee.expression.text === "Math") {
7618
+ if (ts27.isIdentifier(callee.expression) && callee.expression.text === "Math") {
7504
7619
  return this.math(name, node, frame);
7505
7620
  }
7506
- if (ts26.isIdentifier(callee.expression) && callee.expression.text === "Object" && name === "values") {
7621
+ if (ts27.isIdentifier(callee.expression) && callee.expression.text === "Object" && name === "values") {
7507
7622
  const [argument] = node.arguments;
7508
7623
  const object = argument && this.expressions.expression(argument, frame);
7509
7624
  if (object?.kind === "static" && object.node.captured.kind === "object") {
@@ -7551,7 +7666,7 @@ class CallSpecializer {
7551
7666
  }
7552
7667
  return this.expressions.invoke(method, this.expressions.inOrder(node.arguments, (argument, index) => this.argument(argument, method, index, frame), frame), node, frame, expected);
7553
7668
  }
7554
- if (ts26.isIdentifier(callee) && callee.text === "structuredClone") {
7669
+ if (ts27.isIdentifier(callee) && callee.text === "structuredClone") {
7555
7670
  return this.cloned(node, frame);
7556
7671
  }
7557
7672
  const target = this.expressions.expression(callee, frame);
@@ -7562,25 +7677,25 @@ class CallSpecializer {
7562
7677
  const fn = this.functionDeclaration(target.node.captured.file, target.node.captured.name);
7563
7678
  return this.expressions.invoke({ kind: "function", declaration: fn }, this.expressions.inOrder(node.arguments, (argument, index) => this.argument(argument, { kind: "function", declaration: fn }, index, frame), frame), node, frame, expected);
7564
7679
  }
7565
- const sdkFile = ts26.isIdentifier(callee) && this.sdkDeclaration(callee);
7566
- if (ts26.isIdentifier(callee) && sdkFile) {
7680
+ const sdkFile = ts27.isIdentifier(callee) && this.sdkDeclaration(callee);
7681
+ if (ts27.isIdentifier(callee) && sdkFile) {
7567
7682
  return this.sdk(callee.text, sdkModule(sdkFile), node, frame);
7568
7683
  }
7569
7684
  return this.expressions.invoke(target, this.expressions.inOrder(node.arguments, (argument, index) => this.argument(argument, target, index, frame), frame), node, frame, expected);
7570
7685
  }
7571
7686
  argument(node, callee, index, frame) {
7572
- const parameter = callee.kind === "function" && !ts26.isGetAccessorDeclaration(callee.declaration) ? callee.declaration.parameters[index] : undefined;
7687
+ const parameter = callee.kind === "function" && !ts27.isGetAccessorDeclaration(callee.declaration) ? callee.declaration.parameters[index] : undefined;
7573
7688
  return this.expressions.expression(node, frame, parameter && this.checker.getTypeAtLocation(parameter));
7574
7689
  }
7575
7690
  functionDeclaration(file, name) {
7576
7691
  const source = this.sources.find((item) => item.fileName === file);
7577
7692
  for (const statement of source?.statements ?? []) {
7578
- if (ts26.isFunctionDeclaration(statement) && statement.name?.text === name) {
7693
+ if (ts27.isFunctionDeclaration(statement) && statement.name?.text === name) {
7579
7694
  return statement;
7580
7695
  }
7581
- if (ts26.isVariableStatement(statement)) {
7696
+ if (ts27.isVariableStatement(statement)) {
7582
7697
  for (const declaration of statement.declarationList.declarations) {
7583
- if (ts26.isIdentifier(declaration.name) && declaration.name.text === name && declaration.initializer && (ts26.isArrowFunction(declaration.initializer) || ts26.isFunctionExpression(declaration.initializer))) {
7698
+ if (ts27.isIdentifier(declaration.name) && declaration.name.text === name && declaration.initializer && (ts27.isArrowFunction(declaration.initializer) || ts27.isFunctionExpression(declaration.initializer))) {
7584
7699
  return declaration.initializer;
7585
7700
  }
7586
7701
  }
@@ -7600,31 +7715,31 @@ class CallSpecializer {
7600
7715
  return file !== undefined && inSdk(this.sdkFile, file) && file.endsWith("/telemetry.d.ts");
7601
7716
  }
7602
7717
  telemetry(node, callee, frame) {
7603
- const value = (argument) => ts26.isCallExpression(argument) && ts26.isPropertyAccessExpression(argument.expression) && this.telemetryCall(argument.expression) ? this.telemetry(argument, argument.expression, frame) : this.dialect.code(this.expressions.expression(argument, frame), this.checker.getTypeAtLocation(argument));
7718
+ const value = (argument) => ts27.isCallExpression(argument) && ts27.isPropertyAccessExpression(argument.expression) && this.telemetryCall(argument.expression) ? this.telemetry(argument, argument.expression, frame) : this.dialect.code(this.expressions.expression(argument, frame), this.checker.getTypeAtLocation(argument));
7604
7719
  const args = node.arguments.map((argument) => {
7605
- if (ts26.isStringLiteral(argument) || ts26.isNoSubstitutionTemplateLiteral(argument)) {
7720
+ if (ts27.isStringLiteral(argument) || ts27.isNoSubstitutionTemplateLiteral(argument)) {
7606
7721
  return copied(argument);
7607
7722
  }
7608
7723
  const argumentType = this.checker.getTypeAtLocation(argument);
7609
- if (!ts26.isObjectLiteralExpression(argument) && argumentType.flags & ts26.TypeFlags.Object && !this.checker.isArrayType(argumentType)) {
7724
+ if (!ts27.isObjectLiteralExpression(argument) && argumentType.flags & ts27.TypeFlags.Object && !this.checker.isArrayType(argumentType)) {
7610
7725
  const fields = this.expressions.recordFields(argument, frame).map(([name, field]) => mapped`${name}: ${this.dialect.code(field, undefined)}`);
7611
7726
  return mapped`{ ${joined(fields, ", ")} }`;
7612
7727
  }
7613
- if (!ts26.isObjectLiteralExpression(argument)) {
7728
+ if (!ts27.isObjectLiteralExpression(argument)) {
7614
7729
  return value(argument);
7615
7730
  }
7616
7731
  const properties = argument.properties.flatMap((property) => {
7617
- if (ts26.isShorthandPropertyAssignment(property)) {
7732
+ if (ts27.isShorthandPropertyAssignment(property)) {
7618
7733
  const symbol = this.checker.getShorthandAssignmentValueSymbol(property);
7619
7734
  const local = symbol && frame.env.get(symbol);
7620
7735
  return [
7621
7736
  local ? mapped`${copied(property.name)}: ${this.dialect.code(local, this.checker.getTypeAtLocation(property.name))}` : mapped`${copied(property.name)}: ${value(property.name)}`
7622
7737
  ];
7623
7738
  }
7624
- if (ts26.isSpreadAssignment(property)) {
7739
+ if (ts27.isSpreadAssignment(property)) {
7625
7740
  return this.expressions.spreadFields(property, frame).map(([name, field]) => mapped`${name}: ${this.dialect.code(field, undefined)}`);
7626
7741
  }
7627
- if (!ts26.isPropertyAssignment(property)) {
7742
+ if (!ts27.isPropertyAssignment(property)) {
7628
7743
  throw new SpecializeError(property, "Name each telemetry property.");
7629
7744
  }
7630
7745
  return [
@@ -7818,15 +7933,15 @@ class CallSpecializer {
7818
7933
  }
7819
7934
  }
7820
7935
  generator(node, frame) {
7821
- if (!ts26.isCallExpression(node)) {
7936
+ if (!ts27.isCallExpression(node)) {
7822
7937
  return;
7823
7938
  }
7824
7939
  const declaration = this.checker.getResolvedSignature(node)?.declaration;
7825
- if (!declaration || !(ts26.isFunctionDeclaration(declaration) || ts26.isMethodDeclaration(declaration) || ts26.isFunctionExpression(declaration)) || !declaration.asteriskToken || !declaration.body) {
7940
+ if (!declaration || !(ts27.isFunctionDeclaration(declaration) || ts27.isMethodDeclaration(declaration) || ts27.isFunctionExpression(declaration)) || !declaration.asteriskToken || !declaration.body) {
7826
7941
  return;
7827
7942
  }
7828
7943
  const callee = node.expression;
7829
- const target = ts26.isPropertyAccessExpression(callee) ? this.expressions.member(this.expressions.expression(callee.expression, frame), callee.name.text, callee, frame) : this.expressions.expression(callee, frame);
7944
+ const target = ts27.isPropertyAccessExpression(callee) ? this.expressions.member(this.expressions.expression(callee.expression, frame), callee.name.text, callee, frame) : this.expressions.expression(callee, frame);
7830
7945
  const self = target.kind === "function" ? target.self : undefined;
7831
7946
  const args = this.expressions.inOrder(node.arguments, (argument) => this.expressions.expression(argument, frame), frame);
7832
7947
  return { declaration, self, args };
@@ -7905,7 +8020,7 @@ class CallSpecializer {
7905
8020
  }
7906
8021
  arrayFrom(node, frame) {
7907
8022
  const [shape, make] = node.arguments;
7908
- const length = shape && ts26.isObjectLiteralExpression(shape) && this.expressions.member(this.expressions.expression(shape, frame), "length", shape, frame);
8023
+ const length = shape && ts27.isObjectLiteralExpression(shape) && this.expressions.member(this.expressions.expression(shape, frame), "length", shape, frame);
7909
8024
  if (!length || length.kind !== "const" || typeof length.value !== "number") {
7910
8025
  throw new SpecializeError(node, "Array.from needs a length known when the program compiles.");
7911
8026
  }
@@ -7935,11 +8050,11 @@ class CallSpecializer {
7935
8050
  };
7936
8051
  }
7937
8052
  isFilter(node) {
7938
- return ts26.isCallExpression(node) && ts26.isPropertyAccessExpression(node.expression) && node.expression.name.text === "filter" && node.arguments.length === 1;
8053
+ return ts27.isCallExpression(node) && ts27.isPropertyAccessExpression(node.expression) && node.expression.name.text === "filter" && node.arguments.length === 1;
7939
8054
  }
7940
8055
  count(node, frame) {
7941
8056
  const callee = node.expression;
7942
- if (!ts26.isPropertyAccessExpression(callee)) {
8057
+ if (!ts27.isPropertyAccessExpression(callee)) {
7943
8058
  throw new SpecializeError(node, "Not a filter.");
7944
8059
  }
7945
8060
  const items = this.expressions.items(this.expressions.expression(callee.expression, frame));
@@ -8256,9 +8371,9 @@ class FilteredArrays {
8256
8371
  frame.emitter.open(mapped`if (${joined(guards, " && ")}) {`);
8257
8372
  frame.emitter.append(arm.lines);
8258
8373
  if (isTrue(arm.passes)) {
8259
- frame.emitter.line(`${result} = ${arm.node.id};`);
8374
+ frame.emitter.line(`${result} = ${arm.node.reference};`);
8260
8375
  } else if (arm.passes.kind !== "const") {
8261
- frame.emitter.line(mapped`if (${this.dialect.condition(arm.passes, at)}) { ${result} = ${arm.node.id}; }`);
8376
+ frame.emitter.line(mapped`if (${this.dialect.condition(arm.passes, at)}) { ${result} = ${arm.node.reference}; }`);
8262
8377
  }
8263
8378
  frame.emitter.close();
8264
8379
  }
@@ -8290,7 +8405,7 @@ class FilteredArrays {
8290
8405
  if (guarded) {
8291
8406
  frame.emitter.open(mapped`if (${this.dialect.condition(entry.present, at)}) {`);
8292
8407
  }
8293
- const take = `${best} = ${entry.node.id};`;
8408
+ const take = `${best} = ${entry.node.reference};`;
8294
8409
  const rivals = union(before.map((rival) => rival.node)).filter((rival) => rival !== entry.node).map((rival) => {
8295
8410
  const { result, lines } = frame.emitter.detached({ nested: true }, () => this.wins(this.expressions.invoke(order, [entry.item, { kind: "static", node: rival }], at, frame), { last }, at));
8296
8411
  return { rival, wins: result, lines };
@@ -8298,7 +8413,7 @@ class FilteredArrays {
8298
8413
  chain(frame, [
8299
8414
  ...before.some((rival) => isTrue(rival.present)) ? [] : [{ test: `${best} < 0`, body: () => frame.emitter.line(take) }],
8300
8415
  ...rivals.filter(({ wins, lines }) => !isFalse(wins) || lines.length > 0).map(({ rival, wins, lines }) => ({
8301
- test: `${best} === ${rival.id}`,
8416
+ test: `${best} === ${rival.reference}`,
8302
8417
  body: () => {
8303
8418
  frame.emitter.append(lines);
8304
8419
  if (isTrue(wins)) {
@@ -8343,7 +8458,7 @@ class FilteredArrays {
8343
8458
  const nodes = items.map((item) => this.object(item, at));
8344
8459
  chain(frame, nodes.map((item, position) => ({
8345
8460
  test: fromEnd ? mapped`${held} === ${position} || ${held} === ${position - nodes.length}` : mapped`${held} === ${position}`,
8346
- body: () => frame.emitter.line(`${result} = ${item.id};`)
8461
+ body: () => frame.emitter.line(`${result} = ${item.reference};`)
8347
8462
  })));
8348
8463
  return settled2({
8349
8464
  kind: "choice",
@@ -8362,7 +8477,7 @@ class FilteredArrays {
8362
8477
 
8363
8478
  // packages/compiler/src/frontend/elaborate/iterators.ts
8364
8479
  import { primitiveTypes as primitiveTypes4 } from "@tsplc/compiler/ir";
8365
- import ts27 from "typescript";
8480
+ import ts28 from "typescript";
8366
8481
 
8367
8482
  // packages/compiler/src/frontend/elaborate/frame.ts
8368
8483
  class Emitter {
@@ -8482,7 +8597,7 @@ class Iterators {
8482
8597
  }
8483
8598
  readInPlace(node) {
8484
8599
  const user = outside(node);
8485
- if (!ts27.isPropertyAccessExpression(user) && !ts27.isElementAccessExpression(user) && !ts27.isForOfStatement(user)) {
8600
+ if (!ts28.isPropertyAccessExpression(user) && !ts28.isElementAccessExpression(user) && !ts28.isForOfStatement(user)) {
8486
8601
  throw new SpecializeError(node, "A slice with bounds decided at run time has no array to keep: read it where it is made, with every, some, find, findIndex, forEach, includes, indexOf, length or for…of.");
8487
8602
  }
8488
8603
  }
@@ -8622,13 +8737,13 @@ class Iterators {
8622
8737
  };
8623
8738
  }
8624
8739
  traverses(node, frame) {
8625
- if (ts27.isFunctionLike(node)) {
8740
+ if (ts28.isFunctionLike(node)) {
8626
8741
  return false;
8627
8742
  }
8628
- if (ts27.isCallExpression(node) && this.traversing(node, frame)) {
8743
+ if (ts28.isCallExpression(node) && this.traversing(node, frame)) {
8629
8744
  return true;
8630
8745
  }
8631
- return ts27.forEachChild(node, (child) => this.traverses(child, frame)) ?? false;
8746
+ return ts28.forEachChild(node, (child) => this.traverses(child, frame)) ?? false;
8632
8747
  }
8633
8748
  lifted(counted, base, frame, parameters, runtimeArgs, lift) {
8634
8749
  const { source } = counted;
@@ -8667,7 +8782,7 @@ class Iterators {
8667
8782
  return this.runner;
8668
8783
  }
8669
8784
  helper(node) {
8670
- if (!ts27.isCallExpression(node) || !ts27.isPropertyAccessExpression(node.expression)) {
8785
+ if (!ts28.isCallExpression(node) || !ts28.isPropertyAccessExpression(node.expression)) {
8671
8786
  return;
8672
8787
  }
8673
8788
  const receiver = node.expression.expression;
@@ -8685,11 +8800,11 @@ class Iterators {
8685
8800
  if (this.helper(node)) {
8686
8801
  return true;
8687
8802
  }
8688
- return ts27.isPropertyAccessExpression(node.expression) && node.expression.name.text !== "slice" && this.loopsAtRunTime(node.expression.expression, frame, { sliced: false });
8803
+ return ts28.isPropertyAccessExpression(node.expression) && node.expression.name.text !== "slice" && this.loopsAtRunTime(node.expression.expression, frame, { sliced: false });
8689
8804
  }
8690
8805
  loopsAtRunTime(node, frame, { sliced }) {
8691
8806
  const inner = unwrapped2(node);
8692
- if (ts27.isCallExpression(inner) && ts27.isPropertyAccessExpression(inner.expression) && inner.expression.name.text === "slice") {
8807
+ if (ts28.isCallExpression(inner) && ts28.isPropertyAccessExpression(inner.expression) && inner.expression.name.text === "slice") {
8693
8808
  return this.loopsAtRunTime(inner.expression.expression, frame, {
8694
8809
  sliced: true
8695
8810
  });
@@ -8701,11 +8816,11 @@ class Iterators {
8701
8816
  return sliced && value !== undefined && this.storage(value) !== undefined;
8702
8817
  }
8703
8818
  glance(node, frame, { sliced }) {
8704
- if (ts27.isIdentifier(node)) {
8819
+ if (ts28.isIdentifier(node)) {
8705
8820
  const symbol = this.checker.getSymbolAtLocation(node);
8706
8821
  return symbol && frame.env.get(symbol);
8707
8822
  }
8708
- if (!sliced || !ts27.isPropertyAccessExpression(node)) {
8823
+ if (!sliced || !ts28.isPropertyAccessExpression(node)) {
8709
8824
  return;
8710
8825
  }
8711
8826
  try {
@@ -8727,7 +8842,7 @@ class Iterators {
8727
8842
  return this.generated(generator, inner);
8728
8843
  }
8729
8844
  const helper = this.helper(inner);
8730
- if (!helper || !ts27.isCallExpression(inner)) {
8845
+ if (!helper || !ts28.isCallExpression(inner)) {
8731
8846
  throw new SpecializeError(node, "A generator runs in place: call it where a for…of or an iterator helper reads it.");
8732
8847
  }
8733
8848
  const source = this.pipeline(helper.receiver, frame);
@@ -9318,9 +9433,9 @@ var iterationCount = (start, comparison, limit, incrementor) => {
9318
9433
  const size = Math.abs(step);
9319
9434
  const rising = step > 0;
9320
9435
  switch (comparison) {
9321
- case (rising ? ts27.SyntaxKind.LessThanToken : ts27.SyntaxKind.GreaterThanToken):
9436
+ case (rising ? ts28.SyntaxKind.LessThanToken : ts28.SyntaxKind.GreaterThanToken):
9322
9437
  return Math.max(0, Math.ceil(span / size));
9323
- case (rising ? ts27.SyntaxKind.LessThanEqualsToken : ts27.SyntaxKind.GreaterThanEqualsToken):
9438
+ case (rising ? ts28.SyntaxKind.LessThanEqualsToken : ts28.SyntaxKind.GreaterThanEqualsToken):
9324
9439
  return Math.max(0, Math.floor(span / size) + 1);
9325
9440
  default:
9326
9441
  return;
@@ -9350,17 +9465,17 @@ var reread = (sample, array, index) => {
9350
9465
  return sample.kind === "code" ? { ...sample, text: place } : sample;
9351
9466
  };
9352
9467
  var stepOf = (incrementor) => {
9353
- if (ts27.isPrefixUnaryExpression(incrementor) || ts27.isPostfixUnaryExpression(incrementor)) {
9354
- return incrementor.operator === ts27.SyntaxKind.PlusPlusToken ? 1 : -1;
9468
+ if (ts28.isPrefixUnaryExpression(incrementor) || ts28.isPostfixUnaryExpression(incrementor)) {
9469
+ return incrementor.operator === ts28.SyntaxKind.PlusPlusToken ? 1 : -1;
9355
9470
  }
9356
- if (!ts27.isBinaryExpression(incrementor) || !ts27.isNumericLiteral(incrementor.right)) {
9471
+ if (!ts28.isBinaryExpression(incrementor) || !ts28.isNumericLiteral(incrementor.right)) {
9357
9472
  return;
9358
9473
  }
9359
9474
  const size = Number(incrementor.right.text);
9360
9475
  switch (incrementor.operatorToken.kind) {
9361
- case ts27.SyntaxKind.PlusEqualsToken:
9476
+ case ts28.SyntaxKind.PlusEqualsToken:
9362
9477
  return size > 0 ? size : undefined;
9363
- case ts27.SyntaxKind.MinusEqualsToken:
9478
+ case ts28.SyntaxKind.MinusEqualsToken:
9364
9479
  return size > 0 ? -size : undefined;
9365
9480
  default:
9366
9481
  return;
@@ -9387,7 +9502,7 @@ var copyable = (value, at) => {
9387
9502
  }
9388
9503
  return value;
9389
9504
  };
9390
- var copiedFrom = (values, method) => values.some((value) => value.kind === "code" && (value.copyOf !== undefined || value.place === true && value.declared !== undefined && Boolean(value.declared.flags & ts27.TypeFlags.Object))) ? method : undefined;
9505
+ var copiedFrom = (values, method) => values.some((value) => value.kind === "code" && (value.copyOf !== undefined || value.place === true && value.declared !== undefined && Boolean(value.declared.flags & ts28.TypeFlags.Object))) ? method : undefined;
9391
9506
  var fewest = (left, right) => {
9392
9507
  if (left === undefined || right === undefined) {
9393
9508
  return left ?? right;
@@ -9415,9 +9530,9 @@ var all = (conditions) => {
9415
9530
  const tests = conditions.filter((condition) => condition instanceof Mapped);
9416
9531
  return tests.length ? joined(tests, " && ") : true;
9417
9532
  };
9418
- var takes = (callback, parameter) => callback.kind === "function" && !ts27.isGetAccessorDeclaration(callback.declaration) && callback.declaration.parameters.some((declared, position) => position === parameter || declared.dotDotDotToken !== undefined && position < parameter);
9419
- var unwrapped2 = (node) => ts27.isParenthesizedExpression(node) || ts27.isNonNullExpression(node) || ts27.isAsExpression(node) || ts27.isSatisfiesExpression(node) ? unwrapped2(node.expression) : node;
9420
- var outside = (node) => ts27.isParenthesizedExpression(node.parent) || ts27.isNonNullExpression(node.parent) ? outside(node.parent) : node.parent;
9533
+ var takes = (callback, parameter) => callback.kind === "function" && !ts28.isGetAccessorDeclaration(callback.declaration) && callback.declaration.parameters.some((declared, position) => position === parameter || declared.dotDotDotToken !== undefined && position < parameter);
9534
+ var unwrapped2 = (node) => ts28.isParenthesizedExpression(node) || ts28.isNonNullExpression(node) || ts28.isAsExpression(node) || ts28.isSatisfiesExpression(node) ? unwrapped2(node.expression) : node;
9535
+ var outside = (node) => ts28.isParenthesizedExpression(node.parent) || ts28.isNonNullExpression(node.parent) ? outside(node.parent) : node.parent;
9421
9536
 
9422
9537
  // packages/compiler/src/frontend/elaborate/expressions.ts
9423
9538
  class ExpressionSpecializer {
@@ -9459,46 +9574,46 @@ class ExpressionSpecializer {
9459
9574
  }
9460
9575
  return {
9461
9576
  ...value,
9462
- text: from(node, ts28.isIdentifier(node) ? String(value.text) : value.text)
9577
+ text: from(node, ts29.isIdentifier(node) ? String(value.text) : value.text)
9463
9578
  };
9464
9579
  }
9465
9580
  evaluate(node, frame, expected) {
9466
- if (ts28.isParenthesizedExpression(node) || ts28.isNonNullExpression(node) || ts28.isAsExpression(node) || ts28.isSatisfiesExpression(node)) {
9581
+ if (ts29.isParenthesizedExpression(node) || ts29.isNonNullExpression(node) || ts29.isAsExpression(node) || ts29.isSatisfiesExpression(node)) {
9467
9582
  return this.expression(node.expression, frame, expected);
9468
9583
  }
9469
- if (ts28.isNumericLiteral(node)) {
9584
+ if (ts29.isNumericLiteral(node)) {
9470
9585
  return constant(Number(node.text));
9471
9586
  }
9472
- if (ts28.isStringLiteral(node) || ts28.isNoSubstitutionTemplateLiteral(node)) {
9587
+ if (ts29.isStringLiteral(node) || ts29.isNoSubstitutionTemplateLiteral(node)) {
9473
9588
  return constant(node.text);
9474
9589
  }
9475
- if (node.kind === ts28.SyntaxKind.TrueKeyword) {
9590
+ if (node.kind === ts29.SyntaxKind.TrueKeyword) {
9476
9591
  return constant(true);
9477
9592
  }
9478
- if (node.kind === ts28.SyntaxKind.FalseKeyword) {
9593
+ if (node.kind === ts29.SyntaxKind.FalseKeyword) {
9479
9594
  return constant(false);
9480
9595
  }
9481
- if (node.kind === ts28.SyntaxKind.NullKeyword) {
9596
+ if (node.kind === ts29.SyntaxKind.NullKeyword) {
9482
9597
  return constant(undefined);
9483
9598
  }
9484
- if (ts28.isBigIntLiteral(node)) {
9599
+ if (ts29.isBigIntLiteral(node)) {
9485
9600
  return constant(BigInt(node.text.slice(0, -1)));
9486
9601
  }
9487
- if (node.kind === ts28.SyntaxKind.ThisKeyword) {
9602
+ if (node.kind === ts29.SyntaxKind.ThisKeyword) {
9488
9603
  if (!frame.self) {
9489
9604
  throw new SpecializeError(node, "`this` outside a method.");
9490
9605
  }
9491
9606
  return { kind: "static", node: frame.self };
9492
9607
  }
9493
- if (ts28.isIdentifier(node)) {
9608
+ if (ts29.isIdentifier(node)) {
9494
9609
  return this.identifier(node, frame);
9495
9610
  }
9496
- if (ts28.isPropertyAccessExpression(node)) {
9611
+ if (ts29.isPropertyAccessExpression(node)) {
9497
9612
  const member = this.checker.getSymbolAtLocation(node.name)?.valueDeclaration;
9498
- if (member && ts28.isEnumMember(member)) {
9613
+ if (member && ts29.isEnumMember(member)) {
9499
9614
  return constant(this.checker.getConstantValue(member));
9500
9615
  }
9501
- if (node.expression.kind === ts28.SyntaxKind.SuperKeyword) {
9616
+ if (node.expression.kind === ts29.SyntaxKind.SuperKeyword) {
9502
9617
  return this.superMember(node, frame);
9503
9618
  }
9504
9619
  if (this.isMathConstant(node)) {
@@ -9509,15 +9624,15 @@ class ExpressionSpecializer {
9509
9624
  }
9510
9625
  return this.property(this.expression(node.expression, frame), node, frame);
9511
9626
  }
9512
- if (ts28.isElementAccessExpression(node)) {
9627
+ if (ts29.isElementAccessExpression(node)) {
9513
9628
  const object = this.expression(node.expression, frame);
9514
9629
  const index = this.expression(node.argumentExpression, frame);
9515
9630
  return this.element(object, index, node, frame);
9516
9631
  }
9517
- if (ts28.isCallExpression(node)) {
9632
+ if (ts29.isCallExpression(node)) {
9518
9633
  return this.calls.call(node, frame, expected);
9519
9634
  }
9520
- if (ts28.isAwaitExpression(node)) {
9635
+ if (ts29.isAwaitExpression(node)) {
9521
9636
  const value = this.expression(node.expression, frame);
9522
9637
  return {
9523
9638
  kind: "code",
@@ -9529,16 +9644,16 @@ class ExpressionSpecializer {
9529
9644
  if (isUpdate(node)) {
9530
9645
  return this.assignments.step(node, frame, { used: true });
9531
9646
  }
9532
- if (ts28.isTypeOfExpression(node)) {
9647
+ if (ts29.isTypeOfExpression(node)) {
9533
9648
  return this.typeOf(this.expression(node.expression, frame));
9534
9649
  }
9535
- if (ts28.isPrefixUnaryExpression(node)) {
9650
+ if (ts29.isPrefixUnaryExpression(node)) {
9536
9651
  return this.unary(node, frame);
9537
9652
  }
9538
- if (ts28.isBinaryExpression(node)) {
9653
+ if (ts29.isBinaryExpression(node)) {
9539
9654
  return this.binary(node, frame, expected);
9540
9655
  }
9541
- if (ts28.isConditionalExpression(node)) {
9656
+ if (ts29.isConditionalExpression(node)) {
9542
9657
  const condition = this.expression(node.condition, frame);
9543
9658
  if (condition.kind === "const") {
9544
9659
  return this.expression(condition.value ? node.whenTrue : node.whenFalse, frame, expected);
@@ -9563,7 +9678,7 @@ class ExpressionSpecializer {
9563
9678
  copyOf: [whenTrue, whenFalse].find((branch) => branch.kind === "code" && branch.copyOf !== undefined)?.copyOf
9564
9679
  };
9565
9680
  }
9566
- if (ts28.isArrowFunction(node) || ts28.isFunctionExpression(node)) {
9681
+ if (ts29.isArrowFunction(node) || ts29.isFunctionExpression(node)) {
9567
9682
  return {
9568
9683
  kind: "function",
9569
9684
  declaration: node,
@@ -9571,13 +9686,13 @@ class ExpressionSpecializer {
9571
9686
  env: frame.env
9572
9687
  };
9573
9688
  }
9574
- if (ts28.isObjectLiteralExpression(node)) {
9689
+ if (ts29.isObjectLiteralExpression(node)) {
9575
9690
  return this.objectLiteral(node, frame);
9576
9691
  }
9577
- if (ts28.isArrayLiteralExpression(node)) {
9692
+ if (ts29.isArrayLiteralExpression(node)) {
9578
9693
  const items = [];
9579
9694
  for (const element of node.elements) {
9580
- if (ts28.isSpreadElement(element)) {
9695
+ if (ts29.isSpreadElement(element)) {
9581
9696
  const spread = this.items(this.expression(element.expression, frame));
9582
9697
  if (!spread) {
9583
9698
  throw new SpecializeError(element, "Spread an array setup built.");
@@ -9589,10 +9704,10 @@ class ExpressionSpecializer {
9589
9704
  }
9590
9705
  return { kind: "virtual", items };
9591
9706
  }
9592
- if (ts28.isTemplateExpression(node)) {
9707
+ if (ts29.isTemplateExpression(node)) {
9593
9708
  throw new SpecializeError(node, "Template strings are not supported in scan code.");
9594
9709
  }
9595
- throw new SpecializeError(node, `${ts28.SyntaxKind[node.kind]} is not supported in scan code.`);
9710
+ throw new SpecializeError(node, `${ts29.SyntaxKind[node.kind]} is not supported in scan code.`);
9596
9711
  }
9597
9712
  property(object, node, frame) {
9598
9713
  if (node.questionDotToken && object.kind === "const" && object.value === undefined) {
@@ -9624,31 +9739,31 @@ class ExpressionSpecializer {
9624
9739
  if (!declaration) {
9625
9740
  throw new SpecializeError(node, `${node.text} has no declaration.`);
9626
9741
  }
9627
- if (ts28.isFunctionDeclaration(declaration)) {
9742
+ if (ts29.isFunctionDeclaration(declaration)) {
9628
9743
  return { kind: "function", declaration };
9629
9744
  }
9630
- if (ts28.isVariableDeclaration(declaration)) {
9745
+ if (ts29.isVariableDeclaration(declaration)) {
9631
9746
  const initializer = declaration.initializer;
9632
- if (initializer && (ts28.isArrowFunction(initializer) || ts28.isFunctionExpression(initializer))) {
9747
+ if (initializer && (ts29.isArrowFunction(initializer) || ts29.isFunctionExpression(initializer))) {
9633
9748
  return { kind: "function", declaration: initializer };
9634
9749
  }
9635
9750
  const root = this.model.roots.find((item) => item.declaration === declaration);
9636
9751
  if (root) {
9637
9752
  return this.storage.rootValue(root);
9638
9753
  }
9639
- if (ts28.isVariableStatement(declaration.parent.parent) && declaration.parent.parent.parent && ts28.isSourceFile(declaration.parent.parent.parent)) {
9754
+ if (ts29.isVariableStatement(declaration.parent.parent) && declaration.parent.parent.parent && ts29.isSourceFile(declaration.parent.parent.parent)) {
9640
9755
  if (initializer) {
9641
9756
  return this.expression(initializer, { ...frame, env: new Map });
9642
9757
  }
9643
9758
  }
9644
9759
  }
9645
- if (ts28.isBindingElement(declaration)) {
9760
+ if (ts29.isBindingElement(declaration)) {
9646
9761
  const root = this.model.roots.find((item) => item.declaration === declaration);
9647
9762
  if (root) {
9648
9763
  return this.storage.rootValue(root);
9649
9764
  }
9650
9765
  }
9651
- if (ts28.isEnumMember(declaration)) {
9766
+ if (ts29.isEnumMember(declaration)) {
9652
9767
  return constant(this.checker.getConstantValue(declaration));
9653
9768
  }
9654
9769
  throw new SpecializeError(node, `${node.text} is not available in scan code.`);
@@ -9674,7 +9789,7 @@ class ExpressionSpecializer {
9674
9789
  }
9675
9790
  if (captured.kind === "instance") {
9676
9791
  const members = this.model.members(this.model.classOf(node));
9677
- const accessor = members.find((member) => ts28.isGetAccessorDeclaration(member) && member.name.getText() === name);
9792
+ const accessor = members.find((member) => ts29.isGetAccessorDeclaration(member) && member.name.getText() === name);
9678
9793
  if (accessor) {
9679
9794
  const returned = onlyReturned(accessor);
9680
9795
  if (returned) {
@@ -9688,7 +9803,7 @@ class ExpressionSpecializer {
9688
9803
  }
9689
9804
  return this.invoke({ kind: "function", declaration: accessor, self: node }, [], at, frame);
9690
9805
  }
9691
- const method = members.find((member) => ts28.isMethodDeclaration(member) && member.name.getText() === name);
9806
+ const method = members.find((member) => ts29.isMethodDeclaration(member) && member.name.getText() === name);
9692
9807
  if (method) {
9693
9808
  return { kind: "function", declaration: method, self: node };
9694
9809
  }
@@ -9777,8 +9892,10 @@ class ExpressionSpecializer {
9777
9892
  if (known) {
9778
9893
  return known;
9779
9894
  }
9895
+ const id = -1 - this.services.size;
9780
9896
  const node = {
9781
- id: -1 - this.services.size,
9897
+ id,
9898
+ reference: id,
9782
9899
  captured: { kind: "service", path }
9783
9900
  };
9784
9901
  this.services.set(path, node);
@@ -9874,7 +9991,8 @@ class ExpressionSpecializer {
9874
9991
  if (!node.type) {
9875
9992
  throw new Error("A table needs a declared type.");
9876
9993
  }
9877
- const name = `tsplcTable${this.tables.size + 1}`;
9994
+ const identity = this.model.identity(node);
9995
+ const name = identity ? `tsplcTable_${identityDigest4(identity)}` : `tsplcTable${this.tables.size + 1}`;
9878
9996
  this.tables.set(node.id, name);
9879
9997
  const type = this.layouts.text(node.type, { kind: "node", id: node.id });
9880
9998
  this.tableDeclarations.push(from(at, `const ${name}: ${type} = ${this.initializers.valueText({ kind: "node", id: node.id }, node.type, type)};`));
@@ -9893,13 +10011,13 @@ class ExpressionSpecializer {
9893
10011
  objectLiteral(node, frame) {
9894
10012
  const fields = new Map;
9895
10013
  for (const property of node.properties) {
9896
- if (ts28.isPropertyAssignment(property)) {
10014
+ if (ts29.isPropertyAssignment(property)) {
9897
10015
  fields.set(property.name.getText(), this.expression(property.initializer, frame, this.checker.getContextualType(property.initializer)));
9898
- } else if (ts28.isShorthandPropertyAssignment(property)) {
10016
+ } else if (ts29.isShorthandPropertyAssignment(property)) {
9899
10017
  const symbol = this.checker.getShorthandAssignmentValueSymbol(property);
9900
10018
  const local = symbol && frame.env.get(symbol);
9901
10019
  fields.set(property.name.text, local ?? this.expression(property.name, frame));
9902
- } else if (ts28.isSpreadAssignment(property)) {
10020
+ } else if (ts29.isSpreadAssignment(property)) {
9903
10021
  for (const [name, value] of this.spreadFields(property, frame)) {
9904
10022
  fields.set(name, value);
9905
10023
  }
@@ -9912,7 +10030,7 @@ class ExpressionSpecializer {
9912
10030
  unary(node, frame) {
9913
10031
  const operand = this.expression(node.operand, frame);
9914
10032
  switch (node.operator) {
9915
- case ts28.SyntaxKind.ExclamationToken:
10033
+ case ts29.SyntaxKind.ExclamationToken:
9916
10034
  if (operand.kind === "const") {
9917
10035
  return constant(!operand.value);
9918
10036
  }
@@ -9924,7 +10042,7 @@ class ExpressionSpecializer {
9924
10042
  text: mapped`!${this.dialect.condition(operand, node.operand)}`,
9925
10043
  declared: this.checker.getBooleanType()
9926
10044
  };
9927
- case ts28.SyntaxKind.MinusToken:
10045
+ case ts29.SyntaxKind.MinusToken:
9928
10046
  if (operand.kind === "const" && typeof operand.value === "number") {
9929
10047
  return constant(-operand.value);
9930
10048
  }
@@ -9933,17 +10051,17 @@ class ExpressionSpecializer {
9933
10051
  text: mapped`-${this.dialect.code(operand, undefined)}`,
9934
10052
  declared: this.checker.getTypeAtLocation(node)
9935
10053
  };
9936
- case ts28.SyntaxKind.PlusToken:
10054
+ case ts29.SyntaxKind.PlusToken:
9937
10055
  return operand;
9938
10056
  default:
9939
- throw new SpecializeError(node, `${ts28.tokenToString(node.operator)} is not supported.`);
10057
+ throw new SpecializeError(node, `${ts29.tokenToString(node.operator)} is not supported.`);
9940
10058
  }
9941
10059
  }
9942
10060
  binary(node, frame, expected) {
9943
10061
  const kind = node.operatorToken.kind;
9944
- if (kind === ts28.SyntaxKind.AmpersandAmpersandToken || kind === ts28.SyntaxKind.BarBarToken) {
10062
+ if (kind === ts29.SyntaxKind.AmpersandAmpersandToken || kind === ts29.SyntaxKind.BarBarToken) {
9945
10063
  const left = this.expression(node.left, frame);
9946
- const and = kind === ts28.SyntaxKind.AmpersandAmpersandToken;
10064
+ const and = kind === ts29.SyntaxKind.AmpersandAmpersandToken;
9947
10065
  if (left.kind === "const") {
9948
10066
  if (Boolean(left.value) !== and) {
9949
10067
  return left;
@@ -9996,7 +10114,7 @@ class ExpressionSpecializer {
9996
10114
  declared: this.checker.getBooleanType()
9997
10115
  };
9998
10116
  }
9999
- if (kind === ts28.SyntaxKind.QuestionQuestionToken) {
10117
+ if (kind === ts29.SyntaxKind.QuestionQuestionToken) {
10000
10118
  const left = this.expression(node.left, frame);
10001
10119
  if (left.kind === "const") {
10002
10120
  return left.value === undefined ? this.expression(node.right, frame, expected) : left;
@@ -10035,15 +10153,15 @@ class ExpressionSpecializer {
10035
10153
  return this.assignments.assign(node, frame);
10036
10154
  }
10037
10155
  const equality = [
10038
- ts28.SyntaxKind.EqualsEqualsEqualsToken,
10039
- ts28.SyntaxKind.ExclamationEqualsEqualsToken,
10040
- ts28.SyntaxKind.EqualsEqualsToken,
10041
- ts28.SyntaxKind.ExclamationEqualsToken
10156
+ ts29.SyntaxKind.EqualsEqualsEqualsToken,
10157
+ ts29.SyntaxKind.ExclamationEqualsEqualsToken,
10158
+ ts29.SyntaxKind.EqualsEqualsToken,
10159
+ ts29.SyntaxKind.ExclamationEqualsToken
10042
10160
  ].includes(kind);
10043
10161
  const read = this.expression(node.left, frame);
10044
10162
  const left = containsWrite(node.right) ? this.held(read, frame) : read;
10045
10163
  const right = this.expression(node.right, frame, read.kind === "code" ? read.declared : undefined);
10046
- const negate = kind === ts28.SyntaxKind.ExclamationEqualsEqualsToken || kind === ts28.SyntaxKind.ExclamationEqualsToken;
10164
+ const negate = kind === ts29.SyntaxKind.ExclamationEqualsEqualsToken || kind === ts29.SyntaxKind.ExclamationEqualsToken;
10047
10165
  if (equality) {
10048
10166
  this.references.identities(left, right, node);
10049
10167
  return this.equality(left, right, { negate });
@@ -10054,7 +10172,7 @@ class ExpressionSpecializer {
10054
10172
  return constant(folded);
10055
10173
  }
10056
10174
  }
10057
- if (kind === ts28.SyntaxKind.AsteriskAsteriskToken) {
10175
+ if (kind === ts29.SyntaxKind.AsteriskAsteriskToken) {
10058
10176
  if (left.kind === "const" && right.kind === "const" && typeof left.value === "number" && typeof right.value === "number") {
10059
10177
  return constant(left.value ** right.value);
10060
10178
  }
@@ -10083,7 +10201,7 @@ class ExpressionSpecializer {
10083
10201
  }
10084
10202
  isNumber(node) {
10085
10203
  const flags = this.checker.getTypeAtLocation(node).flags;
10086
- return Boolean(flags & (ts28.TypeFlags.Number | ts28.TypeFlags.NumberLiteral)) && !(flags & ts28.TypeFlags.EnumLike);
10204
+ return Boolean(flags & (ts29.TypeFlags.Number | ts29.TypeFlags.NumberLiteral)) && !(flags & ts29.TypeFlags.EnumLike);
10087
10205
  }
10088
10206
  firstNonZero(left, node, frame) {
10089
10207
  const once = this.temporaryOf(left, frame);
@@ -10145,7 +10263,7 @@ class ExpressionSpecializer {
10145
10263
  throw new SpecializeError(at, "Only functions can be called.");
10146
10264
  }
10147
10265
  const declaration = target.declaration;
10148
- if ((ts28.isArrowFunction(declaration) || ts28.isFunctionExpression(declaration)) && target.env && ts28.isArrowFunction(declaration) && !ts28.isBlock(declaration.body)) {
10266
+ if ((ts29.isArrowFunction(declaration) || ts29.isFunctionExpression(declaration)) && target.env && ts29.isArrowFunction(declaration) && !ts29.isBlock(declaration.body)) {
10149
10267
  const inline = {
10150
10268
  ...frame,
10151
10269
  env: new Map(target.env),
@@ -10161,8 +10279,8 @@ class ExpressionSpecializer {
10161
10279
  const called = this.routineTable.routine(declaration, target.self, args, target.env);
10162
10280
  const text = mapped`${called.name}(${joined(called.args, ", ")})`;
10163
10281
  const returns = called.returns;
10164
- if (!returns || returns.flags & ts28.TypeFlags.Void) {
10165
- if (ts28.isExpressionStatement(at.parent)) {
10282
+ if (!returns || returns.flags & ts29.TypeFlags.Void) {
10283
+ if (ts29.isExpressionStatement(at.parent)) {
10166
10284
  return { kind: "code", text, declared: returns };
10167
10285
  }
10168
10286
  frame.emitter.line(mapped`${text};`);
@@ -10182,17 +10300,17 @@ class ExpressionSpecializer {
10182
10300
  };
10183
10301
  }
10184
10302
  superMember(node, frame) {
10185
- const owner = ts28.findAncestor(node, ts28.isClassDeclaration);
10303
+ const owner = ts29.findAncestor(node, ts29.isClassDeclaration);
10186
10304
  if (!owner || !frame.self) {
10187
10305
  throw new SpecializeError(node, "`super` outside a method.");
10188
10306
  }
10189
10307
  const name = node.name.text;
10190
10308
  const inherited = this.model.ancestry(owner).slice(1).flatMap((base) => [...base.members]);
10191
- const accessor = inherited.find((member) => ts28.isGetAccessorDeclaration(member) && member.name.getText() === name);
10309
+ const accessor = inherited.find((member) => ts29.isGetAccessorDeclaration(member) && member.name.getText() === name);
10192
10310
  if (accessor) {
10193
10311
  return this.invoke({ kind: "function", declaration: accessor, self: frame.self }, [], node, frame);
10194
10312
  }
10195
- const method = inherited.find((member) => ts28.isMethodDeclaration(member) && member.name.getText() === name);
10313
+ const method = inherited.find((member) => ts29.isMethodDeclaration(member) && member.name.getText() === name);
10196
10314
  if (!method) {
10197
10315
  throw new SpecializeError(node, `The base class has no ${name}.`);
10198
10316
  }
@@ -10218,7 +10336,7 @@ class ExpressionSpecializer {
10218
10336
  if (inner.some((item) => item.kind === "static" || item.kind === "function" || item.kind === "choice")) {
10219
10337
  return false;
10220
10338
  }
10221
- const scope = ts28.findAncestor(name.parent, ts28.isFunctionLike) ?? name.getSourceFile();
10339
+ const scope = ts29.findAncestor(name.parent, ts29.isFunctionLike) ?? name.getSourceFile();
10222
10340
  return writesThrough(scope, symbol, this.checker);
10223
10341
  }
10224
10342
  typeOf(value) {
@@ -10233,16 +10351,16 @@ class ExpressionSpecializer {
10233
10351
  }
10234
10352
  const declared = value.declared;
10235
10353
  const kinds = [
10236
- [ts28.TypeFlags.NumberLike, "number"],
10237
- [ts28.TypeFlags.StringLike, "string"],
10238
- [ts28.TypeFlags.BooleanLike, "boolean"],
10239
- [ts28.TypeFlags.BigIntLike, "bigint"]
10354
+ [ts29.TypeFlags.NumberLike, "number"],
10355
+ [ts29.TypeFlags.StringLike, "string"],
10356
+ [ts29.TypeFlags.BooleanLike, "boolean"],
10357
+ [ts29.TypeFlags.BigIntLike, "bigint"]
10240
10358
  ];
10241
10359
  const found = kinds.find(([flag]) => declared.flags & flag);
10242
10360
  return constant(found ? found[1] : "object");
10243
10361
  }
10244
10362
  isMathConstant(node) {
10245
- return ts28.isIdentifier(node.expression) && node.expression.text === "Math" && mathConstants.has(node.name.text) && (this.checker.getSymbolAtLocation(node.expression)?.declarations?.every((declaration) => declaration.getSourceFile().isDeclarationFile) ?? false);
10363
+ return ts29.isIdentifier(node.expression) && node.expression.text === "Math" && mathConstants.has(node.name.text) && (this.checker.getSymbolAtLocation(node.expression)?.declarations?.every((declaration) => declaration.getSourceFile().isDeclarationFile) ?? false);
10246
10364
  }
10247
10365
  closure(node, at) {
10248
10366
  const captured = node.captured;
@@ -10344,8 +10462,8 @@ class ExpressionSpecializer {
10344
10462
  return { kind: "code", text: local, declared: value.declared, place: true };
10345
10463
  }
10346
10464
  bind(name, value, mutable, frame, declared, iec) {
10347
- const bound = !ts28.isIdentifier(name) && value.kind === "code" && !value.place ? this.temporaryOf(value, frame) : value;
10348
- if (ts28.isObjectBindingPattern(name)) {
10465
+ const bound = !ts29.isIdentifier(name) && value.kind === "code" && !value.place ? this.temporaryOf(value, frame) : value;
10466
+ if (ts29.isObjectBindingPattern(name)) {
10349
10467
  for (const element of name.elements) {
10350
10468
  const field = (element.propertyName ?? element.name).getText();
10351
10469
  const inner = this.member(bound, field, element, frame);
@@ -10353,9 +10471,9 @@ class ExpressionSpecializer {
10353
10471
  }
10354
10472
  return;
10355
10473
  }
10356
- if (ts28.isArrayBindingPattern(name)) {
10474
+ if (ts29.isArrayBindingPattern(name)) {
10357
10475
  name.elements.forEach((element, index) => {
10358
- if (ts28.isOmittedExpression(element)) {
10476
+ if (ts29.isOmittedExpression(element)) {
10359
10477
  return;
10360
10478
  }
10361
10479
  const inner = this.element(bound, constant(index), element, frame);
@@ -10386,20 +10504,20 @@ class ExpressionSpecializer {
10386
10504
  frame.env.set(symbol, bound);
10387
10505
  return;
10388
10506
  }
10389
- if (!mutable && bound.kind === "code" && bound.place && ts28.isIdentifier(name) && this.isAggregate(this.checker.getNonNullableType(declared)) && replacedWhileAliased(name, this.checker)) {
10507
+ if (!mutable && bound.kind === "code" && bound.place && ts29.isIdentifier(name) && this.isAggregate(this.checker.getNonNullableType(declared)) && replacedWhileAliased(name, this.checker)) {
10390
10508
  this.snapshot(name, symbol, bound, declared, frame);
10391
10509
  return;
10392
10510
  }
10393
10511
  if (!mutable && bound.kind === "code" && bound.place) {
10394
10512
  if (this.isAggregate(declared)) {
10395
10513
  const pin = bound.pinned;
10396
- const repeats = ts28.isIdentifier(name) && pureRead(bound.text) && stableAlias(name, this.checker);
10514
+ const repeats = ts29.isIdentifier(name) && pureRead(bound.text) && stableAlias(name, this.checker);
10397
10515
  frame.env.set(symbol, pin && !repeats ? pin(frame) : bound);
10398
10516
  return;
10399
10517
  }
10400
10518
  }
10401
10519
  const local = frame.emitter.local(name.text);
10402
- const changes = !mutable && this.isAggregate(declared) && writesThrough(ts28.findAncestor(name.parent, ts28.isFunctionLike) ?? name.getSourceFile(), symbol, this.checker);
10520
+ const changes = !mutable && this.isAggregate(declared) && writesThrough(ts29.findAncestor(name.parent, ts29.isFunctionLike) ?? name.getSourceFile(), symbol, this.checker);
10403
10521
  const width = iec ?? (bound.kind === "code" ? bound.iec : undefined);
10404
10522
  const layout = bound.kind === "code" ? bound.layout : undefined;
10405
10523
  const length = bound.kind === "code" ? bound.length : undefined;
@@ -10425,7 +10543,7 @@ class ExpressionSpecializer {
10425
10543
  return this.layouts.text(this.checker.getBaseTypeOfLiteralType(declared));
10426
10544
  }
10427
10545
  snapshot(name, symbol, bound, declared, frame) {
10428
- if (writesThrough(ts28.findAncestor(name.parent, ts28.isFunctionLike) ?? name.getSourceFile(), symbol, this.checker)) {
10546
+ if (writesThrough(ts29.findAncestor(name.parent, ts29.isFunctionLike) ?? name.getSourceFile(), symbol, this.checker)) {
10429
10547
  throw new SpecializeError(name, "This const is changed through, and the place it names is assigned anew while it is still used: the PLC can't keep both. Take a structuredClone of it, or change the place through its own path.");
10430
10548
  }
10431
10549
  const local = frame.emitter.local(name.text);
@@ -10442,7 +10560,7 @@ class ExpressionSpecializer {
10442
10560
  });
10443
10561
  }
10444
10562
  isAggregate(type) {
10445
- return Boolean(type.flags & ts28.TypeFlags.Object) && !this.layouts.literalEnum(type);
10563
+ return Boolean(type.flags & ts29.TypeFlags.Object) && !this.layouts.literalEnum(type);
10446
10564
  }
10447
10565
  items(value) {
10448
10566
  if (value.kind === "virtual" && value.items) {
@@ -10470,37 +10588,37 @@ class ExpressionSpecializer {
10470
10588
  }
10471
10589
  }
10472
10590
  var binaryOperators = new Map([
10473
- [ts28.SyntaxKind.PlusToken, "+"],
10474
- [ts28.SyntaxKind.MinusToken, "-"],
10475
- [ts28.SyntaxKind.AsteriskToken, "*"],
10476
- [ts28.SyntaxKind.PercentToken, "%"],
10477
- [ts28.SyntaxKind.LessThanToken, "<"],
10478
- [ts28.SyntaxKind.LessThanEqualsToken, "<="],
10479
- [ts28.SyntaxKind.GreaterThanToken, ">"],
10480
- [ts28.SyntaxKind.GreaterThanEqualsToken, ">="],
10481
- [ts28.SyntaxKind.AmpersandToken, "&"],
10482
- [ts28.SyntaxKind.BarToken, "|"],
10483
- [ts28.SyntaxKind.CaretToken, "^"],
10484
- [ts28.SyntaxKind.LessThanLessThanToken, "<<"],
10485
- [ts28.SyntaxKind.GreaterThanGreaterThanToken, ">>"]
10591
+ [ts29.SyntaxKind.PlusToken, "+"],
10592
+ [ts29.SyntaxKind.MinusToken, "-"],
10593
+ [ts29.SyntaxKind.AsteriskToken, "*"],
10594
+ [ts29.SyntaxKind.PercentToken, "%"],
10595
+ [ts29.SyntaxKind.LessThanToken, "<"],
10596
+ [ts29.SyntaxKind.LessThanEqualsToken, "<="],
10597
+ [ts29.SyntaxKind.GreaterThanToken, ">"],
10598
+ [ts29.SyntaxKind.GreaterThanEqualsToken, ">="],
10599
+ [ts29.SyntaxKind.AmpersandToken, "&"],
10600
+ [ts29.SyntaxKind.BarToken, "|"],
10601
+ [ts29.SyntaxKind.CaretToken, "^"],
10602
+ [ts29.SyntaxKind.LessThanLessThanToken, "<<"],
10603
+ [ts29.SyntaxKind.GreaterThanGreaterThanToken, ">>"]
10486
10604
  ]);
10487
10605
  var foldNumber = (kind, left, right) => {
10488
10606
  switch (kind) {
10489
- case ts28.SyntaxKind.PlusToken:
10607
+ case ts29.SyntaxKind.PlusToken:
10490
10608
  return left + right;
10491
- case ts28.SyntaxKind.MinusToken:
10609
+ case ts29.SyntaxKind.MinusToken:
10492
10610
  return left - right;
10493
- case ts28.SyntaxKind.AsteriskToken:
10611
+ case ts29.SyntaxKind.AsteriskToken:
10494
10612
  return left * right;
10495
- case ts28.SyntaxKind.PercentToken:
10613
+ case ts29.SyntaxKind.PercentToken:
10496
10614
  return right === 0 ? undefined : left % right;
10497
- case ts28.SyntaxKind.LessThanToken:
10615
+ case ts29.SyntaxKind.LessThanToken:
10498
10616
  return left < right;
10499
- case ts28.SyntaxKind.LessThanEqualsToken:
10617
+ case ts29.SyntaxKind.LessThanEqualsToken:
10500
10618
  return left <= right;
10501
- case ts28.SyntaxKind.GreaterThanToken:
10619
+ case ts29.SyntaxKind.GreaterThanToken:
10502
10620
  return left > right;
10503
- case ts28.SyntaxKind.GreaterThanEqualsToken:
10621
+ case ts29.SyntaxKind.GreaterThanEqualsToken:
10504
10622
  return left >= right;
10505
10623
  default:
10506
10624
  return;
@@ -10519,10 +10637,10 @@ var mathConstants = new Map([
10519
10637
  var isReadonly = (type, checker) => checker.isArrayType(type) === false && type.getSymbol()?.name === "ReadonlyArray" || type.aliasSymbol?.name === "Readonly" || checker.typeToString(type).startsWith("readonly ");
10520
10638
  var findClosure = (source, start) => {
10521
10639
  const visit = (node) => {
10522
- if ((ts28.isArrowFunction(node) || ts28.isFunctionExpression(node)) && node.getStart(source) === start) {
10640
+ if ((ts29.isArrowFunction(node) || ts29.isFunctionExpression(node)) && node.getStart(source) === start) {
10523
10641
  return node;
10524
10642
  }
10525
- return node.pos <= start && start < node.end ? ts28.forEachChild(node, visit) : undefined;
10643
+ return node.pos <= start && start < node.end ? ts29.forEachChild(node, visit) : undefined;
10526
10644
  };
10527
10645
  return visit(source);
10528
10646
  };
@@ -10541,26 +10659,26 @@ var capturedConstant = (value) => {
10541
10659
  var closureSymbols = (declaration, checker) => {
10542
10660
  const found = new Map;
10543
10661
  const visit = (node) => {
10544
- if (ts28.isIdentifier(node)) {
10545
- const symbol = ts28.isShorthandPropertyAssignment(node.parent) ? checker.getShorthandAssignmentValueSymbol(node.parent) : checker.getSymbolAtLocation(node);
10662
+ if (ts29.isIdentifier(node)) {
10663
+ const symbol = ts29.isShorthandPropertyAssignment(node.parent) ? checker.getShorthandAssignmentValueSymbol(node.parent) : checker.getSymbolAtLocation(node);
10546
10664
  const known = found.get(node.text) ?? [];
10547
10665
  if (symbol && !known.includes(symbol)) {
10548
10666
  found.set(node.text, [...known, symbol]);
10549
10667
  }
10550
10668
  }
10551
- ts28.forEachChild(node, visit);
10669
+ ts29.forEachChild(node, visit);
10552
10670
  };
10553
10671
  visit(declaration);
10554
10672
  return found;
10555
10673
  };
10556
10674
  var onlyReturned = (accessor) => {
10557
10675
  const [only, ...others] = accessor.body?.statements ?? [];
10558
- return only && !others.length && ts28.isReturnStatement(only) ? only.expression : undefined;
10676
+ return only && !others.length && ts29.isReturnStatement(only) ? only.expression : undefined;
10559
10677
  };
10560
10678
  var pureRead = (text) => !/[\w\]>]\s*\(/.test(String(text).replace(/\b(?:wrap|exact)<\w+>\(/g, "("));
10561
10679
 
10562
10680
  // packages/compiler/src/frontend/elaborate/initializers.ts
10563
- import ts29 from "typescript";
10681
+ import ts30 from "typescript";
10564
10682
  class Initializers {
10565
10683
  model;
10566
10684
  checker;
@@ -10696,13 +10814,13 @@ class Initializers {
10696
10814
  }
10697
10815
  }
10698
10816
  defaultOf(type) {
10699
- if (!type || type.flags & ts29.TypeFlags.Void) {
10817
+ if (!type || type.flags & ts30.TypeFlags.Void) {
10700
10818
  return "";
10701
10819
  }
10702
- if (type.flags & ts29.TypeFlags.BooleanLike) {
10820
+ if (type.flags & ts30.TypeFlags.BooleanLike) {
10703
10821
  return "false";
10704
10822
  }
10705
- if (type.flags & ts29.TypeFlags.NumberLike) {
10823
+ if (type.flags & ts30.TypeFlags.NumberLike) {
10706
10824
  return "0";
10707
10825
  }
10708
10826
  return `defaultValue<${this.layouts.text(type)}>()`;
@@ -10710,7 +10828,7 @@ class Initializers {
10710
10828
  }
10711
10829
 
10712
10830
  // packages/compiler/src/frontend/elaborate/statements.ts
10713
- import ts30 from "typescript";
10831
+ import ts31 from "typescript";
10714
10832
  class StatementSpecializer {
10715
10833
  expressions;
10716
10834
  scopes = [];
@@ -10732,7 +10850,7 @@ class StatementSpecializer {
10732
10850
  });
10733
10851
  }
10734
10852
  body(node, frame) {
10735
- if (ts30.isBlock(node)) {
10853
+ if (ts31.isBlock(node)) {
10736
10854
  this.statements(node.statements, frame);
10737
10855
  } else {
10738
10856
  frame.emitter.origin = node;
@@ -10753,7 +10871,7 @@ class StatementSpecializer {
10753
10871
  try {
10754
10872
  return this.specializeStatement(node, frame);
10755
10873
  } catch (cause) {
10756
- if (!(cause instanceof SpecializeError) || ts30.isBlock(node) || node.getChildren().some((child) => ts30.isBlock(child))) {
10874
+ if (!(cause instanceof SpecializeError) || ts31.isBlock(node) || node.getChildren().some((child) => ts31.isBlock(child))) {
10757
10875
  throw cause;
10758
10876
  }
10759
10877
  if (!this.failures.some((failure) => failure.node === cause.node && failure.message === cause.message)) {
@@ -10766,74 +10884,74 @@ class StatementSpecializer {
10766
10884
  }
10767
10885
  specializeStatement(node, frame) {
10768
10886
  const { emitter } = frame;
10769
- if (ts30.isBlock(node)) {
10887
+ if (ts31.isBlock(node)) {
10770
10888
  emitter.open("{");
10771
10889
  const returns = this.statements(node.statements, frame);
10772
10890
  emitter.close();
10773
10891
  return returns;
10774
10892
  }
10775
- if (ts30.isVariableStatement(node)) {
10776
- const mutable = !(node.declarationList.flags & ts30.NodeFlags.Const);
10893
+ if (ts31.isVariableStatement(node)) {
10894
+ const mutable = !(node.declarationList.flags & ts31.NodeFlags.Const);
10777
10895
  for (const declaration of node.declarationList.declarations) {
10778
10896
  this.declare(declaration, mutable, frame);
10779
10897
  }
10780
10898
  return false;
10781
10899
  }
10782
- if (ts30.isExpressionStatement(node)) {
10783
- if (ts30.isYieldExpression(node.expression)) {
10900
+ if (ts31.isExpressionStatement(node)) {
10901
+ if (ts31.isYieldExpression(node.expression)) {
10784
10902
  this.yieldStatement(node.expression, frame);
10785
10903
  return false;
10786
10904
  }
10787
10905
  this.effect(node.expression, frame);
10788
10906
  return false;
10789
10907
  }
10790
- if (ts30.isIfStatement(node)) {
10908
+ if (ts31.isIfStatement(node)) {
10791
10909
  return this.ifStatement(node, frame);
10792
10910
  }
10793
- if (ts30.isReturnStatement(node)) {
10911
+ if (ts31.isReturnStatement(node)) {
10794
10912
  this.returnStatement(node, frame);
10795
10913
  return true;
10796
10914
  }
10797
- if (ts30.isForOfStatement(node)) {
10915
+ if (ts31.isForOfStatement(node)) {
10798
10916
  this.forOf(node, frame);
10799
10917
  return false;
10800
10918
  }
10801
- if (ts30.isSwitchStatement(node)) {
10919
+ if (ts31.isSwitchStatement(node)) {
10802
10920
  this.switch(node, frame);
10803
10921
  return false;
10804
10922
  }
10805
- if (ts30.isForStatement(node)) {
10923
+ if (ts31.isForStatement(node)) {
10806
10924
  this.forLoop(node, frame);
10807
10925
  return false;
10808
10926
  }
10809
- if ((ts30.isWhileStatement(node) || ts30.isDoStatement(node)) && frame.async && containsAwait2(node.statement)) {
10927
+ if ((ts31.isWhileStatement(node) || ts31.isDoStatement(node)) && frame.async && containsAwait2(node.statement)) {
10810
10928
  this.suspendingLoop(node, frame);
10811
10929
  return false;
10812
10930
  }
10813
- if (ts30.isWhileStatement(node)) {
10931
+ if (ts31.isWhileStatement(node)) {
10814
10932
  throw new SpecializeError(node, "Use a counted for loop or for…of; while loops have no bound to prove.");
10815
10933
  }
10816
- if (ts30.isTryStatement(node)) {
10934
+ if (ts31.isTryStatement(node)) {
10817
10935
  this.tryStatement(node, frame);
10818
10936
  return false;
10819
10937
  }
10820
- if (ts30.isBreakStatement(node) || ts30.isContinueStatement(node)) {
10938
+ if (ts31.isBreakStatement(node) || ts31.isContinueStatement(node)) {
10821
10939
  emitter.line(this.jumpText(node));
10822
10940
  return false;
10823
10941
  }
10824
- if (ts30.isLabeledStatement(node)) {
10942
+ if (ts31.isLabeledStatement(node)) {
10825
10943
  this.labelled(node, frame);
10826
10944
  return false;
10827
10945
  }
10828
- if (ts30.isEmptyStatement(node)) {
10946
+ if (ts31.isEmptyStatement(node)) {
10829
10947
  return false;
10830
10948
  }
10831
- if (ts30.isThrowStatement(node) && frame.async) {
10949
+ if (ts31.isThrowStatement(node) && frame.async) {
10832
10950
  const code = this.expressions.expression(node.expression, frame);
10833
10951
  emitter.line(mapped`throw ${this.dialect.code(code, undefined)};`);
10834
10952
  return true;
10835
10953
  }
10836
- throw new SpecializeError(node, `${ts30.SyntaxKind[node.kind]} is not supported in scan code.`);
10954
+ throw new SpecializeError(node, `${ts31.SyntaxKind[node.kind]} is not supported in scan code.`);
10837
10955
  }
10838
10956
  jumpText(node) {
10839
10957
  const label = node.label?.text;
@@ -10841,15 +10959,15 @@ class StatementSpecializer {
10841
10959
  if (label !== undefined) {
10842
10960
  return item.labels.includes(label);
10843
10961
  }
10844
- return item.kind === "loop" || ts30.isBreakStatement(node) && item.kind === "switch";
10962
+ return item.kind === "loop" || ts31.isBreakStatement(node) && item.kind === "switch";
10845
10963
  });
10846
- const emitted = ts30.isBreakStatement(node) ? scope?.breakLabel : scope?.continueLabel;
10964
+ const emitted = ts31.isBreakStatement(node) ? scope?.breakLabel : scope?.continueLabel;
10847
10965
  return emitted ? `break ${emitted};` : copied(node);
10848
10966
  }
10849
10967
  labelled(node, frame) {
10850
10968
  const labels = [];
10851
10969
  const inner = innermostLabelled(node, labels);
10852
- if (ts30.isIterationStatement(inner, false) || ts30.isSwitchStatement(inner)) {
10970
+ if (ts31.isIterationStatement(inner, false) || ts31.isSwitchStatement(inner)) {
10853
10971
  this.labels = labels;
10854
10972
  this.statement(inner, frame);
10855
10973
  this.labels = [];
@@ -10900,16 +11018,16 @@ class StatementSpecializer {
10900
11018
  frame.emitter.line("return;");
10901
11019
  return;
10902
11020
  }
10903
- if (ts30.isSatisfiesExpression(node.expression) && this.isNever(node.expression.type)) {
11021
+ if (ts31.isSatisfiesExpression(node.expression) && this.isNever(node.expression.type)) {
10904
11022
  frame.emitter.line(`return ${this.initializers.defaultOf(frame.returns)};`);
10905
11023
  return;
10906
11024
  }
10907
11025
  const value = this.expressions.expression(node.expression, frame, frame.returns);
10908
11026
  this.expressions.references.returned(value, node.expression, frame);
10909
- if (value.kind === "code" && (value.place && value.declared && value.declared.flags & ts30.TypeFlags.Object || value.copyOf)) {
11027
+ if (value.kind === "code" && (value.place && value.declared && value.declared.flags & ts31.TypeFlags.Object || value.copyOf)) {
10910
11028
  frame.returnsStored = true;
10911
11029
  }
10912
- const element = frame.returns && this.checker.getIndexTypeOfType(frame.returns, ts30.IndexKind.Number);
11030
+ const element = frame.returns && this.checker.getIndexTypeOfType(frame.returns, ts31.IndexKind.Number);
10913
11031
  if (element && value.kind === "virtual" && value.items) {
10914
11032
  frame.resultLayout = `FixedArray<${this.layouts.text(element, undefined)}, ${Math.max(value.items.length, 1)}>`;
10915
11033
  frame.resultLength = value.items.length;
@@ -10921,7 +11039,7 @@ class StatementSpecializer {
10921
11039
  }
10922
11040
  resultIec(frame) {
10923
11041
  const declaration = frame.emitter.origin;
10924
- const routine = ts30.findAncestor(declaration, ts30.isFunctionLike);
11042
+ const routine = ts31.findAncestor(declaration, ts31.isFunctionLike);
10925
11043
  return routine && "type" in routine && routine.type ? this.layouts.iecName(routine) : undefined;
10926
11044
  }
10927
11045
  tryStatement(node, frame) {
@@ -10932,7 +11050,7 @@ class StatementSpecializer {
10932
11050
  if (node.catchClause) {
10933
11051
  const binding = node.catchClause.variableDeclaration?.name;
10934
11052
  frame.emitter.reopen(`} catch${binding ? ` (${binding.getText()})` : ""} {`);
10935
- if (binding && ts30.isIdentifier(binding)) {
11053
+ if (binding && ts31.isIdentifier(binding)) {
10936
11054
  frame.env.set(this.checker.getSymbolAtLocation(binding), {
10937
11055
  kind: "code",
10938
11056
  text: binding.text,
@@ -10953,10 +11071,10 @@ class StatementSpecializer {
10953
11071
  frame.emitter.close();
10954
11072
  }
10955
11073
  inner(node, frame) {
10956
- return ts30.isBlock(node) ? this.statements(node.statements, frame) : this.statement(node, frame);
11074
+ return ts31.isBlock(node) ? this.statements(node.statements, frame) : this.statement(node, frame);
10957
11075
  }
10958
11076
  isNever(type) {
10959
- return type.kind === ts30.SyntaxKind.NeverKeyword;
11077
+ return type.kind === ts31.SyntaxKind.NeverKeyword;
10960
11078
  }
10961
11079
  declare(declaration, mutable, frame) {
10962
11080
  const initializer = declaration.initializer;
@@ -10986,7 +11104,7 @@ class StatementSpecializer {
10986
11104
  return;
10987
11105
  }
10988
11106
  const call = node.expression;
10989
- if (ts30.isCallExpression(call) && ts30.isPropertyAccessExpression(call.expression) && call.expression.name.text === "entries" && !call.arguments.length) {
11107
+ if (ts31.isCallExpression(call) && ts31.isPropertyAccessExpression(call.expression) && call.expression.name.text === "entries" && !call.arguments.length) {
10990
11108
  const array = this.expressions.expression(call.expression.expression, frame);
10991
11109
  if (array.kind === "code") {
10992
11110
  this.forEntries(node, array.text, frame);
@@ -11013,7 +11131,7 @@ class StatementSpecializer {
11013
11131
  if (iterable.kind !== "code") {
11014
11132
  throw new SpecializeError(node.expression, "for…of needs an array.");
11015
11133
  }
11016
- if (!ts30.isIdentifier(name)) {
11134
+ if (!ts31.isIdentifier(name)) {
11017
11135
  throw new SpecializeError(name, "Destructure a runtime element inside the loop.");
11018
11136
  }
11019
11137
  const local = frame.emitter.local(name.text);
@@ -11057,7 +11175,7 @@ class StatementSpecializer {
11057
11175
  throw new SpecializeError(at, "A generator runs in place, so it can't yield from itself.");
11058
11176
  }
11059
11177
  const body = declaration.body;
11060
- if (!body || !ts30.isBlock(body)) {
11178
+ if (!body || !ts31.isBlock(body)) {
11061
11179
  throw new SpecializeError(at, "A generator needs a body.");
11062
11180
  }
11063
11181
  const whole = frame.emitter.local("tsplcGenerator");
@@ -11082,7 +11200,7 @@ class StatementSpecializer {
11082
11200
  }
11083
11201
  }
11084
11202
  };
11085
- if (!ts30.isGetAccessorDeclaration(declaration)) {
11203
+ if (!ts31.isGetAccessorDeclaration(declaration)) {
11086
11204
  declaration.parameters.forEach((parameter, index) => {
11087
11205
  const given = generator.args[index] ?? constant(undefined);
11088
11206
  const value = given.kind === "const" && given.value === undefined && parameter.initializer ? this.expressions.expression(parameter.initializer, inner) : given;
@@ -11136,7 +11254,7 @@ class StatementSpecializer {
11136
11254
  }
11137
11255
  forEntries(node, array, frame) {
11138
11256
  const binding = onlyDeclaration(node.initializer)?.name;
11139
- const names = binding && ts30.isArrayBindingPattern(binding) ? binding.elements.map((element) => ts30.isBindingElement(element) && ts30.isIdentifier(element.name) ? element.name : undefined) : [];
11257
+ const names = binding && ts31.isArrayBindingPattern(binding) ? binding.elements.map((element) => ts31.isBindingElement(element) && ts31.isIdentifier(element.name) ? element.name : undefined) : [];
11140
11258
  const [indexName, itemName] = names;
11141
11259
  if (names.length !== 2 || !indexName || !itemName) {
11142
11260
  throw new SpecializeError(node.initializer, "Destructure [index, item] from array.entries().");
@@ -11159,13 +11277,13 @@ class StatementSpecializer {
11159
11277
  suspendingLoop(node, frame) {
11160
11278
  const labels = this.takeLabels();
11161
11279
  const test = () => this.dialect.condition(this.expressions.expression(node.expression, frame), node.expression);
11162
- if (ts30.isWhileStatement(node)) {
11280
+ if (ts31.isWhileStatement(node)) {
11163
11281
  frame.emitter.open(mapped`${labelText(labels)}while (${test()}) {`);
11164
11282
  } else {
11165
11283
  frame.emitter.open(`${labelText(labels)}do {`);
11166
11284
  }
11167
11285
  this.expressions.iterators.looping(undefined, () => this.scoped({ kind: "loop", labels }, () => this.inner(node.statement, frame)));
11168
- if (ts30.isWhileStatement(node)) {
11286
+ if (ts31.isWhileStatement(node)) {
11169
11287
  frame.emitter.close();
11170
11288
  return;
11171
11289
  }
@@ -11174,14 +11292,14 @@ class StatementSpecializer {
11174
11292
  forLoop(node, frame) {
11175
11293
  const { condition, incrementor, initializer } = node;
11176
11294
  const declaration = onlyDeclaration(initializer);
11177
- if (!declaration || !(declaration.parent.flags & ts30.NodeFlags.Let)) {
11295
+ if (!declaration || !(declaration.parent.flags & ts31.NodeFlags.Let)) {
11178
11296
  throw new SpecializeError(node, "Declare one let counter in the for header.");
11179
11297
  }
11180
11298
  const name = declaration.name;
11181
- if (!ts30.isIdentifier(name) || !declaration.initializer) {
11299
+ if (!ts31.isIdentifier(name) || !declaration.initializer) {
11182
11300
  throw new SpecializeError(declaration, "Initialize the loop counter.");
11183
11301
  }
11184
- if (!condition || !ts30.isBinaryExpression(condition) || !incrementor) {
11302
+ if (!condition || !ts31.isBinaryExpression(condition) || !incrementor) {
11185
11303
  throw new SpecializeError(node, "Compare the counter to a bound and step it in the for header.");
11186
11304
  }
11187
11305
  const declared = this.checker.getTypeAtLocation(name);
@@ -11207,10 +11325,10 @@ class StatementSpecializer {
11207
11325
  frame.emitter.close();
11208
11326
  }
11209
11327
  loopStep(incrementor, local, declared, frame) {
11210
- if (ts30.isPrefixUnaryExpression(incrementor) || ts30.isPostfixUnaryExpression(incrementor)) {
11211
- return `${local}${ts30.tokenToString(incrementor.operator)}`;
11328
+ if (ts31.isPrefixUnaryExpression(incrementor) || ts31.isPostfixUnaryExpression(incrementor)) {
11329
+ return `${local}${ts31.tokenToString(incrementor.operator)}`;
11212
11330
  }
11213
- if (ts30.isBinaryExpression(incrementor)) {
11331
+ if (ts31.isBinaryExpression(incrementor)) {
11214
11332
  return mapped`${local} ${incrementor.operatorToken.getText()} ${this.dialect.code(this.expressions.expression(incrementor.right, frame), declared)}`;
11215
11333
  }
11216
11334
  throw new SpecializeError(incrementor, "Use i++, i--, i += step or i -= step in the for header.");
@@ -11229,11 +11347,11 @@ class StatementSpecializer {
11229
11347
  }
11230
11348
  switchClauses(node, declared, frame) {
11231
11349
  for (const clause of node.caseBlock.clauses) {
11232
- if (ts30.isDefaultClause(clause)) {
11233
- const unreachable = clause.statements.some((statement) => ts30.isReturnStatement(statement) && statement.expression && ts30.isSatisfiesExpression(statement.expression) && this.isNever(statement.expression.type));
11350
+ if (ts31.isDefaultClause(clause)) {
11351
+ const unreachable = clause.statements.some((statement) => ts31.isReturnStatement(statement) && statement.expression && ts31.isSatisfiesExpression(statement.expression) && this.isNever(statement.expression.type));
11234
11352
  frame.emitter.open("default: {");
11235
11353
  if (unreachable) {
11236
- frame.emitter.line(frame.returns && !(frame.returns.flags & ts30.TypeFlags.Void) ? `return ${this.initializers.defaultOf(frame.returns)};` : "break;");
11354
+ frame.emitter.line(frame.returns && !(frame.returns.flags & ts31.TypeFlags.Void) ? `return ${this.initializers.defaultOf(frame.returns)};` : "break;");
11237
11355
  } else {
11238
11356
  for (const statement of clause.statements) {
11239
11357
  this.statement(statement, frame);
@@ -11251,7 +11369,7 @@ class StatementSpecializer {
11251
11369
  }
11252
11370
  }
11253
11371
  constantSwitch(node, subject, labels, frame) {
11254
- const nested = node.caseBlock.clauses.some((clause) => clause.statements.some((statement) => !ts30.isBreakStatement(statement) && containsJump(statement)));
11372
+ const nested = node.caseBlock.clauses.some((clause) => clause.statements.some((statement) => !ts31.isBreakStatement(statement) && containsJump(statement)));
11255
11373
  const label = nested ? frame.emitter.local("tsplcSwitch") : undefined;
11256
11374
  if (label) {
11257
11375
  frame.emitter.open(`${label}: {`);
@@ -11264,7 +11382,7 @@ class StatementSpecializer {
11264
11382
  matchedClauses(node, subject, frame) {
11265
11383
  const clauses = node.caseBlock.clauses;
11266
11384
  const start = clauses.findIndex((clause) => {
11267
- if (ts30.isDefaultClause(clause)) {
11385
+ if (ts31.isDefaultClause(clause)) {
11268
11386
  return true;
11269
11387
  }
11270
11388
  const label = this.expressions.expression(clause.expression, frame);
@@ -11275,25 +11393,25 @@ class StatementSpecializer {
11275
11393
  }
11276
11394
  for (const clause of clauses.slice(start)) {
11277
11395
  for (const statement of clause.statements) {
11278
- if (ts30.isBreakStatement(statement)) {
11396
+ if (ts31.isBreakStatement(statement)) {
11279
11397
  return;
11280
11398
  }
11281
11399
  this.statement(statement, frame);
11282
11400
  }
11283
- if (clause.statements.some((statement) => ts30.isReturnStatement(statement))) {
11401
+ if (clause.statements.some((statement) => ts31.isReturnStatement(statement))) {
11284
11402
  return;
11285
11403
  }
11286
11404
  }
11287
11405
  }
11288
11406
  effect(node, frame) {
11289
- if (ts30.isVoidExpression(node)) {
11407
+ if (ts31.isVoidExpression(node)) {
11290
11408
  const value = this.expressions.expression(node.expression, frame);
11291
11409
  if (value.kind === "code") {
11292
11410
  frame.emitter.line(mapped`void ${value.text};`);
11293
11411
  }
11294
11412
  return;
11295
11413
  }
11296
- if (ts30.isBinaryExpression(node) && isAssignment(node.operatorToken.kind)) {
11414
+ if (ts31.isBinaryExpression(node) && isAssignment(node.operatorToken.kind)) {
11297
11415
  this.expressions.assignments.assign(node, frame);
11298
11416
  return;
11299
11417
  }
@@ -11308,7 +11426,7 @@ class StatementSpecializer {
11308
11426
  }
11309
11427
  }
11310
11428
  var onlyDeclaration = (initializer) => {
11311
- if (!initializer || !ts30.isVariableDeclarationList(initializer)) {
11429
+ if (!initializer || !ts31.isVariableDeclarationList(initializer)) {
11312
11430
  return;
11313
11431
  }
11314
11432
  const [declaration, ...others] = initializer.declarations;
@@ -11317,13 +11435,14 @@ var onlyDeclaration = (initializer) => {
11317
11435
  var labelText = (labels) => labels.map((label) => `${label}: `).join("");
11318
11436
  var innermostLabelled = (node, labels) => {
11319
11437
  labels.push(node.label.text);
11320
- return ts30.isLabeledStatement(node.statement) ? innermostLabelled(node.statement, labels) : node.statement;
11438
+ return ts31.isLabeledStatement(node.statement) ? innermostLabelled(node.statement, labels) : node.statement;
11321
11439
  };
11322
- var containsJump = (node) => ts30.isBreakStatement(node) || ts30.isContinueStatement(node) || !ts30.isFunctionLike(node) && (ts30.forEachChild(node, containsJump) ?? false);
11323
- var containsAwait2 = (node) => ts30.isAwaitExpression(node) || !ts30.isFunctionLike(node) && (ts30.forEachChild(node, containsAwait2) ?? false);
11440
+ var containsJump = (node) => ts31.isBreakStatement(node) || ts31.isContinueStatement(node) || !ts31.isFunctionLike(node) && (ts31.forEachChild(node, containsJump) ?? false);
11441
+ var containsAwait2 = (node) => ts31.isAwaitExpression(node) || !ts31.isFunctionLike(node) && (ts31.forEachChild(node, containsAwait2) ?? false);
11324
11442
 
11325
11443
  // packages/compiler/src/frontend/elaborate/storage.ts
11326
- import ts31 from "typescript";
11444
+ import { basename as basename2 } from "node:path";
11445
+ import ts32 from "typescript";
11327
11446
  class Storage {
11328
11447
  model;
11329
11448
  checker;
@@ -11343,7 +11462,7 @@ class Storage {
11343
11462
  this.kept = kept;
11344
11463
  this.rootModule = rootModule;
11345
11464
  this.writes = new ScanWrites(checker, sources);
11346
- this.typeNames = new Set(sources.flatMap((source) => source.statements.flatMap((statement) => (ts31.isInterfaceDeclaration(statement) || ts31.isTypeAliasDeclaration(statement) || ts31.isClassDeclaration(statement) || ts31.isEnumDeclaration(statement)) && statement.name ? [statement.name.text] : [])));
11465
+ this.typeNames = new Set(sources.flatMap((source) => source.statements.flatMap((statement) => (ts32.isInterfaceDeclaration(statement) || ts32.isTypeAliasDeclaration(statement) || ts32.isClassDeclaration(statement) || ts32.isEnumDeclaration(statement)) && statement.name ? [statement.name.text] : [])));
11347
11466
  }
11348
11467
  typeNames;
11349
11468
  fieldSymbol(holder, name) {
@@ -11376,8 +11495,41 @@ class Storage {
11376
11495
  const type = holder.captured.kind === "instance" ? this.model.capturedFieldType(holder, name) : undefined;
11377
11496
  const found = type !== undefined && referenceType(type) && this.written(holder, name);
11378
11497
  this.referenceFields.set(key, found);
11498
+ if (found) {
11499
+ this.references.push({ holder, name });
11500
+ }
11379
11501
  return found;
11380
11502
  }
11503
+ references = [];
11504
+ referenceTable() {
11505
+ if (!this.references.length) {
11506
+ return { references: [], referenceFields: [] };
11507
+ }
11508
+ return {
11509
+ references: this.model.nodes.flatMap((node) => {
11510
+ const path = referable(node) ? this.storagePlace(node) : undefined;
11511
+ return path === undefined ? [] : [{ id: node.reference, path }];
11512
+ }),
11513
+ referenceFields: this.references.flatMap(({ holder, name }) => {
11514
+ const path = this.storagePlace(holder);
11515
+ return path === undefined ? [] : [`${path}.${name}`];
11516
+ })
11517
+ };
11518
+ }
11519
+ storagePlace(node) {
11520
+ const owner = node.owner;
11521
+ if (!owner) {
11522
+ return;
11523
+ }
11524
+ const root = this.flattened(owner.root) ? owner.root.name : `${owner.root.name}.${owner.root.name}`;
11525
+ return root + owner.steps.map((step, index) => {
11526
+ const holder = this.model.at(owner.root, owner.steps.slice(0, index));
11527
+ if (step.kind === "index") {
11528
+ return holder && this.mixedStates(holder) ? `.${mixedItem(step.index)}` : `[${step.index}]`;
11529
+ }
11530
+ return /^\d+$/.test(step.name) ? `[${step.name}]` : `.${step.name}`;
11531
+ }).join("");
11532
+ }
11381
11533
  referenceFields = new Map;
11382
11534
  storedArray(array) {
11383
11535
  const owner = array.owner;
@@ -11427,7 +11579,7 @@ class Storage {
11427
11579
  return node?.captured.kind === "object" || node?.captured.kind === "instance";
11428
11580
  }
11429
11581
  namespace(root) {
11430
- const pascal = pascalCase(root.name);
11582
+ const pascal = pascalCase(basename2(this.rootModule(root), ".ts"));
11431
11583
  const name = this.typeNames.has(pascal) ? `${pascal}Root` : pascal;
11432
11584
  this.imports.namespaces.set(name, this.rootModule(root));
11433
11585
  return name;
@@ -11589,7 +11741,7 @@ class Storage {
11589
11741
  }
11590
11742
  return { kind: "static", node };
11591
11743
  }
11592
- if (this.kept(root.file) || ts31.getCombinedNodeFlags(root.declaration) & ts31.NodeFlags.Const) {
11744
+ if (this.kept(root.file) || ts32.getCombinedNodeFlags(root.declaration) & ts32.NodeFlags.Const) {
11593
11745
  return primitive2(value);
11594
11746
  }
11595
11747
  const namespace = this.namespace(root);
@@ -11609,7 +11761,7 @@ class Storage {
11609
11761
  kind: "code",
11610
11762
  text: root.name,
11611
11763
  declared: this.checker.getTypeAtLocation(root.declaration.name),
11612
- place: !(ts31.getCombinedNodeFlags(root.declaration) & ts31.NodeFlags.Const)
11764
+ place: !(ts32.getCombinedNodeFlags(root.declaration) & ts32.NodeFlags.Const)
11613
11765
  };
11614
11766
  }
11615
11767
  fromCaptured(value, holder, step) {
@@ -11822,7 +11974,7 @@ class Specializer {
11822
11974
  specializeRoutine(declaration, self, args, closure) {
11823
11975
  const signature = this.checker.getSignatureFromDeclaration(declaration);
11824
11976
  const returnType = signature && this.checker.getReturnTypeOfSignature(signature);
11825
- const isAsync = Boolean(ts32.canHaveModifiers(declaration) && ts32.getModifiers(declaration)?.some((modifier) => modifier.kind === ts32.SyntaxKind.AsyncKeyword));
11977
+ const isAsync = Boolean(ts33.canHaveModifiers(declaration) && ts33.getModifiers(declaration)?.some((modifier) => modifier.kind === ts33.SyntaxKind.AsyncKeyword));
11826
11978
  const frame = {
11827
11979
  emitter: new Emitter(declaration),
11828
11980
  env: new Map(closure),
@@ -11836,7 +11988,7 @@ class Specializer {
11836
11988
  const parameters = [];
11837
11989
  const runtimeArgs = [];
11838
11990
  const keys = [];
11839
- const parameterList = ts32.isGetAccessorDeclaration(declaration) ? [] : declaration.parameters;
11991
+ const parameterList = ts33.isGetAccessorDeclaration(declaration) ? [] : declaration.parameters;
11840
11992
  parameterList.forEach((parameter, index) => {
11841
11993
  const declared = this.checker.getTypeAtLocation(parameter);
11842
11994
  if (parameter.dotDotDotToken) {
@@ -11894,13 +12046,13 @@ class Specializer {
11894
12046
  referents: this.resultReferents(known)
11895
12047
  };
11896
12048
  }
11897
- const name = this.routineName(declaration, self);
12049
+ const name = this.routineName(declaration, self, keys);
11898
12050
  this.specialized.set(key, name);
11899
- if (ts32.isArrowFunction(declaration) && !ts32.isBlock(declaration.body)) {
12051
+ if (ts33.isArrowFunction(declaration) && !ts33.isBlock(declaration.body)) {
11900
12052
  frame.emitter.origin = declaration.body;
11901
12053
  const result = this.expressions.expression(declaration.body, frame, frame.returns);
11902
12054
  this.expressions.references.returned(result, declaration.body, frame);
11903
- if (!frame.returns || frame.returns.flags & ts32.TypeFlags.Void) {
12055
+ if (!frame.returns || frame.returns.flags & ts33.TypeFlags.Void) {
11904
12056
  if (result.kind === "code") {
11905
12057
  frame.emitter.line(mapped`${result.text};`);
11906
12058
  }
@@ -11910,13 +12062,13 @@ class Specializer {
11910
12062
  } else {
11911
12063
  this.statements.body(declaration.body, frame);
11912
12064
  }
11913
- const resultText = frame.returns && !(frame.returns.flags & ts32.TypeFlags.Void) ? frame.resultLayout ?? this.layouts.iecName(declaration) ?? (frame.referents ? referenceLayout : this.layouts.text(frame.returns)) : "void";
12065
+ const resultText = frame.returns && !(frame.returns.flags & ts33.TypeFlags.Void) ? frame.resultLayout ?? this.layouts.iecName(declaration) ?? (frame.referents ? referenceLayout : this.layouts.text(frame.returns)) : "void";
11914
12066
  if (frame.referents) {
11915
12067
  this.referents.set(name, frame.referents);
11916
12068
  }
11917
12069
  const head = `${frame.async ? "async " : ""}function ${name}(${parameters.join(", ")}): ${frame.async ? `Promise<${resultText}>` : resultText} {`;
11918
12070
  const instance = self?.owner && tsPath(self.owner);
11919
- if (self?.captured.kind === "instance" && (ts32.isMethodDeclaration(declaration) || ts32.isGetAccessorDeclaration(declaration))) {
12071
+ if (self?.captured.kind === "instance" && (ts33.isMethodDeclaration(declaration) || ts33.isGetAccessorDeclaration(declaration))) {
11920
12072
  this.origins.set(name, {
11921
12073
  name: `${self.captured.name}.${declaration.name.getText()}`,
11922
12074
  ...instance && { instance }
@@ -11955,17 +12107,21 @@ class Specializer {
11955
12107
  optional: referents.optional
11956
12108
  };
11957
12109
  }
11958
- routineName(declaration, self) {
11959
- const own = declaration.name && ts32.isIdentifier(declaration.name) ? declaration.name.text : undefined;
11960
- const variable = !own && declaration.parent && ts32.isVariableDeclaration(declaration.parent) && ts32.isIdentifier(declaration.parent.name) ? declaration.parent.name.text : undefined;
12110
+ routineName(declaration, self, keys) {
12111
+ const own = declaration.name && ts33.isIdentifier(declaration.name) ? declaration.name.text : undefined;
12112
+ const variable = !own && declaration.parent && ts33.isVariableDeclaration(declaration.parent) && ts33.isIdentifier(declaration.parent.name) ? declaration.parent.name.text : undefined;
11961
12113
  const owner = self?.captured.kind === "instance" ? self.captured.name : undefined;
11962
- const base = [owner, own ?? variable ?? "callback"].filter(Boolean).join("_");
12114
+ const named = [owner, own ?? variable ?? "callback"].filter(Boolean).join("_");
12115
+ const instance = self && this.model.identity(self);
12116
+ const specialized = Boolean(instance) || keys.length > 0;
12117
+ const stable = keys.map((key) => key.replace(/fn:[^,|\]}]*/g, "fn"));
12118
+ const base = specialized ? `${named}_${identityDigest5([instance ?? "", ...stable].join("\x00"))}` : named;
11963
12119
  const name = unusedName(base, (candidate) => this.routineNames.has(candidate));
11964
12120
  this.routineNames.add(name);
11965
12121
  return name;
11966
12122
  }
11967
12123
  bindParameter(name, arg, declared, frame, parameters, runtimeArgs, keys) {
11968
- if (ts32.isObjectBindingPattern(name)) {
12124
+ if (ts33.isObjectBindingPattern(name)) {
11969
12125
  for (const element of name.elements) {
11970
12126
  const field = (element.propertyName ?? element.name).getText();
11971
12127
  const inner = this.expressions.member(arg, field, element, frame);
@@ -11973,9 +12129,9 @@ class Specializer {
11973
12129
  }
11974
12130
  return;
11975
12131
  }
11976
- if (ts32.isArrayBindingPattern(name)) {
12132
+ if (ts33.isArrayBindingPattern(name)) {
11977
12133
  name.elements.forEach((element, index) => {
11978
- if (ts32.isOmittedExpression(element)) {
12134
+ if (ts33.isOmittedExpression(element)) {
11979
12135
  return;
11980
12136
  }
11981
12137
  if (element.dotDotDotToken) {
@@ -11989,7 +12145,7 @@ class Specializer {
11989
12145
  if (arg.kind === "code" || arg.kind === "virtual" && !this.isKnownShape(arg)) {
11990
12146
  const local = frame.emitter.local(name.text);
11991
12147
  const iec = this.layouts.iecName(name.parent) ?? (arg.kind === "code" ? arg.iec : undefined);
11992
- const element = this.checker.getIndexTypeOfType(declared, ts32.IndexKind.Number);
12148
+ const element = this.checker.getIndexTypeOfType(declared, ts33.IndexKind.Number);
11993
12149
  const layout = arg.kind === "code" ? arg.layout : arg.items && element ? `FixedArray<${this.layouts.text(element)}, ${Math.max(arg.items.length, 1)}>` : undefined;
11994
12150
  parameters.push(`${local}: ${iec ?? layout ?? this.layouts.text(declared)}`);
11995
12151
  runtimeArgs.push(this.dialect.assignmentText(arg, declared, iec));
@@ -12004,7 +12160,7 @@ class Specializer {
12004
12160
  keys.push(`${name.text}=code${layout ? `:${layout}` : ""}`);
12005
12161
  return;
12006
12162
  }
12007
- if (arg.kind === "const" && !(declared.flags & ts32.TypeFlags.Undefined) && typeof arg.value !== "undefined") {
12163
+ if (arg.kind === "const" && !(declared.flags & ts33.TypeFlags.Undefined) && typeof arg.value !== "undefined") {
12008
12164
  const local = frame.emitter.local(name.text);
12009
12165
  parameters.push(`${local}: ${this.layouts.text(declared)}`);
12010
12166
  runtimeArgs.push(this.dialect.code(arg, declared));
@@ -12087,7 +12243,7 @@ class Specializer {
12087
12243
  if (arg.kind === "const") {
12088
12244
  return arg.value === undefined;
12089
12245
  }
12090
- if (arg.kind === "code" && arg.declared && arg.declared.flags & ts32.TypeFlags.Union) {
12246
+ if (arg.kind === "code" && arg.declared && arg.declared.flags & ts33.TypeFlags.Union) {
12091
12247
  if (this.checker.getNonNullableType(arg.declared) !== arg.declared) {
12092
12248
  throw new SpecializeError(parameter, "Pass a defined value or leave the argument out: the default applies to a missing argument.");
12093
12249
  }
@@ -12104,10 +12260,10 @@ class Specializer {
12104
12260
  this.bindParameter(parameter.name, value, declared, frame, parameters, runtimeArgs, keys);
12105
12261
  }
12106
12262
  bindRest(parameter, args, declared, frame, parameters, runtimeArgs, keys) {
12107
- if (!ts32.isIdentifier(parameter.name)) {
12263
+ if (!ts33.isIdentifier(parameter.name)) {
12108
12264
  throw new SpecializeError(parameter.name, "Name the rest parameter; destructure it in the body.");
12109
12265
  }
12110
- const element = this.checker.getIndexTypeOfType(declared, ts32.IndexKind.Number) ?? this.checker.getAnyType();
12266
+ const element = this.checker.getIndexTypeOfType(declared, ts33.IndexKind.Number) ?? this.checker.getAnyType();
12111
12267
  const name = parameter.name.text;
12112
12268
  const items = args.map((arg, index) => {
12113
12269
  if (arg.kind !== "code" && arg.kind !== "const") {
@@ -12134,12 +12290,12 @@ class Specializer {
12134
12290
  return inner.some((item) => item.kind === "static" || item.kind === "function" || item.kind === "choice" || this.isKnownShape(item)) || value.items !== undefined && inner.every((item) => item.kind === "const");
12135
12291
  }
12136
12292
  }
12137
- var closingBrace = (declaration) => declaration.body && ts32.isBlock(declaration.body) ? declaration.body.getLastToken() : declaration;
12293
+ var closingBrace = (declaration) => declaration.body && ts33.isBlock(declaration.body) ? declaration.body.getLastToken() : declaration;
12138
12294
  var declarationKey = (declaration) => `${declaration.getSourceFile().fileName}:${declaration.pos}`;
12139
12295
  var valueKey = (value) => {
12140
12296
  switch (value.kind) {
12141
12297
  case "static":
12142
- return `#${value.node.id}`;
12298
+ return `#${value.node.reference}`;
12143
12299
  case "const":
12144
12300
  return `=${String(value.value)}`;
12145
12301
  case "function":
@@ -12149,7 +12305,7 @@ var valueKey = (value) => {
12149
12305
  case "code":
12150
12306
  return "code";
12151
12307
  case "choice":
12152
- return `ref(${value.options.map((option) => option.id).join(",")})${value.optional ? "?" : ""}`;
12308
+ return `ref(${value.options.map((option) => option.reference).join(",")})${value.optional ? "?" : ""}`;
12153
12309
  case "masked":
12154
12310
  return `some[${value.entries.map((entry) => `${valueKey(entry.item)}:${valueKey(entry.present)}`).join(",")}]${value.order ? `by ${valueKey(value.order)}` : ""}`;
12155
12311
  case "counted":
@@ -12159,13 +12315,13 @@ var valueKey = (value) => {
12159
12315
  var readSymbols = (declaration, checker) => {
12160
12316
  const read = new Set;
12161
12317
  const visit = (node) => {
12162
- if (ts32.isIdentifier(node)) {
12318
+ if (ts33.isIdentifier(node)) {
12163
12319
  const symbol = checker.getSymbolAtLocation(node);
12164
12320
  if (symbol) {
12165
12321
  read.add(symbol);
12166
12322
  }
12167
12323
  }
12168
- ts32.forEachChild(node, visit);
12324
+ ts33.forEachChild(node, visit);
12169
12325
  };
12170
12326
  visit(declaration);
12171
12327
  return read;
@@ -12173,42 +12329,42 @@ var readSymbols = (declaration, checker) => {
12173
12329
 
12174
12330
  // packages/compiler/src/frontend/elaborate/index.ts
12175
12331
  var keptModule = (source, checker, sdk) => source.statements.every((statement) => {
12176
- if (ts33.isImportDeclaration(statement) || ts33.isExportDeclaration(statement) || ts33.isInterfaceDeclaration(statement) || ts33.isTypeAliasDeclaration(statement) || ts33.isEnumDeclaration(statement)) {
12332
+ if (ts34.isImportDeclaration(statement) || ts34.isExportDeclaration(statement) || ts34.isInterfaceDeclaration(statement) || ts34.isTypeAliasDeclaration(statement) || ts34.isEnumDeclaration(statement)) {
12177
12333
  return true;
12178
12334
  }
12179
- if (!ts33.isVariableStatement(statement)) {
12335
+ if (!ts34.isVariableStatement(statement)) {
12180
12336
  return false;
12181
12337
  }
12182
12338
  return statement.declarationList.declarations.every((declaration) => declaration.initializer && constantInitializer(declaration.initializer, checker, sdk));
12183
12339
  });
12184
12340
  var constantInitializer = (node, checker, sdk) => {
12185
- if (ts33.isNumericLiteral(node) || ts33.isStringLiteral(node) || ts33.isNoSubstitutionTemplateLiteral(node) || ts33.isBigIntLiteral(node) || node.kind === ts33.SyntaxKind.TrueKeyword || node.kind === ts33.SyntaxKind.FalseKeyword) {
12341
+ if (ts34.isNumericLiteral(node) || ts34.isStringLiteral(node) || ts34.isNoSubstitutionTemplateLiteral(node) || ts34.isBigIntLiteral(node) || node.kind === ts34.SyntaxKind.TrueKeyword || node.kind === ts34.SyntaxKind.FalseKeyword) {
12186
12342
  return true;
12187
12343
  }
12188
- if (ts33.isPrefixUnaryExpression(node)) {
12344
+ if (ts34.isPrefixUnaryExpression(node)) {
12189
12345
  return constantInitializer(node.operand, checker, sdk);
12190
12346
  }
12191
- if (ts33.isAsExpression(node) || ts33.isSatisfiesExpression(node) || ts33.isParenthesizedExpression(node)) {
12347
+ if (ts34.isAsExpression(node) || ts34.isSatisfiesExpression(node) || ts34.isParenthesizedExpression(node)) {
12192
12348
  return constantInitializer(node.expression, checker, sdk);
12193
12349
  }
12194
- if (ts33.isPropertyAccessExpression(node)) {
12195
- return ts33.isIdentifier(node.expression);
12350
+ if (ts34.isPropertyAccessExpression(node)) {
12351
+ return ts34.isIdentifier(node.expression);
12196
12352
  }
12197
- if (ts33.isIdentifier(node)) {
12353
+ if (ts34.isIdentifier(node)) {
12198
12354
  return true;
12199
12355
  }
12200
- if (ts33.isObjectLiteralExpression(node)) {
12201
- return node.properties.every((property) => ts33.isPropertyAssignment(property) && constantInitializer(property.initializer, checker, sdk) || ts33.isShorthandPropertyAssignment(property));
12356
+ if (ts34.isObjectLiteralExpression(node)) {
12357
+ return node.properties.every((property) => ts34.isPropertyAssignment(property) && constantInitializer(property.initializer, checker, sdk) || ts34.isShorthandPropertyAssignment(property));
12202
12358
  }
12203
- if (ts33.isArrayLiteralExpression(node)) {
12359
+ if (ts34.isArrayLiteralExpression(node)) {
12204
12360
  return node.elements.every((element) => constantInitializer(element, checker, sdk));
12205
12361
  }
12206
- if (ts33.isCallExpression(node)) {
12362
+ if (ts34.isCallExpression(node)) {
12207
12363
  return namesSdk(checker, sdk, node.expression, "createServiceClient");
12208
12364
  }
12209
12365
  return false;
12210
12366
  };
12211
- var needsElaboration = (sources, kept, checker, sdk) => sources.some((source) => !kept(source.fileName) && source.statements.some((statement) => ts33.isClassDeclaration(statement) && !statement.heritageClauses?.some((clause) => clause.types.some((type) => namesSdk(checker, sdk, type.expression, "FunctionBlock")))));
12367
+ var needsElaboration = (sources, kept, checker, sdk) => sources.some((source) => !kept(source.fileName) && source.statements.some((statement) => ts34.isClassDeclaration(statement) && !statement.heritageClauses?.some((clause) => clause.types.some((type) => namesSdk(checker, sdk, type.expression, "FunctionBlock")))));
12212
12368
  var constant2 = (value, iec) => {
12213
12369
  switch (value.kind) {
12214
12370
  case "number":
@@ -12238,7 +12394,16 @@ var lowerElaboration = (program, sdk, entries, root, positions, debug) => {
12238
12394
  const origins = new Map;
12239
12395
  const folded = [];
12240
12396
  const literals = new Map;
12241
- const result = { sources, diagnostics, origins, folded, literals };
12397
+ const references = [];
12398
+ const referenceFields = [];
12399
+ const result = {
12400
+ sources,
12401
+ diagnostics,
12402
+ origins,
12403
+ folded,
12404
+ literals,
12405
+ references: { objects: references, fields: referenceFields }
12406
+ };
12242
12407
  const runtime = runtimeSources(program).filter((source) => !source.isDeclarationFile && !inSdk(sdk, source.fileName));
12243
12408
  const checker = program.getTypeChecker();
12244
12409
  const kept = new Set(runtime.filter((source) => keptModule(source, checker, sdk)).map((source) => source.fileName));
@@ -12258,13 +12423,13 @@ var lowerElaboration = (program, sdk, entries, root, positions, debug) => {
12258
12423
  return result;
12259
12424
  }
12260
12425
  const directory = join2(dirname5(entryFile), generatedDirectory).replace(/\\/g, "/");
12261
- const rootModule = (item) => `${directory}/${item.name}.ts`;
12262
12426
  let recorded = () => [];
12263
12427
  try {
12264
12428
  const declarations = retainedDeclarations(runtime, checker, sdk);
12265
12429
  const graph = captureGraph(entryFile, runtime, checker);
12266
12430
  const generics = new GenericTypes(checker);
12267
- const model = new Model(graph, generics.checker, program, entryFile);
12431
+ const model = new Model(graph, generics.checker, program, entryFile, root);
12432
+ const rootModule = rootModules(model.roots, directory, root);
12268
12433
  const specializer = new Specializer(model, generics, sdk, runtime, isKept, rootModule);
12269
12434
  recorded = () => specializer.failures;
12270
12435
  const main = findEntry(entrySource, entry.export);
@@ -12333,6 +12498,9 @@ var lowerElaboration = (program, sdk, entries, root, positions, debug) => {
12333
12498
  for (const { name, members } of specializer.layouts.literalEnums) {
12334
12499
  literals.set(`${typesFile}:${name}`, members);
12335
12500
  }
12501
+ const table = specializer.storage.referenceTable();
12502
+ references.push(...table.references);
12503
+ referenceFields.push(...table.referenceFields);
12336
12504
  for (const item of specializer.storage.folded()) {
12337
12505
  const known = constant2(item.value, item.iec);
12338
12506
  if (known) {
@@ -12405,7 +12573,7 @@ var storageGlobals = (specializer, retention, item) => {
12405
12573
  ] : lines;
12406
12574
  };
12407
12575
  var typesOnly = (source) => joined([
12408
- ...source.statements.filter((statement) => ts33.isInterfaceDeclaration(statement) || ts33.isTypeAliasDeclaration(statement) || ts33.isImportDeclaration(statement) && statement.importClause?.isTypeOnly).map(copied),
12576
+ ...source.statements.filter((statement) => ts34.isInterfaceDeclaration(statement) || ts34.isTypeAliasDeclaration(statement) || ts34.isImportDeclaration(statement) && statement.importClause?.isTypeOnly).map(copied),
12409
12577
  "export {};"
12410
12578
  ], `
12411
12579
  `);
@@ -12420,12 +12588,12 @@ var failure = (cause, positions, debug) => {
12420
12588
  };
12421
12589
  var findEntry = (source, name) => {
12422
12590
  for (const statement of source.statements) {
12423
- if (ts33.isFunctionDeclaration(statement) && statement.name?.text === name && statement.body) {
12591
+ if (ts34.isFunctionDeclaration(statement) && statement.name?.text === name && statement.body) {
12424
12592
  return statement;
12425
12593
  }
12426
- if (ts33.isVariableStatement(statement)) {
12594
+ if (ts34.isVariableStatement(statement)) {
12427
12595
  for (const declaration of statement.declarationList.declarations) {
12428
- if (ts33.isIdentifier(declaration.name) && declaration.name.text === name && declaration.initializer && ts33.isArrowFunction(declaration.initializer)) {
12596
+ if (ts34.isIdentifier(declaration.name) && declaration.name.text === name && declaration.initializer && ts34.isArrowFunction(declaration.initializer)) {
12429
12597
  return declaration.initializer;
12430
12598
  }
12431
12599
  }
@@ -12433,12 +12601,25 @@ var findEntry = (source, name) => {
12433
12601
  }
12434
12602
  throw new Error(`${source.fileName} exports no function ${name}.`);
12435
12603
  };
12604
+ var rootModules = (roots, directory, projectRoot) => {
12605
+ const counts = new Map;
12606
+ for (const item of roots) {
12607
+ const key = item.name.toLowerCase();
12608
+ counts.set(key, (counts.get(key) ?? 0) + 1);
12609
+ }
12610
+ return (item) => {
12611
+ const shared = (counts.get(item.name.toLowerCase()) ?? 0) > 1;
12612
+ const module = relative6(projectRoot, item.file).replace(/\\/g, "/");
12613
+ const name = shared ? `${item.name}_${identityDigest6(module)}` : item.name;
12614
+ return `${directory}/${name}.ts`;
12615
+ };
12616
+ };
12436
12617
 
12437
12618
  // packages/compiler/src/frontend/exposure.ts
12438
12619
  import { createHash } from "node:crypto";
12439
12620
  import { error as error7 } from "@tsplc/compiler/ir";
12440
12621
  import { elementaryType as elementaryType2, isIntegerValued } from "@tsplc/iec";
12441
- import ts34 from "typescript";
12622
+ import ts35 from "typescript";
12442
12623
  var telemetryType = (annotation) => {
12443
12624
  const type = elementaryType2(annotation);
12444
12625
  return type?.family === "bool" || isIntegerValued(type) && type.bits <= 32 || /^STRING<\d+>$/.test(annotation);
@@ -12456,21 +12637,21 @@ var lowerExposure = (program, sdk, positions) => {
12456
12637
  const edits = [];
12457
12638
  const extra = [];
12458
12639
  const visit = (node) => {
12459
- if (!ts34.isCallExpression(node) || !namesSdk(checker, sdk, node.expression, "expose")) {
12460
- ts34.forEachChild(node, visit);
12640
+ if (!ts35.isCallExpression(node) || !namesSdk(checker, sdk, node.expression, "expose")) {
12641
+ ts35.forEachChild(node, visit);
12461
12642
  return;
12462
12643
  }
12463
12644
  const fail = (message) => diagnostics.push(error7("PLC1014", message, positions.node(node)));
12464
12645
  const [label, values] = node.arguments;
12465
- if (!label || !ts34.isStringLiteral(label) || !/^[A-Za-z_][A-Za-z0-9_]*$/.test(label.text) || label.text === "__proto__" || !values || !ts34.isObjectLiteralExpression(values) || !ts34.isExpressionStatement(node.parent)) {
12646
+ if (!label || !ts35.isStringLiteral(label) || !/^[A-Za-z_][A-Za-z0-9_]*$/.test(label.text) || label.text === "__proto__" || !values || !ts35.isObjectLiteralExpression(values) || !ts35.isExpressionStatement(node.parent)) {
12466
12647
  fail("expose requires a literal machine name and a flat telemetry object in a synchronous cyclic routine.");
12467
12648
  return;
12468
12649
  }
12469
12650
  let owner = node.parent;
12470
- while (owner && !ts34.isFunctionLike(owner)) {
12651
+ while (owner && !ts35.isFunctionLike(owner)) {
12471
12652
  owner = owner.parent;
12472
12653
  }
12473
- if (!owner || ts34.canHaveModifiers(owner) && ts34.getModifiers(owner)?.some((value) => value.kind === ts34.SyntaxKind.AsyncKeyword)) {
12654
+ if (!owner || ts35.canHaveModifiers(owner) && ts35.getModifiers(owner)?.some((value) => value.kind === ts35.SyntaxKind.AsyncKeyword)) {
12474
12655
  fail("Sample telemetry from a synchronous cyclic routine, outside async continuations.");
12475
12656
  return;
12476
12657
  }
@@ -12481,18 +12662,18 @@ var lowerExposure = (program, sdk, positions) => {
12481
12662
  names.add(label.text);
12482
12663
  const fields = [];
12483
12664
  for (const property of values.properties) {
12484
- if (!ts34.isPropertyAssignment(property) || !ts34.isIdentifier(property.name) || ["contractVersion", "__proto__"].includes(property.name.text)) {
12665
+ if (!ts35.isPropertyAssignment(property) || !ts35.isIdentifier(property.name) || ["contractVersion", "__proto__"].includes(property.name.text)) {
12485
12666
  fail("Telemetry uses named scalar fields; contractVersion and __proto__ are reserved.");
12486
12667
  return;
12487
12668
  }
12488
12669
  const value = property.initializer;
12489
12670
  const type = checker.getTypeAtLocation(value);
12490
12671
  let annotation;
12491
- if (type.flags & ts34.TypeFlags.BooleanLike) {
12672
+ if (type.flags & ts35.TypeFlags.BooleanLike) {
12492
12673
  annotation = "BOOL";
12493
12674
  }
12494
- const declaration = symbolAt(checker, ts34.isPropertyAccessExpression(value) ? value.name : value)?.valueDeclaration;
12495
- if (declaration && (ts34.isPropertySignature(declaration) || ts34.isPropertyDeclaration(declaration) || ts34.isVariableDeclaration(declaration) || ts34.isParameter(declaration)) && declaration.type) {
12675
+ const declaration = symbolAt(checker, ts35.isPropertyAccessExpression(value) ? value.name : value)?.valueDeclaration;
12676
+ if (declaration && (ts35.isPropertySignature(declaration) || ts35.isPropertyDeclaration(declaration) || ts35.isVariableDeclaration(declaration) || ts35.isParameter(declaration)) && declaration.type) {
12496
12677
  const text = declaration.type.getText(declaration.getSourceFile());
12497
12678
  if (telemetryType(text)) {
12498
12679
  annotation = text;
@@ -12542,33 +12723,33 @@ export let ${name}:${record}=defaultValue<${record}>();`));
12542
12723
 
12543
12724
  // packages/compiler/src/frontend/promises.ts
12544
12725
  import { error as error8 } from "@tsplc/compiler/ir";
12545
- import ts36 from "typescript";
12726
+ import ts37 from "typescript";
12546
12727
 
12547
12728
  // packages/compiler/src/frontend/promise-chains.ts
12548
- import ts35 from "typescript";
12729
+ import ts36 from "typescript";
12549
12730
  var asyncRoutine = (context, node) => {
12550
12731
  const fn = context.routines.get(context.symbol(node));
12551
- return fn && hasModifier(fn, ts35.SyntaxKind.AsyncKeyword) ? fn : undefined;
12732
+ return fn && hasModifier(fn, ts36.SyntaxKind.AsyncKeyword) ? fn : undefined;
12552
12733
  };
12553
12734
  var job = (context, node) => {
12554
- const declaration = context.symbol(node)?.declarations?.find((value) => ts35.isVariableDeclaration(value) || ts35.isPropertyDeclaration(value));
12555
- if (!declaration || !ts35.isVariableDeclaration(declaration) && !ts35.isPropertyDeclaration(declaration)) {
12735
+ const declaration = context.symbol(node)?.declarations?.find((value) => ts36.isVariableDeclaration(value) || ts36.isPropertyDeclaration(value));
12736
+ if (!declaration || !ts36.isVariableDeclaration(declaration) && !ts36.isPropertyDeclaration(declaration)) {
12556
12737
  return;
12557
12738
  }
12558
12739
  const init = declaration.initializer;
12559
- if (!init || !ts35.isCallExpression(init) || !ts35.isPropertyAccessExpression(init.expression) || !context.namesSdk(init.expression.expression, "backgroundTasks") || init.expression.name.text !== "define") {
12740
+ if (!init || !ts36.isCallExpression(init) || !ts36.isPropertyAccessExpression(init.expression) || !context.namesSdk(init.expression.expression, "backgroundTasks") || init.expression.name.text !== "define") {
12560
12741
  return;
12561
12742
  }
12562
12743
  return asyncRoutine(context, init.arguments[0]);
12563
12744
  };
12564
- var callee = (call) => ts35.isPropertyAccessExpression(call.expression) ? call.expression.name : call.expression;
12745
+ var callee = (call) => ts36.isPropertyAccessExpression(call.expression) ? call.expression.name : call.expression;
12565
12746
  var operation = (context, call) => asyncRoutine(context, callee(call)) ?? job(context, callee(call));
12566
12747
  var isSdk = (context, call, name) => context.namesSdk(callee(call), name);
12567
12748
  var chainOf = (context, expression) => {
12568
- if (!ts35.isCallExpression(expression)) {
12749
+ if (!ts36.isCallExpression(expression)) {
12569
12750
  return;
12570
12751
  }
12571
- if (ts35.isPropertyAccessExpression(expression.expression) && ["then", "catch"].includes(expression.expression.name.text)) {
12752
+ if (ts36.isPropertyAccessExpression(expression.expression) && ["then", "catch"].includes(expression.expression.name.text)) {
12572
12753
  const prefix = chainOf(context, expression.expression.expression);
12573
12754
  if (!prefix) {
12574
12755
  return;
@@ -12589,7 +12770,7 @@ var chainOf = (context, expression) => {
12589
12770
  }
12590
12771
  };
12591
12772
  var lowerChain = (context, expression, owner, detached) => new PromiseChain(context, expression, owner).lower(detached);
12592
- var isAggregate = (type) => Boolean(type && type.flags & ts35.TypeFlags.Object);
12773
+ var isAggregate = (type) => Boolean(type && type.flags & ts36.TypeFlags.Object);
12593
12774
  var helperFinish = (call, type, discard = false) => type === "void" || discard ? `await ${call};return;` : `return await ${call};`;
12594
12775
 
12595
12776
  class PromiseChain {
@@ -12616,15 +12797,15 @@ class PromiseChain {
12616
12797
  }
12617
12798
  this.chain = chain;
12618
12799
  this.source = expression.getSourceFile();
12619
- this.classOwner = ts35.isMethodDeclaration(owner) && ts35.isClassDeclaration(owner.parent) ? owner.parent : undefined;
12800
+ this.classOwner = ts36.isMethodDeclaration(owner) && ts36.isClassDeclaration(owner.parent) ? owner.parent : undefined;
12620
12801
  context.ensureImports(this.source, expression);
12621
12802
  context.useDiagnostics(expression);
12622
12803
  for (const link of chain.links) {
12623
12804
  for (const value of link.handlers) {
12624
- if (value.kind === ts35.SyntaxKind.UndefinedKeyword || value.kind === ts35.SyntaxKind.NullKeyword) {
12805
+ if (value.kind === ts36.SyntaxKind.UndefinedKeyword || value.kind === ts36.SyntaxKind.NullKeyword) {
12625
12806
  continue;
12626
12807
  }
12627
- if (ts35.isArrowFunction(value) || ts35.isFunctionExpression(value)) {
12808
+ if (ts36.isArrowFunction(value) || ts36.isFunctionExpression(value)) {
12628
12809
  this.collectCaptures(value);
12629
12810
  }
12630
12811
  }
@@ -12646,21 +12827,21 @@ class PromiseChain {
12646
12827
  }
12647
12828
  collectCaptures(handler) {
12648
12829
  const visit = (node) => {
12649
- if (ts35.isIdentifier(node) && !(ts35.isPropertyAccessExpression(node.parent) && node.parent.name === node) && !(ts35.isPropertyAssignment(node.parent) && node.parent.name === node)) {
12830
+ if (ts36.isIdentifier(node) && !(ts36.isPropertyAccessExpression(node.parent) && node.parent.name === node) && !(ts36.isPropertyAssignment(node.parent) && node.parent.name === node)) {
12650
12831
  this.capture(node);
12651
12832
  }
12652
- ts35.forEachChild(node, visit);
12833
+ ts36.forEachChild(node, visit);
12653
12834
  };
12654
12835
  visit(handler.body);
12655
12836
  }
12656
12837
  capture(node) {
12657
12838
  const { context } = this;
12658
- const key = ts35.isShorthandPropertyAssignment(node.parent) ? context.checker.getShorthandAssignmentValueSymbol(node.parent) : context.symbol(node);
12839
+ const key = ts36.isShorthandPropertyAssignment(node.parent) ? context.checker.getShorthandAssignmentValueSymbol(node.parent) : context.symbol(node);
12659
12840
  const declaration = key?.valueDeclaration;
12660
- if (!key || !declaration || !(ts35.isVariableDeclaration(declaration) || ts35.isParameter(declaration)) || ts35.findAncestor(declaration.parent, ts35.isFunctionLike) !== this.owner || this.captures.has(key)) {
12841
+ if (!key || !declaration || !(ts36.isVariableDeclaration(declaration) || ts36.isParameter(declaration)) || ts36.findAncestor(declaration.parent, ts36.isFunctionLike) !== this.owner || this.captures.has(key)) {
12661
12842
  return;
12662
12843
  }
12663
- if (ts35.isVariableDeclaration(declaration) && (!ts35.isVariableDeclarationList(declaration.parent) || !(declaration.parent.flags & ts35.NodeFlags.Const))) {
12844
+ if (ts36.isVariableDeclaration(declaration) && (!ts36.isVariableDeclarationList(declaration.parent) || !(declaration.parent.flags & ts36.NodeFlags.Const))) {
12664
12845
  this.context.fail(node, "Continuation captures must be const values; store mutable state on the controller instead.");
12665
12846
  }
12666
12847
  if (!declaration.type) {
@@ -12677,7 +12858,7 @@ class PromiseChain {
12677
12858
  }
12678
12859
  hasBorrow(node, seen = new Set) {
12679
12860
  const { context } = this;
12680
- if (ts35.isTypeReferenceNode(node)) {
12861
+ if (ts36.isTypeReferenceNode(node)) {
12681
12862
  if (context.namesSdk(node.typeName, "InOut")) {
12682
12863
  return true;
12683
12864
  }
@@ -12685,16 +12866,16 @@ class PromiseChain {
12685
12866
  if (key && !seen.has(key)) {
12686
12867
  seen.add(key);
12687
12868
  for (const declaration of key.declarations ?? []) {
12688
- if (ts35.isInterfaceDeclaration(declaration) && declaration.members.some((member) => ts35.isPropertySignature(member) && member.type && this.hasBorrow(member.type, seen))) {
12869
+ if (ts36.isInterfaceDeclaration(declaration) && declaration.members.some((member) => ts36.isPropertySignature(member) && member.type && this.hasBorrow(member.type, seen))) {
12689
12870
  return true;
12690
12871
  }
12691
- if (ts35.isTypeAliasDeclaration(declaration) && this.hasBorrow(declaration.type, seen)) {
12872
+ if (ts36.isTypeAliasDeclaration(declaration) && this.hasBorrow(declaration.type, seen)) {
12692
12873
  return true;
12693
12874
  }
12694
12875
  }
12695
12876
  }
12696
12877
  }
12697
- return node.getChildren().some((child) => ts35.isTypeNode(child) && this.hasBorrow(child, seen));
12878
+ return node.getChildren().some((child) => ts36.isTypeNode(child) && this.hasBorrow(child, seen));
12698
12879
  }
12699
12880
  rootCall() {
12700
12881
  const { context, source } = this;
@@ -12702,7 +12883,7 @@ class PromiseChain {
12702
12883
  const fn = operation(context, root);
12703
12884
  if (fn) {
12704
12885
  const node = fn.type;
12705
- if (!node || !ts35.isTypeReferenceNode(node) || !node.typeArguments?.[0]) {
12886
+ if (!node || !ts36.isTypeReferenceNode(node) || !node.typeArguments?.[0]) {
12706
12887
  this.context.fail(fn, "Async calls need an explicit Promise<T> result.");
12707
12888
  }
12708
12889
  const type = context.typeText(node.typeArguments[0], source);
@@ -12751,12 +12932,12 @@ class PromiseChain {
12751
12932
  }
12752
12933
  const type = context.typeText(response, source);
12753
12934
  const options = root.arguments[1];
12754
- if (options && !ts35.isObjectLiteralExpression(options)) {
12935
+ if (options && !ts36.isObjectLiteralExpression(options)) {
12755
12936
  this.context.fail(options, "fetch options must be an inline object.");
12756
12937
  }
12757
12938
  const parameters = [];
12758
- const optionText = options && ts35.isObjectLiteralExpression(options) ? options.properties.map((property) => {
12759
- if (!ts35.isPropertyAssignment(property)) {
12939
+ const optionText = options && ts36.isObjectLiteralExpression(options) ? options.properties.map((property) => {
12940
+ if (!ts36.isPropertyAssignment(property)) {
12760
12941
  this.context.fail(property, "fetch requires named options.");
12761
12942
  }
12762
12943
  if (property.name.getText(source) !== "json") {
@@ -12778,23 +12959,23 @@ class PromiseChain {
12778
12959
  expressionType(node) {
12779
12960
  const { context, source } = this;
12780
12961
  const { checker } = context;
12781
- if (ts35.isCallExpression(node) && node.typeArguments?.[0] && (context.namesSdk(node.expression, "defaultValue") || context.namesSdk(node.expression, "copy") || ["exact", "wrap", "wrapAdd", "wrapMultiply", "saturate"].some((name) => context.namesSdk(node.expression, name)))) {
12962
+ if (ts36.isCallExpression(node) && node.typeArguments?.[0] && (context.namesSdk(node.expression, "defaultValue") || context.namesSdk(node.expression, "copy") || ["exact", "wrap", "wrapAdd", "wrapMultiply", "saturate"].some((name) => context.namesSdk(node.expression, name)))) {
12782
12963
  return context.typeText(node.typeArguments[0], source);
12783
12964
  }
12784
- const name = ts35.isPropertyAccessExpression(node) ? node.name : node;
12785
- const declaration = context.symbol(name)?.declarations?.find((value) => (ts35.isVariableDeclaration(value) || ts35.isParameter(value) || ts35.isPropertyDeclaration(value) || ts35.isPropertySignature(value)) && value.type);
12786
- if (declaration && (ts35.isVariableDeclaration(declaration) || ts35.isParameter(declaration) || ts35.isPropertyDeclaration(declaration) || ts35.isPropertySignature(declaration)) && declaration.type) {
12965
+ const name = ts36.isPropertyAccessExpression(node) ? node.name : node;
12966
+ const declaration = context.symbol(name)?.declarations?.find((value) => (ts36.isVariableDeclaration(value) || ts36.isParameter(value) || ts36.isPropertyDeclaration(value) || ts36.isPropertySignature(value)) && value.type);
12967
+ if (declaration && (ts36.isVariableDeclaration(declaration) || ts36.isParameter(declaration) || ts36.isPropertyDeclaration(declaration) || ts36.isPropertySignature(declaration)) && declaration.type) {
12787
12968
  return context.typeText(declaration.type, source);
12788
12969
  }
12789
12970
  const type = checker.getTypeAtLocation(node);
12790
- if (type.flags & ts35.TypeFlags.BooleanLike) {
12971
+ if (type.flags & ts36.TypeFlags.BooleanLike) {
12791
12972
  return "BOOL";
12792
12973
  }
12793
- if (type.flags & ts35.TypeFlags.Void) {
12974
+ if (type.flags & ts36.TypeFlags.Void) {
12794
12975
  return "void";
12795
12976
  }
12796
- if (type.symbol && type.symbol.name !== "__type" && type.flags & ts35.TypeFlags.Object) {
12797
- return checker.typeToString(type, node, ts35.TypeFormatFlags.NoTruncation | ts35.TypeFormatFlags.UseAliasDefinedOutsideCurrentScope);
12977
+ if (type.symbol && type.symbol.name !== "__type" && type.flags & ts36.TypeFlags.Object) {
12978
+ return checker.typeToString(type, node, ts36.TypeFormatFlags.NoTruncation | ts36.TypeFormatFlags.UseAliasDefinedOutsideCurrentScope);
12798
12979
  }
12799
12980
  this.context.fail(node, "Annotate this value with its concrete PLC type before using it in an async continuation.");
12800
12981
  }
@@ -12816,29 +12997,30 @@ class PromiseChain {
12816
12997
  const { context, classOwner, source } = this;
12817
12998
  const links = this.chain.links;
12818
12999
  let lowered = {
12819
- call: this.addHelper(`tsplcPromiseOperation${context.sequence()}`, helperFinish(this.rootInvocation, this.rootType), this.rootType),
13000
+ call: this.addHelper(context.names.name("tsplcPromiseOperation", this.chain.root), helperFinish(this.rootInvocation, this.rootType), this.rootType),
12820
13001
  type: this.rootType,
12821
13002
  aggregate: isAggregate(context.checker.getAwaitedType(context.checker.getTypeAtLocation(this.chain.root)))
12822
13003
  };
12823
13004
  for (const [index, link] of links.entries()) {
12824
13005
  lowered = this.link(link, lowered, {
12825
- terminal: detached && index === links.length - 1
13006
+ terminal: detached && index === links.length - 1,
13007
+ index
12826
13008
  });
12827
13009
  }
12828
13010
  const values = this.params.map((value) => value.expression).join(",");
12829
13011
  if (!detached) {
12830
13012
  return lowered.call.replace(`(${this.args})`, `(${values})`);
12831
13013
  }
12832
- const site = `tsplcPromiseSite${context.sequence()}`;
13014
+ const site = context.names.name("tsplcPromiseSite", this.chain.root);
12833
13015
  const callable = lowered.call.slice(0, lowered.call.indexOf("("));
12834
13016
  const scope = classOwner ?? source;
12835
13017
  context.append(scope, this.expression, `${classOwner ? "private " : "const "}${site}=tsplcCooperative.define(${callable});`);
12836
13018
  context.sites.set(scope, [...context.sites.get(scope) ?? [], site]);
12837
13019
  return `${classOwner ? "this." : ""}${site}.start(${values});`;
12838
13020
  }
12839
- link(link, previous, { terminal }) {
12840
- const fulfilled = link.kind === "then" ? this.callback(link.handlers[0], previous.type, "promiseResult") : undefined;
12841
- const rejected = this.callback(link.handlers[link.kind === "catch" ? 0 : 1], "UDINT", "tsplcErrorCode(promiseError)");
13021
+ link(link, previous, { terminal, index }) {
13022
+ const fulfilled = link.kind === "then" ? this.callback(link.handlers[0], previous.type, "promiseResult", `${index}Fulfilled`) : undefined;
13023
+ const rejected = this.callback(link.handlers[link.kind === "catch" ? 0 : 1], "UDINT", "tsplcErrorCode(promiseError)", `${index}Rejected`);
12842
13024
  if (!fulfilled && !rejected) {
12843
13025
  return previous;
12844
13026
  }
@@ -12847,13 +13029,13 @@ class PromiseChain {
12847
13029
  this.context.fail(this.expression, "A recovery callback must return the same PLC type as the fulfilled branch.");
12848
13030
  }
12849
13031
  return {
12850
- call: this.addHelper(`tsplcPromiseChain${this.context.sequence()}`, linkBody(previous, { fulfilled, rejected, terminal }), output),
13032
+ call: this.addHelper(this.context.names.name(`tsplcPromiseChain${index}`, this.chain.root), linkBody(previous, { fulfilled, rejected, terminal }), output),
12851
13033
  type: output,
12852
13034
  aggregate: terminal ? false : fulfilled?.aggregate ?? previous.aggregate
12853
13035
  };
12854
13036
  }
12855
- callback(expression, inputType, input) {
12856
- if (!expression || expression.kind === ts35.SyntaxKind.NullKeyword || ts35.isIdentifier(expression) && expression.text === "undefined") {
13037
+ callback(expression, inputType, input, slot) {
13038
+ if (!expression || expression.kind === ts36.SyntaxKind.NullKeyword || ts36.isIdentifier(expression) && expression.text === "undefined") {
12857
13039
  return;
12858
13040
  }
12859
13041
  const { context, source } = this;
@@ -12867,13 +13049,14 @@ class PromiseChain {
12867
13049
  return this.namedCallback(expression, declaration, {
12868
13050
  inputType,
12869
13051
  input,
12870
- aggregate
13052
+ aggregate,
13053
+ slot
12871
13054
  });
12872
13055
  }
12873
13056
  const names = new Map(this.captureNames);
12874
13057
  const parameter = declaration.parameters[0];
12875
13058
  if (parameter) {
12876
- if (!ts35.isIdentifier(parameter.name)) {
13059
+ if (!ts36.isIdentifier(parameter.name)) {
12877
13060
  this.context.fail(parameter, "Promise callback parameters need names.");
12878
13061
  }
12879
13062
  names.set(context.symbol(parameter.name), "promiseValue");
@@ -12882,7 +13065,7 @@ class PromiseChain {
12882
13065
  parameter,
12883
13066
  inputType
12884
13067
  });
12885
- const name = `tsplcPromiseHandler${context.sequence()}`;
13068
+ const name = context.names.name(`tsplcPromiseHandler${slot}`, this.chain.root);
12886
13069
  const body = this.replaceNames(declaration.body, names);
12887
13070
  const takesInput = Boolean(parameter && inputType !== "void");
12888
13071
  const handlerParams = [
@@ -12897,12 +13080,12 @@ class PromiseChain {
12897
13080
  };
12898
13081
  }
12899
13082
  handlerDeclaration(expression) {
12900
- if (ts35.isArrowFunction(expression) || ts35.isFunctionExpression(expression)) {
13083
+ if (ts36.isArrowFunction(expression) || ts36.isFunctionExpression(expression)) {
12901
13084
  return expression;
12902
13085
  }
12903
13086
  const key = this.context.symbol(expression);
12904
13087
  const named = key && this.context.routines.get(key);
12905
- if (!named || !ts35.isFunctionDeclaration(named)) {
13088
+ if (!named || !ts36.isFunctionDeclaration(named)) {
12906
13089
  this.context.fail(expression, "Use a named function or inline arrow; bind instance methods with an arrow.");
12907
13090
  }
12908
13091
  return named;
@@ -12910,18 +13093,19 @@ class PromiseChain {
12910
13093
  namedCallback(expression, declaration, {
12911
13094
  inputType,
12912
13095
  input,
12913
- aggregate
13096
+ aggregate,
13097
+ slot
12914
13098
  }) {
12915
13099
  const { context, source } = this;
12916
13100
  const result = declaration.type;
12917
13101
  if (!result) {
12918
13102
  this.context.fail(declaration, "Annotate callback results with their concrete PLC type.");
12919
13103
  }
12920
- const output = ts35.isTypeReferenceNode(result) && result.typeName.getText(declaration.getSourceFile()) === "Promise" ? result.typeArguments[0] : result;
13104
+ const output = ts36.isTypeReferenceNode(result) && result.typeName.getText(declaration.getSourceFile()) === "Promise" ? result.typeArguments[0] : result;
12921
13105
  const callbackType = context.typeText(output, source);
12922
13106
  const name = expression.getText(source);
12923
13107
  const takesInput = declaration.parameters.length > 0;
12924
- if (hasModifier(declaration, ts35.SyntaxKind.AsyncKeyword)) {
13108
+ if (hasModifier(declaration, ts36.SyntaxKind.AsyncKeyword)) {
12925
13109
  return {
12926
13110
  call: `${name}(${takesInput ? input : ""})`,
12927
13111
  type: callbackType,
@@ -12929,7 +13113,7 @@ class PromiseChain {
12929
13113
  };
12930
13114
  }
12931
13115
  return {
12932
- call: this.addHelper(`tsplcPromiseNamed${context.sequence()}`, callbackType === "void" ? `${name}(${takesInput ? "promiseInput" : ""});return;` : `return ${name}(${takesInput ? "promiseInput" : ""});`, callbackType, takesInput ? { type: inputType, argument: input } : undefined),
13116
+ call: this.addHelper(context.names.name(`tsplcPromiseNamed${slot}`, this.chain.root), callbackType === "void" ? `${name}(${takesInput ? "promiseInput" : ""});return;` : `return ${name}(${takesInput ? "promiseInput" : ""});`, callbackType, takesInput ? { type: inputType, argument: input } : undefined),
12933
13117
  type: callbackType,
12934
13118
  aggregate
12935
13119
  };
@@ -12941,24 +13125,24 @@ class PromiseChain {
12941
13125
  const { context, source } = this;
12942
13126
  const annotation = declaration.type;
12943
13127
  if (annotation) {
12944
- return ts35.isTypeReferenceNode(annotation) && annotation.typeName.getText(source) === "Promise" ? context.typeText(annotation.typeArguments[0], source) : context.typeText(annotation, source);
13128
+ return ts36.isTypeReferenceNode(annotation) && annotation.typeName.getText(source) === "Promise" ? context.typeText(annotation.typeArguments[0], source) : context.typeText(annotation, source);
12945
13129
  }
12946
13130
  const resolved = context.checker.getSignatureFromDeclaration(declaration);
12947
13131
  const inferred = resolved && context.checker.getAwaitedType(context.checker.getReturnTypeOfSignature(resolved));
12948
- if (inferred?.flags && inferred.flags & ts35.TypeFlags.Void) {
13132
+ if (inferred?.flags && inferred.flags & ts36.TypeFlags.Void) {
12949
13133
  return "void";
12950
13134
  }
12951
- if (ts35.isBlock(body)) {
13135
+ if (ts36.isBlock(body)) {
12952
13136
  this.context.fail(declaration, "Annotate a callback that returns a value with its concrete PLC type.");
12953
13137
  }
12954
- if (ts35.isIdentifier(body) && parameter && context.symbol(body) === context.symbol(parameter.name)) {
13138
+ if (ts36.isIdentifier(body) && parameter && context.symbol(body) === context.symbol(parameter.name)) {
12955
13139
  return inputType;
12956
13140
  }
12957
- const returned = ts35.isCallExpression(body) ? operation(context, body) : undefined;
12958
- return returned?.type && ts35.isTypeReferenceNode(returned.type) ? context.typeText(returned.type.typeArguments[0], source) : this.expressionType(body);
13141
+ const returned = ts36.isCallExpression(body) ? operation(context, body) : undefined;
13142
+ return returned?.type && ts36.isTypeReferenceNode(returned.type) ? context.typeText(returned.type.typeArguments[0], source) : this.expressionType(body);
12959
13143
  }
12960
13144
  callbackCode(body, printed, type) {
12961
- if (ts35.isBlock(body)) {
13145
+ if (ts36.isBlock(body)) {
12962
13146
  return printed.slice(1, -1);
12963
13147
  }
12964
13148
  if (type === "void") {
@@ -12968,37 +13152,37 @@ class PromiseChain {
12968
13152
  }
12969
13153
  replaceNames(node, names) {
12970
13154
  const { context } = this;
12971
- const transformed = ts35.transform(node, [
13155
+ const transformed = ts36.transform(node, [
12972
13156
  (transformation) => (root) => {
12973
13157
  const visit = (value) => {
12974
- if (ts35.isReturnStatement(value) && value.expression && !ts35.isAwaitExpression(value.expression) && this.isPromise(value.expression)) {
12975
- return ts35.factory.updateReturnStatement(value, ts35.factory.createAwaitExpression(ts35.visitNode(value.expression, visit)));
13158
+ if (ts36.isReturnStatement(value) && value.expression && !ts36.isAwaitExpression(value.expression) && this.isPromise(value.expression)) {
13159
+ return ts36.factory.updateReturnStatement(value, ts36.factory.createAwaitExpression(ts36.visitNode(value.expression, visit)));
12976
13160
  }
12977
- if (ts35.isShorthandPropertyAssignment(value)) {
13161
+ if (ts36.isShorthandPropertyAssignment(value)) {
12978
13162
  const key = context.checker.getShorthandAssignmentValueSymbol(value);
12979
13163
  const name = key && names.get(key);
12980
13164
  if (name) {
12981
- return ts35.factory.createPropertyAssignment(value.name, ts35.factory.createIdentifier(name));
13165
+ return ts36.factory.createPropertyAssignment(value.name, ts36.factory.createIdentifier(name));
12982
13166
  }
12983
13167
  }
12984
- if (ts35.isIdentifier(value) && !(ts35.isPropertyAccessExpression(value.parent) && value.parent.name === value) && !(ts35.isPropertyAssignment(value.parent) && value.parent.name === value)) {
13168
+ if (ts36.isIdentifier(value) && !(ts36.isPropertyAccessExpression(value.parent) && value.parent.name === value) && !(ts36.isPropertyAssignment(value.parent) && value.parent.name === value)) {
12985
13169
  const key = context.symbol(value);
12986
13170
  const name = key && names.get(key);
12987
13171
  if (name) {
12988
- return ts35.factory.createIdentifier(name);
13172
+ return ts36.factory.createIdentifier(name);
12989
13173
  }
12990
13174
  }
12991
- return ts35.visitEachChild(value, visit, transformation);
13175
+ return ts36.visitEachChild(value, visit, transformation);
12992
13176
  };
12993
- return ts35.visitNode(root, visit);
13177
+ return ts36.visitNode(root, visit);
12994
13178
  }
12995
13179
  ]);
12996
- const printed = printer.printNode(ts35.EmitHint.Unspecified, transformed.transformed[0], node.getSourceFile());
13180
+ const printed = printer.printNode(ts36.EmitHint.Unspecified, transformed.transformed[0], node.getSourceFile());
12997
13181
  transformed.dispose();
12998
13182
  return printed;
12999
13183
  }
13000
13184
  }
13001
- var printer = ts35.createPrinter();
13185
+ var printer = ts36.createPrinter();
13002
13186
  function linkBody(previous, {
13003
13187
  fulfilled,
13004
13188
  rejected,
@@ -13026,9 +13210,9 @@ function successCode(fulfilled, resultType, terminal) {
13026
13210
 
13027
13211
  // packages/compiler/src/frontend/promises.ts
13028
13212
  var diagnosticsInstance = "tsplcPromiseDiagnostics";
13029
- var lowerPromises = (program, sdk, positions) => {
13213
+ var lowerPromises = (program, sdk, positions, root) => {
13030
13214
  const files = runtimeSources(program).filter((source) => !source.isDeclarationFile);
13031
- const rewrite = new PromiseRewrite(program.getTypeChecker(), sdk, positions, files);
13215
+ const rewrite = new PromiseRewrite(program.getTypeChecker(), sdk, positions, files, new GeneratedNames(root));
13032
13216
  const diagnostics = [];
13033
13217
  const runtimeBlocks = new Map;
13034
13218
  const { diagnosticsCalls, cancelCalls } = rewriteChains(rewrite, files, diagnostics);
@@ -13073,29 +13257,29 @@ function rewriteChains(rewrite, files, diagnostics) {
13073
13257
  };
13074
13258
  for (const source of files) {
13075
13259
  const visit = (node, owner) => {
13076
- if (ts36.isFunctionDeclaration(node) || ts36.isMethodDeclaration(node)) {
13260
+ if (ts37.isFunctionDeclaration(node) || ts37.isMethodDeclaration(node)) {
13077
13261
  if (node.body) {
13078
- ts36.forEachChild(node.body, (child) => visit(child, node));
13262
+ ts37.forEachChild(node.body, (child) => visit(child, node));
13079
13263
  }
13080
13264
  return;
13081
13265
  }
13082
13266
  if (!owner) {
13083
- ts36.forEachChild(node, (child) => visit(child));
13267
+ ts37.forEachChild(node, (child) => visit(child));
13084
13268
  return;
13085
13269
  }
13086
- if (ts36.isCallExpression(node) && rewrite.namesSdk(node.expression, "asyncDiagnostics")) {
13270
+ if (ts37.isCallExpression(node) && rewrite.namesSdk(node.expression, "asyncDiagnostics")) {
13087
13271
  rewrite.useDiagnostics(node);
13088
13272
  diagnosticsCalls.push(node);
13089
13273
  return;
13090
13274
  }
13091
- if (ts36.isCallExpression(node) && rewrite.namesSdk(node.expression, "cancelAsync")) {
13275
+ if (ts37.isCallExpression(node) && rewrite.namesSdk(node.expression, "cancelAsync")) {
13092
13276
  cancelCalls.push({ node, owner });
13093
13277
  return;
13094
13278
  }
13095
- if (ts36.isExpressionStatement(node)) {
13096
- const expression = ts36.isVoidExpression(node.expression) ? node.expression.expression : node.expression;
13279
+ if (ts37.isExpressionStatement(node)) {
13280
+ const expression = ts37.isVoidExpression(node.expression) ? node.expression.expression : node.expression;
13097
13281
  if (chainOf(rewrite, expression)) {
13098
- if (hasModifier(owner, ts36.SyntaxKind.AsyncKeyword)) {
13282
+ if (hasModifier(owner, ts37.SyntaxKind.AsyncKeyword)) {
13099
13283
  diagnostics.push(rewrite.diagnostic(node, "Await async work inside an async routine; detached calls belong in synchronous controllers."));
13100
13284
  return;
13101
13285
  }
@@ -13103,23 +13287,23 @@ function rewriteChains(rewrite, files, diagnostics) {
13103
13287
  return;
13104
13288
  }
13105
13289
  }
13106
- if (ts36.isCallExpression(node) && chainOf(rewrite, node)?.links.length) {
13290
+ if (ts37.isCallExpression(node) && chainOf(rewrite, node)?.links.length) {
13107
13291
  lower(node, node, owner, { detached: false });
13108
13292
  return;
13109
13293
  }
13110
- ts36.forEachChild(node, (child) => visit(child, owner));
13294
+ ts37.forEachChild(node, (child) => visit(child, owner));
13111
13295
  };
13112
13296
  visit(source);
13113
13297
  }
13114
13298
  return { diagnosticsCalls, cancelCalls };
13115
13299
  }
13116
13300
  function cancelScope(rewrite, node, owner, diagnostics) {
13117
- const scope = ts36.isMethodDeclaration(owner) && ts36.isClassDeclaration(owner.parent) ? owner.parent : owner.getSourceFile();
13118
- if (node.arguments.length && (node.arguments.length !== 1 || node.arguments[0].kind !== ts36.SyntaxKind.ThisKeyword)) {
13301
+ const scope = ts37.isMethodDeclaration(owner) && ts37.isClassDeclaration(owner.parent) ? owner.parent : owner.getSourceFile();
13302
+ if (node.arguments.length && (node.arguments.length !== 1 || node.arguments[0].kind !== ts37.SyntaxKind.ThisKeyword)) {
13119
13303
  diagnostics.push(rewrite.diagnostic(node, "cancelAsync takes this in a controller, or no argument in a module."));
13120
13304
  }
13121
- const name = `tsplcCancelScope${rewrite.sequence()}`;
13122
- const member = ts36.isClassDeclaration(scope);
13305
+ const name = rewrite.names.name("tsplcCancelScope", node);
13306
+ const member = ts37.isClassDeclaration(scope);
13123
13307
  const body = (rewrite.sites.get(scope) ?? []).map((site) => `${member ? "this." : ""}${site}.cancel();`).join("");
13124
13308
  rewrite.append(scope, node, member ? `private ${name}():void{${body}}` : `function ${name}():void{${body}}`);
13125
13309
  rewrite.edit(node, `${member ? "this." : ""}${name}()`);
@@ -13129,6 +13313,7 @@ class PromiseRewrite {
13129
13313
  checker;
13130
13314
  sdk;
13131
13315
  positions;
13316
+ names;
13132
13317
  routines = new Map;
13133
13318
  sites = new Map;
13134
13319
  diagnosticsOwner;
@@ -13138,16 +13323,16 @@ class PromiseRewrite {
13138
13323
  aliases = new Map;
13139
13324
  typeImports = new Map;
13140
13325
  imported = new Set;
13141
- nextName = 0;
13142
- constructor(checker, sdk, positions, files) {
13326
+ constructor(checker, sdk, positions, files, names) {
13143
13327
  this.checker = checker;
13144
13328
  this.sdk = sdk;
13145
13329
  this.positions = positions;
13330
+ this.names = names;
13146
13331
  for (const source of files) {
13147
13332
  for (const statement of source.statements) {
13148
- const candidates = ts36.isClassDeclaration(statement) ? statement.members.filter(ts36.isMethodDeclaration) : [statement];
13333
+ const candidates = ts37.isClassDeclaration(statement) ? statement.members.filter(ts37.isMethodDeclaration) : [statement];
13149
13334
  for (const candidate of candidates) {
13150
- if ((ts36.isFunctionDeclaration(candidate) || ts36.isMethodDeclaration(candidate)) && candidate.name) {
13335
+ if ((ts37.isFunctionDeclaration(candidate) || ts37.isMethodDeclaration(candidate)) && candidate.name) {
13151
13336
  this.routines.set(this.symbol(candidate.name), candidate);
13152
13337
  }
13153
13338
  }
@@ -13166,11 +13351,8 @@ class PromiseRewrite {
13166
13351
  fail(node, message) {
13167
13352
  throw new SemanticError(this.diagnostic(node, message));
13168
13353
  }
13169
- sequence() {
13170
- return this.nextName++;
13171
- }
13172
13354
  append(scope, origin, text) {
13173
- if (ts36.isClassDeclaration(scope)) {
13355
+ if (ts37.isClassDeclaration(scope)) {
13174
13356
  this.members.set(scope, [
13175
13357
  ...this.members.get(scope) ?? [],
13176
13358
  from(origin, text)
@@ -13193,7 +13375,7 @@ class PromiseRewrite {
13193
13375
  return this.additions.keys();
13194
13376
  }
13195
13377
  typeText(node, source) {
13196
- if (node.kind === ts36.SyntaxKind.VoidKeyword) {
13378
+ if (node.kind === ts37.SyntaxKind.VoidKeyword) {
13197
13379
  return "void";
13198
13380
  }
13199
13381
  if (node.getSourceFile() === source) {
@@ -13210,7 +13392,7 @@ class PromiseRewrite {
13210
13392
  return alias;
13211
13393
  }
13212
13394
  declareAlias(node) {
13213
- const alias = `TsplcPromiseType${this.sequence()}`;
13395
+ const alias = this.names.name("TsplcPromiseType", node);
13214
13396
  this.aliases.set(node, alias);
13215
13397
  this.append(node.getSourceFile(), node, `export type ${alias}=${node.getText(node.getSourceFile())};`);
13216
13398
  return alias;
@@ -13253,7 +13435,7 @@ class PromiseRewrite {
13253
13435
  }
13254
13436
 
13255
13437
  // packages/compiler/src/frontend/services.ts
13256
- import { dirname as dirname6, join as join3, relative as relative4 } from "node:path";
13438
+ import { dirname as dirname6, join as join3, relative as relative7 } from "node:path";
13257
13439
  import { error as error9 } from "@tsplc/compiler/ir";
13258
13440
  import {
13259
13441
  isIntegerType,
@@ -13262,7 +13444,7 @@ import {
13262
13444
  wireLayout,
13263
13445
  wireRecord
13264
13446
  } from "@tsplc/server";
13265
- import ts37 from "typescript";
13447
+ import ts38 from "typescript";
13266
13448
  var property = (checker, type, name) => {
13267
13449
  const symbol = type.getProperty(name);
13268
13450
  return symbol && checker.getTypeOfSymbol(symbol);
@@ -13279,12 +13461,12 @@ var layoutNumber = (checker, type, name, label) => {
13279
13461
  return value.value;
13280
13462
  };
13281
13463
  var scalarLayout = (checker, type, label) => {
13282
- if (type.flags & ts37.TypeFlags.Boolean) {
13464
+ if (type.flags & ts38.TypeFlags.Boolean) {
13283
13465
  return { field: { kind: "boolean" } };
13284
13466
  }
13285
13467
  const first = type.isUnion() ? type.types[0] : type;
13286
13468
  const member = first?.symbol?.valueDeclaration;
13287
- if (first && first.flags & ts37.TypeFlags.EnumLiteral && member && ts37.isEnumMember(member)) {
13469
+ if (first && first.flags & ts38.TypeFlags.EnumLiteral && member && ts38.isEnumMember(member)) {
13288
13470
  const members = {};
13289
13471
  for (const item of member.parent.members) {
13290
13472
  const value = checker.getConstantValue(item);
@@ -13313,13 +13495,13 @@ var scalarLayout = (checker, type, label) => {
13313
13495
  var recordLayout = (checker, type, label, output) => {
13314
13496
  const fields = {};
13315
13497
  const enums = {};
13316
- if (!(type.flags & ts37.TypeFlags.Void)) {
13317
- if (!(type.flags & ts37.TypeFlags.Object) || type.getStringIndexType() || type.getNumberIndexType() || type.getCallSignatures().length) {
13498
+ if (!(type.flags & ts38.TypeFlags.Void)) {
13499
+ if (!(type.flags & ts38.TypeFlags.Object) || type.getStringIndexType() || type.getNumberIndexType() || type.getCallSignatures().length) {
13318
13500
  throw new Error(`${label}: PLC procedures exchange one closed z.strictObject() record.`);
13319
13501
  }
13320
13502
  for (const field of type.getProperties()) {
13321
13503
  const key = `${label}.${field.name}`;
13322
- if (field.flags & ts37.SymbolFlags.Optional) {
13504
+ if (field.flags & ts38.SymbolFlags.Optional) {
13323
13505
  throw new Error(`${key}: optional wire fields are unsupported.`);
13324
13506
  }
13325
13507
  const value = checker.getTypeOfSymbol(field);
@@ -13383,17 +13565,17 @@ var lowerServices = (program, sdk, positions, options) => {
13383
13565
  const sourceFiles = runtimeSources(program).filter((source) => !source.isDeclarationFile);
13384
13566
  for (const source of sourceFiles) {
13385
13567
  for (const statement of source.statements) {
13386
- if (!ts37.isVariableStatement(statement)) {
13568
+ if (!ts38.isVariableStatement(statement)) {
13387
13569
  continue;
13388
13570
  }
13389
13571
  for (const declaration of statement.declarationList.declarations) {
13390
13572
  const call = declaration.initializer;
13391
- if (!call || !ts37.isCallExpression(call) || !namesSdk(checker, sdk, call.expression, "createServiceClient")) {
13573
+ if (!call || !ts38.isCallExpression(call) || !namesSdk(checker, sdk, call.expression, "createServiceClient")) {
13392
13574
  continue;
13393
13575
  }
13394
13576
  const router = call.typeArguments?.[0];
13395
13577
  const client = symbolAt(checker, declaration.name);
13396
- if (!router || !client || !(statement.declarationList.flags & ts37.NodeFlags.Const)) {
13578
+ if (!router || !client || !(statement.declarationList.flags & ts38.NodeFlags.Const)) {
13397
13579
  fail(declaration, "PLC1013", "Create a service client as a module constant: const services = createServiceClient<AppRouter>().");
13398
13580
  } else if (!options) {
13399
13581
  fail(call, "PLC1013", "Configure server in tsplc.config.ts to call the server.");
@@ -13413,11 +13595,11 @@ var lowerServices = (program, sdk, positions, options) => {
13413
13595
  const edits = [];
13414
13596
  const imports = new Map;
13415
13597
  const visit = (node) => {
13416
- if (ts37.isImportDeclaration(node) && ts37.isStringLiteral(node.moduleSpecifier)) {
13598
+ if (ts38.isImportDeclaration(node) && ts38.isStringLiteral(node.moduleSpecifier)) {
13417
13599
  const clause = node.importClause;
13418
13600
  const bindings = clause?.namedBindings;
13419
- const typeOnly = clause?.isTypeOnly || !clause?.name && bindings && ts37.isNamedImports(bindings) && bindings.elements.every((element) => element.isTypeOnly);
13420
- if (!typeOnly && clause && bindings && ts37.isNamedImports(bindings)) {
13601
+ const typeOnly = clause?.isTypeOnly || !clause?.name && bindings && ts38.isNamedImports(bindings) && bindings.elements.every((element) => element.isTypeOnly);
13602
+ if (!typeOnly && clause && bindings && ts38.isNamedImports(bindings)) {
13421
13603
  const elements = bindings.elements.filter((element) => {
13422
13604
  const imported = symbolAt(checker, element.name);
13423
13605
  return !imported || !clients.has(imported);
@@ -13426,7 +13608,7 @@ var lowerServices = (program, sdk, positions, options) => {
13426
13608
  edits.push({
13427
13609
  start: node.getStart(source),
13428
13610
  end: node.end,
13429
- text: elements.length || clause.name ? ts37.createPrinter().printNode(ts37.EmitHint.Unspecified, ts37.factory.updateImportDeclaration(node, node.modifiers, ts37.factory.updateImportClause(clause, clause.isTypeOnly, clause.name, ts37.factory.updateNamedImports(bindings, elements)), node.moduleSpecifier, node.attributes), source) : ""
13611
+ text: elements.length || clause.name ? ts38.createPrinter().printNode(ts38.EmitHint.Unspecified, ts38.factory.updateImportDeclaration(node, node.modifiers, ts38.factory.updateImportClause(clause, clause.isTypeOnly, clause.name, ts38.factory.updateNamedImports(bindings, elements)), node.moduleSpecifier, node.attributes), source) : ""
13430
13612
  });
13431
13613
  }
13432
13614
  }
@@ -13443,7 +13625,7 @@ var lowerServices = (program, sdk, positions, options) => {
13443
13625
  fail(node, "PLC1013", `Server runtime import ${node.moduleSpecifier.text} cannot execute in PLC code. Expose a PLC procedure on the server router and call it through createServiceClient instead.`);
13444
13626
  }
13445
13627
  }
13446
- if (ts37.isVariableStatement(node)) {
13628
+ if (ts38.isVariableStatement(node)) {
13447
13629
  const clientStatement = node.declarationList.declarations.some((declaration) => {
13448
13630
  const declared = symbolAt(checker, declaration.name);
13449
13631
  return declared && clients.has(declared);
@@ -13453,10 +13635,10 @@ var lowerServices = (program, sdk, positions, options) => {
13453
13635
  return;
13454
13636
  }
13455
13637
  }
13456
- if (clients.size && ts37.isPropertyAccessExpression(node)) {
13638
+ if (clients.size && ts38.isPropertyAccessExpression(node)) {
13457
13639
  const parts = [];
13458
13640
  let root = node;
13459
- while (ts37.isPropertyAccessExpression(root)) {
13641
+ while (ts38.isPropertyAccessExpression(root)) {
13460
13642
  parts.unshift(root.name.text);
13461
13643
  root = root.expression;
13462
13644
  }
@@ -13499,7 +13681,7 @@ var lowerServices = (program, sdk, positions, options) => {
13499
13681
  return;
13500
13682
  }
13501
13683
  }
13502
- ts37.forEachChild(node, visit);
13684
+ ts38.forEachChild(node, visit);
13503
13685
  };
13504
13686
  visit(source);
13505
13687
  if (!edits.length) {
@@ -13507,7 +13689,7 @@ var lowerServices = (program, sdk, positions, options) => {
13507
13689
  }
13508
13690
  let text = edited(source, edits);
13509
13691
  if (imports.size && module) {
13510
- const path = relative4(dirname6(source.fileName), module.file).replaceAll("\\", "/");
13692
+ const path = relative7(dirname6(source.fileName), module.file).replaceAll("\\", "/");
13511
13693
  text = mapped`${text}\nimport {${[...imports].map(([name, local]) => `${name} as ${local}`).join(",")}} from ${JSON.stringify(path.startsWith("../") ? path : `./${path}`)};\n`;
13512
13694
  }
13513
13695
  sources.set(source.fileName, text);
@@ -13575,7 +13757,7 @@ var serviceRecords = (program, lowering) => {
13575
13757
  return;
13576
13758
  }
13577
13759
  const checker = program.getTypeChecker();
13578
- const declarations = new Map(source.statements.filter(ts37.isInterfaceDeclaration).map((value) => [value.name.text, value]));
13760
+ const declarations = new Map(source.statements.filter(ts38.isInterfaceDeclaration).map((value) => [value.name.text, value]));
13579
13761
  return (type) => {
13580
13762
  let key;
13581
13763
  try {
@@ -13598,8 +13780,8 @@ function tsDiagnostic(diagnostic, locate = sourceSpan) {
13598
13780
  const result = {
13599
13781
  origin: "typescript",
13600
13782
  code: `TS${diagnostic.code}`,
13601
- severity: diagnostic.category === ts38.DiagnosticCategory.Error ? "error" : "warning",
13602
- message: ts38.flattenDiagnosticMessageText(diagnostic.messageText, `
13783
+ severity: diagnostic.category === ts39.DiagnosticCategory.Error ? "error" : "warning",
13784
+ message: ts39.flattenDiagnosticMessageText(diagnostic.messageText, `
13603
13785
  `)
13604
13786
  };
13605
13787
  if (diagnostic.file && diagnostic.start !== undefined) {
@@ -13620,11 +13802,11 @@ function analyze(options) {
13620
13802
  const environment = options.environment ?? { ...process.env };
13621
13803
  const debug = compileDebug(environment);
13622
13804
  const filename = resolve7(options.tsconfig);
13623
- const config = ts38.readConfigFile(filename, ts38.sys.readFile);
13805
+ const config = ts39.readConfigFile(filename, ts39.sys.readFile);
13624
13806
  if (config.error) {
13625
13807
  return { diagnostics: [tsDiagnostic(config.error)] };
13626
13808
  }
13627
- const parsed = ts38.parseJsonConfigFileContent(config.config, ts38.sys, dirname7(filename), undefined, filename);
13809
+ const parsed = ts39.parseJsonConfigFileContent(config.config, ts39.sys, dirname7(filename), undefined, filename);
13628
13810
  if (parsed.errors.length) {
13629
13811
  return {
13630
13812
  diagnostics: parsed.errors.map((diagnostic) => tsDiagnostic(diagnostic))
@@ -13648,8 +13830,8 @@ function analyze(options) {
13648
13830
  skipLibCheck: false,
13649
13831
  types: [],
13650
13832
  lib: ["lib.es2025.d.ts"],
13651
- module: ts38.ModuleKind.ESNext,
13652
- moduleResolution: ts38.ModuleResolutionKind.Bundler
13833
+ module: ts39.ModuleKind.ESNext,
13834
+ moduleResolution: ts39.ModuleResolutionKind.Bundler
13653
13835
  };
13654
13836
  delete compilerOptions.rootDir;
13655
13837
  delete compilerOptions.outDir;
@@ -13657,7 +13839,7 @@ function analyze(options) {
13657
13839
  const rootNames = [...new Set([...projectFiles, ...programFiles, sdk])];
13658
13840
  const virtualSources = new Map;
13659
13841
  const host = loweringHost(compilerOptions, virtualSources);
13660
- let program = ts38.createProgram(rootNames, compilerOptions, host);
13842
+ let program = ts39.createProgram(rootNames, compilerOptions, host);
13661
13843
  const plcFiles = (program) => {
13662
13844
  const files = new Set(runtimeSources(program));
13663
13845
  for (const source of program.getSourceFiles()) {
@@ -13698,12 +13880,12 @@ function analyze(options) {
13698
13880
  }
13699
13881
  if (debug.lowered) {
13700
13882
  for (const [path, text] of lowering.sources) {
13701
- const target = join4(debug.lowered, relative5(dirname7(filename), path));
13883
+ const target = join4(debug.lowered, relative8(dirname7(filename), path));
13702
13884
  mkdirSync(dirname7(target), { recursive: true });
13703
13885
  writeFileSync2(target, text.text);
13704
13886
  }
13705
13887
  }
13706
- program = ts38.createProgram({
13888
+ program = ts39.createProgram({
13707
13889
  rootNames,
13708
13890
  options: compilerOptions,
13709
13891
  host,
@@ -13734,11 +13916,11 @@ function analyze(options) {
13734
13916
  if (!apply(lowerConstFunctions(program, positions))) {
13735
13917
  return { diagnostics };
13736
13918
  }
13737
- const promises = lowerPromises(program, sdk, positions);
13919
+ const promises = lowerPromises(program, sdk, positions, dirname7(filename));
13738
13920
  if (!apply(promises)) {
13739
13921
  return { diagnostics };
13740
13922
  }
13741
- const lowering = lowerAsync(program, sdk, positions);
13923
+ const lowering = lowerAsync(program, sdk, positions, dirname7(filename));
13742
13924
  for (const [key, value] of promises.runtimeBlocks) {
13743
13925
  lowering.blocks.set(key, value);
13744
13926
  }
@@ -13755,7 +13937,7 @@ function analyze(options) {
13755
13937
  return hasErrors(diagnostics) ? { diagnostics } : { module, diagnostics };
13756
13938
  }
13757
13939
  function loweringHost(options, virtualSources) {
13758
- const host = ts38.createCompilerHost(options);
13940
+ const host = ts39.createCompilerHost(options);
13759
13941
  const read = host.readFile;
13760
13942
  const exists = host.fileExists;
13761
13943
  const directoryExists = host.directoryExists?.bind(host);
@@ -13824,6 +14006,9 @@ function attachLowerings(module, root, {
13824
14006
  if (elaboration.folded.length) {
13825
14007
  module.folded = elaboration.folded;
13826
14008
  }
14009
+ if (elaboration.references?.fields.length) {
14010
+ module.references = elaboration.references;
14011
+ }
13827
14012
  for (const entry of module.programs) {
13828
14013
  const background = lowering.schedules.get(entry.name);
13829
14014
  if (background) {
@@ -13837,17 +14022,17 @@ function attachLowerings(module, root, {
13837
14022
  }
13838
14023
  function checkHostConfig(file) {
13839
14024
  const bunTypes = createRequire2(import.meta.url).resolve("@types/bun/index.d.ts");
13840
- const program = ts38.createProgram([file], {
14025
+ const program = ts39.createProgram([file], {
13841
14026
  strict: true,
13842
14027
  noEmit: true,
13843
- target: ts38.ScriptTarget.ES2022,
13844
- module: ts38.ModuleKind.ESNext,
13845
- moduleResolution: ts38.ModuleResolutionKind.Bundler,
14028
+ target: ts39.ScriptTarget.ES2022,
14029
+ module: ts39.ModuleKind.ESNext,
14030
+ moduleResolution: ts39.ModuleResolutionKind.Bundler,
13846
14031
  allowImportingTsExtensions: true,
13847
14032
  skipLibCheck: true,
13848
14033
  types: [bunTypes]
13849
14034
  });
13850
- return ts38.getPreEmitDiagnostics(program).map((diagnostic) => tsDiagnostic(diagnostic));
14035
+ return ts39.getPreEmitDiagnostics(program).map((diagnostic) => tsDiagnostic(diagnostic));
13851
14036
  }
13852
14037
  export {
13853
14038
  analyze,
@@ -13855,5 +14040,5 @@ export {
13855
14040
  typeCheckOnly
13856
14041
  };
13857
14042
 
13858
- //# debugId=D9FCE426FE2EC2EA64756E2164756E21
14043
+ //# debugId=A5EA69EF3ACD83DF64756E2164756E21
13859
14044
  //# sourceMappingURL=index.js.map