@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.
- package/dist/bun-runtime.js +8 -2
- package/dist/bun-runtime.js.map +3 -3
- package/dist/cli.js +17 -5
- package/dist/cli.js.map +5 -5
- package/dist/codesys.js +2933 -1724
- package/dist/codesys.js.map +20 -19
- package/dist/index.js +870 -685
- package/dist/index.js.map +20 -19
- package/dist/ir.js +1654 -1364
- package/dist/ir.js.map +16 -14
- package/dist/project.js +5 -2
- package/dist/project.js.map +3 -3
- package/dist/telemetry.js +8 -2
- package/dist/telemetry.js.map +3 -3
- package/package.json +9 -9
- package/src/codesys/debug.ts +17 -2
- package/src/codesys/emit.ts +34 -11
- package/src/codesys/engineering.ts +27 -12
- package/src/codesys/explain.ts +1465 -0
- package/src/codesys/global-lists.ts +21 -9
- package/src/codesys/http.ts +12 -0
- package/src/codesys/instrumentation.ts +131 -3
- package/src/codesys/manifest.ts +29 -12
- package/src/codesys/numeric.ts +5 -3
- package/src/codesys/plan.ts +31 -28
- package/src/codesys/programs.ts +63 -1
- package/src/codesys/types.ts +34 -12
- package/src/frontend/async.ts +14 -8
- package/src/frontend/coroutines.ts +55 -16
- package/src/frontend/elaborate/expressions.ts +10 -2
- package/src/frontend/elaborate/filtered-arrays.ts +5 -5
- package/src/frontend/elaborate/index.ts +42 -4
- package/src/frontend/elaborate/model.ts +48 -1
- package/src/frontend/elaborate/references.ts +6 -6
- package/src/frontend/elaborate/specialize.ts +18 -4
- package/src/frontend/elaborate/storage.ts +58 -2
- package/src/frontend/expressions.ts +2 -2
- package/src/frontend/generated-names.ts +95 -0
- package/src/frontend/intrinsics.ts +1 -2
- package/src/frontend/promise-chains.ts +22 -8
- package/src/frontend/promises.ts +8 -10
- package/src/frontend/statements.ts +3 -2
- package/src/frontend/tasks.ts +8 -8
- package/src/frontend/typescript.ts +5 -2
- package/src/ir/conditions.ts +895 -0
- package/src/ir/core-model.ts +2 -2
- package/src/ir/fold.ts +15 -107
- package/src/ir/identity.ts +9 -0
- package/src/ir/index.ts +18 -13
- package/src/ir/job-errors.ts +14 -0
- package/src/ir/link.ts +1 -0
- package/src/ir/model.ts +16 -79
- package/src/ir/numeric.ts +5 -41
- package/src/ir/ranges.ts +8 -14
- package/src/ir/scalars.ts +6 -4
- package/src/ir/share.ts +0 -52
- package/src/project/debugger.ts +9 -0
- package/src/project/project.ts +6 -0
- package/src/project/release.ts +7 -4
package/src/codesys/types.ts
CHANGED
|
@@ -75,7 +75,7 @@ export class CodesysTypes {
|
|
|
75
75
|
if (type.kind === "record" || type.kind === "enum") {
|
|
76
76
|
const prefix = type.kind === "record" ? "ST" : "E";
|
|
77
77
|
this.names.set(type.id, names.allocateObject(prefix, label));
|
|
78
|
-
} else {
|
|
78
|
+
} else if (!this.inline(type)) {
|
|
79
79
|
this.names.set(type.id, names.allocate(`T_${label}`));
|
|
80
80
|
}
|
|
81
81
|
}
|
|
@@ -91,19 +91,13 @@ export class CodesysTypes {
|
|
|
91
91
|
}
|
|
92
92
|
}
|
|
93
93
|
|
|
94
|
-
// A block array is declared in place: a function block cannot be a data type's element.
|
|
95
|
-
for (const type of types.values()) {
|
|
96
|
-
if (type.kind === "array" && instancedBlock(type.id, types)) {
|
|
97
|
-
this.names.set(
|
|
98
|
-
type.id,
|
|
99
|
-
`ARRAY[${type.lowerBound}..${type.lowerBound + type.length - 1}] OF ${this.name(type.element)}`,
|
|
100
|
-
);
|
|
101
|
-
}
|
|
102
|
-
}
|
|
103
|
-
|
|
104
94
|
// Verified layouts are acyclic. Emit child DUTs first, then their containing DUT.
|
|
105
95
|
const emitted = new Set<string>();
|
|
106
96
|
const emit = (type: PlcType): void => {
|
|
97
|
+
if (type.kind === "array" && this.inline(type)) {
|
|
98
|
+
emit(this.type(type.element));
|
|
99
|
+
return;
|
|
100
|
+
}
|
|
107
101
|
if (
|
|
108
102
|
instancedBlock(type.id, types) ||
|
|
109
103
|
!this.names.has(type.id) ||
|
|
@@ -207,7 +201,35 @@ END_TYPE
|
|
|
207
201
|
}
|
|
208
202
|
|
|
209
203
|
name(id: string): string {
|
|
210
|
-
|
|
204
|
+
const named = this.names.get(id);
|
|
205
|
+
if (named !== undefined) {
|
|
206
|
+
return named;
|
|
207
|
+
}
|
|
208
|
+
const type = this.types.get(id);
|
|
209
|
+
if (type?.kind === "string" && this.inline(type)) {
|
|
210
|
+
return `${stringTypeName(type)}(${type.capacity})`;
|
|
211
|
+
}
|
|
212
|
+
if (type?.kind === "array" && this.inline(type)) {
|
|
213
|
+
return `ARRAY[${type.lowerBound}..${type.lowerBound + type.length - 1}] OF ${this.name(type.element)}`;
|
|
214
|
+
}
|
|
215
|
+
return id;
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
/**
|
|
219
|
+
* Whether a type is declared in place rather than as a data type of its own. A named alias of
|
|
220
|
+
* an array or a string would name its length, so a length change would change the variable's
|
|
221
|
+
* type, which an online change refuses; in place it changes only the variable's layout. A block
|
|
222
|
+
* array is always in place: a function block cannot be a data type's element. Keyed arrays keep
|
|
223
|
+
* their alias, whose attribute publishes each key.
|
|
224
|
+
*/
|
|
225
|
+
private inline(type: PlcType): boolean {
|
|
226
|
+
if (type.kind === "string") {
|
|
227
|
+
return true;
|
|
228
|
+
}
|
|
229
|
+
return (
|
|
230
|
+
type.kind === "array" &&
|
|
231
|
+
(!type.index || instancedBlock(type.id, this.types) !== undefined)
|
|
232
|
+
);
|
|
211
233
|
}
|
|
212
234
|
|
|
213
235
|
field(id: string, name: string): string {
|
package/src/frontend/async.ts
CHANGED
|
@@ -8,6 +8,7 @@ import {
|
|
|
8
8
|
} from "@tsplc/compiler/ir";
|
|
9
9
|
import ts from "typescript";
|
|
10
10
|
import { lowerCoroutine } from "./coroutines";
|
|
11
|
+
import { GeneratedNames } from "./generated-names";
|
|
11
12
|
import { runtimeSources } from "./module-graph";
|
|
12
13
|
import {
|
|
13
14
|
type Edit,
|
|
@@ -67,8 +68,8 @@ export interface AsyncContext {
|
|
|
67
68
|
/** Whether a node names the SDK declaration `name`. */
|
|
68
69
|
namesSdk: (node: ts.Node, name: string) => boolean;
|
|
69
70
|
fail: (node: ts.Node, message: string) => never;
|
|
70
|
-
/**
|
|
71
|
-
|
|
71
|
+
/** Names for generated declarations, from the source node each stands for. */
|
|
72
|
+
names: GeneratedNames;
|
|
72
73
|
}
|
|
73
74
|
|
|
74
75
|
/** One source file being rewritten: edits to its text and declarations added around it. */
|
|
@@ -94,6 +95,7 @@ export const lowerAsync = (
|
|
|
94
95
|
program: ts.Program,
|
|
95
96
|
sdk: string,
|
|
96
97
|
positions: Positions,
|
|
98
|
+
root: string,
|
|
97
99
|
): AsyncLowering => {
|
|
98
100
|
const result: AsyncLowering = {
|
|
99
101
|
sources: new Map(),
|
|
@@ -109,11 +111,11 @@ export const lowerAsync = (
|
|
|
109
111
|
const fail: (node: ts.Node, message: string) => never = (node, message) => {
|
|
110
112
|
throw new SemanticError(asyncDiagnostic(positions, node, message));
|
|
111
113
|
};
|
|
112
|
-
const
|
|
114
|
+
const names = new GeneratedNames(root);
|
|
115
|
+
const { functions, methods } = asyncRoutines(program, symbol, names);
|
|
113
116
|
if (!functions.size) {
|
|
114
117
|
return result;
|
|
115
118
|
}
|
|
116
|
-
let sequence = 0;
|
|
117
119
|
const context: AsyncContext = {
|
|
118
120
|
checker,
|
|
119
121
|
positions,
|
|
@@ -125,7 +127,7 @@ export const lowerAsync = (
|
|
|
125
127
|
symbol,
|
|
126
128
|
namesSdk: (node, name) => namesSdk(checker, sdk, node, name),
|
|
127
129
|
fail,
|
|
128
|
-
|
|
130
|
+
names,
|
|
129
131
|
};
|
|
130
132
|
const sources = runtimeSources(program).filter(
|
|
131
133
|
(source) => !source.isDeclarationFile,
|
|
@@ -143,6 +145,7 @@ export const lowerAsync = (
|
|
|
143
145
|
function asyncRoutines(
|
|
144
146
|
program: ts.Program,
|
|
145
147
|
symbol: (node: ts.Node) => ts.Symbol | undefined,
|
|
148
|
+
names: GeneratedNames,
|
|
146
149
|
) {
|
|
147
150
|
const functions = new Map<ts.Symbol, Routine>();
|
|
148
151
|
const methods = new Map<ts.Symbol, MethodMembers>();
|
|
@@ -160,7 +163,7 @@ function asyncRoutines(
|
|
|
160
163
|
}
|
|
161
164
|
functions.set(symbol(fn.name)!, fn);
|
|
162
165
|
if (ts.isMethodDeclaration(fn)) {
|
|
163
|
-
const prefix = `tsplcAsync${fn.name.getText(source)}
|
|
166
|
+
const prefix = names.name(`tsplcAsync${fn.name.getText(source)}`, fn);
|
|
164
167
|
methods.set(symbol(fn.name)!, {
|
|
165
168
|
start: `${prefix}Start`,
|
|
166
169
|
reset: `${prefix}Reset`,
|
|
@@ -260,7 +263,7 @@ function addInstanceEntries(
|
|
|
260
263
|
const name = declaration.name.text;
|
|
261
264
|
// One entry polls all of an instance's sites, in their order: they share its task.
|
|
262
265
|
if (polls?.length) {
|
|
263
|
-
const entry =
|
|
266
|
+
const entry = context.names.name("tsplcContinuation", declaration);
|
|
264
267
|
const calls = polls.map((poll) =>
|
|
265
268
|
instance.first === undefined
|
|
266
269
|
? `${name}.${poll}();`
|
|
@@ -279,7 +282,10 @@ function addInstanceEntries(
|
|
|
279
282
|
});
|
|
280
283
|
}
|
|
281
284
|
for (const job of jobs ?? []) {
|
|
282
|
-
const entry =
|
|
285
|
+
const entry = context.names.name(
|
|
286
|
+
`tsplcBackground_${job.method}`,
|
|
287
|
+
declaration,
|
|
288
|
+
);
|
|
283
289
|
entries.push(
|
|
284
290
|
from(node, `export function ${entry}():void{${name}.${job.method}();}`),
|
|
285
291
|
);
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// biome-ignore-all lint/style/noNonNullAssertion: Retain existing non-null assertions during the tooling migration; changing their contracts requires a separate review.
|
|
2
|
-
import { jobError } from "@tsplc/compiler/ir";
|
|
2
|
+
import { identityDigest, jobError, reservedErrors } from "@tsplc/compiler/ir";
|
|
3
3
|
import ts from "typescript";
|
|
4
4
|
import type {
|
|
5
5
|
AsyncContext,
|
|
@@ -10,6 +10,7 @@ import type {
|
|
|
10
10
|
} from "./async";
|
|
11
11
|
import { staticString } from "./configuration";
|
|
12
12
|
import { copyValue } from "./cooperative";
|
|
13
|
+
import type { GeneratedNames } from "./generated-names";
|
|
13
14
|
import { importSpecifier } from "./module-graph";
|
|
14
15
|
import {
|
|
15
16
|
copied,
|
|
@@ -58,8 +59,16 @@ const containsAwait = (node: ts.Node, source: ts.SourceFile): boolean =>
|
|
|
58
59
|
node.getChildren(source).some((child) => containsAwait(child, source));
|
|
59
60
|
|
|
60
61
|
/** The prefix of the type aliases a routine's module exports for its result and arguments. */
|
|
61
|
-
export const aliasPrefix = (fn: Routine) =>
|
|
62
|
-
`TsplcAsync${fn.name.getText(fn.getSourceFile())}
|
|
62
|
+
export const aliasPrefix = (names: GeneratedNames, fn: Routine) =>
|
|
63
|
+
names.name(`TsplcAsync${fn.name.getText(fn.getSourceFile())}`, fn);
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* A job's code identity: its steps, their targets and the state they keep. A job stores it when it
|
|
67
|
+
* starts and stops with `codeChanged` when an online change brings other code, since its step and
|
|
68
|
+
* fields were made for the code it started with. Never 0, the value of a field an online change adds.
|
|
69
|
+
*/
|
|
70
|
+
const codeDigest = (code: string): number =>
|
|
71
|
+
Number.parseInt(identityDigest(code), 16) || 1;
|
|
63
72
|
|
|
64
73
|
/** Replaces an async routine with a block that runs it as a resumable state machine. */
|
|
65
74
|
export function lowerCoroutine(
|
|
@@ -321,7 +330,7 @@ class Coroutine {
|
|
|
321
330
|
return annotated;
|
|
322
331
|
}
|
|
323
332
|
// Another module's result type is named through the alias its coroutine exports.
|
|
324
|
-
const type = `${aliasPrefix(called)}Result`;
|
|
333
|
+
const type = `${aliasPrefix(this.context.names, called)}Result`;
|
|
325
334
|
const statement = `import type {${type}} from ${importSpecifier(source.fileName, called.getSourceFile().fileName)};`;
|
|
326
335
|
if (!extra.some((item) => item.text === statement)) {
|
|
327
336
|
extra.push(from(node, statement));
|
|
@@ -560,7 +569,10 @@ class Coroutine {
|
|
|
560
569
|
this.context.fail(call, "GET requests cannot contain json.");
|
|
561
570
|
}
|
|
562
571
|
const responseType = this.text(response);
|
|
563
|
-
const httpName =
|
|
572
|
+
const httpName = this.context.names.name(
|
|
573
|
+
`Tsplc${rpc ? "Rpc" : "Http"}`,
|
|
574
|
+
call,
|
|
575
|
+
);
|
|
564
576
|
if (!json) {
|
|
565
577
|
extra.push(from(call, `interface ${httpName}Request {reserved:BOOL}`));
|
|
566
578
|
}
|
|
@@ -827,6 +839,16 @@ class ${httpName} extends FunctionBlock<${httpName}Input,${httpName}Output> { pr
|
|
|
827
839
|
"Async throw requires a numeric error code.",
|
|
828
840
|
);
|
|
829
841
|
}
|
|
842
|
+
if (
|
|
843
|
+
ts.isNumericLiteral(statement.expression) &&
|
|
844
|
+
Number(statement.expression.text) >= reservedErrors.first &&
|
|
845
|
+
Number(statement.expression.text) <= reservedErrors.last
|
|
846
|
+
) {
|
|
847
|
+
this.context.fail(
|
|
848
|
+
statement,
|
|
849
|
+
`Error codes ${reservedErrors.first} to ${reservedErrors.last} are tsPLC's own; throw another code.`,
|
|
850
|
+
);
|
|
851
|
+
}
|
|
830
852
|
return this.state(
|
|
831
853
|
reject(this.rewrite(statement.expression)),
|
|
832
854
|
statement,
|
|
@@ -1009,7 +1031,7 @@ class ${httpName} extends FunctionBlock<${httpName}Input,${httpName}Output> { pr
|
|
|
1009
1031
|
(error, cancellable) => {
|
|
1010
1032
|
const recover = mapped`${field ? mapped`this.${field.name} = ${error};` : ""}this.step = ${caught};`;
|
|
1011
1033
|
return cancellable
|
|
1012
|
-
? mapped`if(${error} ===
|
|
1034
|
+
? mapped`if(${error} === ${jobError.cancelled} || ${error} === ${jobError.codeChanged}) {${this.failure(error)}} else {${recover}}`
|
|
1013
1035
|
: recover;
|
|
1014
1036
|
},
|
|
1015
1037
|
);
|
|
@@ -1081,21 +1103,38 @@ class ${httpName} extends FunctionBlock<${httpName}Input,${httpName}Output> { pr
|
|
|
1081
1103
|
const exported = hasModifier(fn, ts.SyntaxKind.ExportKeyword)
|
|
1082
1104
|
? "export "
|
|
1083
1105
|
: "";
|
|
1084
|
-
const
|
|
1085
|
-
|
|
1086
|
-
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}>();
|
|
1106
|
+
const prefix = aliasPrefix(this.context.names, fn);
|
|
1107
|
+
const aliases = `export type ${prefix}Result = ${returnType};\n${parameters.map((p, i) => `export type ${prefix}Argument${i} = ${p.type};`).join("\n")}`;
|
|
1108
|
+
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}>();
|
|
1087
1109
|
${[...this.fields.values()].map((f) => `private ${f.name}:${f.type}=defaultValue<${f.type}>();`).join("\n")}
|
|
1088
1110
|
${[...this.positionFields.values()].map((name) => `private ${name}:DINT=0;`).join("\n")}
|
|
1089
|
-
${this.children.join("\n")}
|
|
1090
|
-
|
|
1091
|
-
reset():void {${this.resets.join(" ")} this.busy=false;this.cancelling=false;this.done=false;this.error=0;this.step=0;}
|
|
1092
|
-
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)}};}
|
|
1093
|
-
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(
|
|
1111
|
+
${this.children.join("\n")}`;
|
|
1112
|
+
const table = joined(
|
|
1094
1113
|
[...this.states].map(
|
|
1095
1114
|
([id, body]) => mapped`case ${id}: {${body}} break;`,
|
|
1096
1115
|
),
|
|
1097
1116
|
"\n",
|
|
1098
|
-
)
|
|
1117
|
+
);
|
|
1118
|
+
const code = codeDigest(
|
|
1119
|
+
[
|
|
1120
|
+
fields,
|
|
1121
|
+
parameters.map((p) => `${p.field}:${p.type}`).join(","),
|
|
1122
|
+
entry,
|
|
1123
|
+
table.text,
|
|
1124
|
+
this.resets.join(" "),
|
|
1125
|
+
this.cancels.join(" "),
|
|
1126
|
+
[...this.yielding].join(","),
|
|
1127
|
+
].join("\n"),
|
|
1128
|
+
);
|
|
1129
|
+
const { codeChanged } = jobError;
|
|
1130
|
+
return mapped`${aliases}\n${exported}class ${this.text(fn.name)} extends FunctionBlock<{cancel:BOOL}> {
|
|
1131
|
+
${fields}
|
|
1132
|
+
private tsplcCode:UDINT=0; private tsplcPending:UDINT=0;
|
|
1133
|
+
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;}
|
|
1134
|
+
reset():void {${this.resets.join(" ")} this.busy=false;this.cancelling=false;this.tsplcPending=0;this.done=false;this.error=0;this.step=0;}
|
|
1135
|
+
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)}};}
|
|
1136
|
+
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=${jobError.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}
|
|
1137
|
+
default: {this.tsplcPending=${codeChanged};this.cancelling=true;return;} }if(!this.busy||this.step===previous${[...this.yielding].map((id) => `||previous===${id}`).join("")})return;}}
|
|
1099
1138
|
|
|
1100
1139
|
}`;
|
|
1101
1140
|
}
|
|
@@ -1113,7 +1152,7 @@ protected execute(input:{cancel:BOOL}):void {if(!this.busy)return;if(input.cance
|
|
|
1113
1152
|
const names = new Map(
|
|
1114
1153
|
worker.members.map((member) => [
|
|
1115
1154
|
member.name!.getText(parsed),
|
|
1116
|
-
|
|
1155
|
+
`${this.context.names.name("tsplcAsync", this.fn)}_${member.name!.getText(parsed)}`,
|
|
1117
1156
|
]),
|
|
1118
1157
|
);
|
|
1119
1158
|
names.set("start", method.start);
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
// biome-ignore-all lint/style/noNonNullAssertion: Retain existing non-null assertions during the tooling migration; changing their contracts requires a separate review.
|
|
2
|
+
import { identityDigest } from "@tsplc/compiler/ir";
|
|
2
3
|
import ts from "typescript";
|
|
3
4
|
import { from, joined, type Mapped, mapped, type Part } from "../positions";
|
|
4
5
|
import { unaliased } from "../sdk";
|
|
@@ -571,8 +572,11 @@ export class ExpressionSpecializer {
|
|
|
571
572
|
if (known) {
|
|
572
573
|
return known;
|
|
573
574
|
}
|
|
575
|
+
const id = -1 - this.services.size;
|
|
576
|
+
// A service is called, never held, so no reference holds its id.
|
|
574
577
|
const node: ModelNode = {
|
|
575
|
-
id
|
|
578
|
+
id,
|
|
579
|
+
reference: id,
|
|
576
580
|
captured: { kind: "service", path },
|
|
577
581
|
};
|
|
578
582
|
this.services.set(path, node);
|
|
@@ -698,7 +702,11 @@ export class ExpressionSpecializer {
|
|
|
698
702
|
if (!node.type) {
|
|
699
703
|
throw new Error("A table needs a declared type.");
|
|
700
704
|
}
|
|
701
|
-
|
|
705
|
+
// Named for where setup put it: numbered by first read, two tables swapped names under one type.
|
|
706
|
+
const identity = this.model.identity(node);
|
|
707
|
+
const name = identity
|
|
708
|
+
? `tsplcTable_${identityDigest(identity)}`
|
|
709
|
+
: `tsplcTable${this.tables.size + 1}`;
|
|
702
710
|
this.tables.set(node.id, name);
|
|
703
711
|
const type = this.layouts.text(node.type, { kind: "node", id: node.id });
|
|
704
712
|
this.tableDeclarations.push(
|
|
@@ -429,10 +429,10 @@ export class FilteredArrays {
|
|
|
429
429
|
frame.emitter.open(mapped`if (${joined(guards, " && ")}) {`);
|
|
430
430
|
frame.emitter.append(arm.lines);
|
|
431
431
|
if (isTrue(arm.passes)) {
|
|
432
|
-
frame.emitter.line(`${result} = ${arm.node.
|
|
432
|
+
frame.emitter.line(`${result} = ${arm.node.reference};`);
|
|
433
433
|
} else if (arm.passes.kind !== "const") {
|
|
434
434
|
frame.emitter.line(
|
|
435
|
-
mapped`if (${this.dialect.condition(arm.passes, at)}) { ${result} = ${arm.node.
|
|
435
|
+
mapped`if (${this.dialect.condition(arm.passes, at)}) { ${result} = ${arm.node.reference}; }`,
|
|
436
436
|
);
|
|
437
437
|
}
|
|
438
438
|
frame.emitter.close();
|
|
@@ -483,7 +483,7 @@ export class FilteredArrays {
|
|
|
483
483
|
mapped`if (${this.dialect.condition(entry.present, at)}) {`,
|
|
484
484
|
);
|
|
485
485
|
}
|
|
486
|
-
const take = `${best} = ${entry.node.
|
|
486
|
+
const take = `${best} = ${entry.node.reference};`;
|
|
487
487
|
const rivals = union(before.map((rival) => rival.node))
|
|
488
488
|
.filter((rival) => rival !== entry.node)
|
|
489
489
|
.map((rival) => {
|
|
@@ -511,7 +511,7 @@ export class FilteredArrays {
|
|
|
511
511
|
...rivals
|
|
512
512
|
.filter(({ wins, lines }) => !isFalse(wins) || lines.length > 0)
|
|
513
513
|
.map(({ rival, wins, lines }) => ({
|
|
514
|
-
test: `${best} === ${rival.
|
|
514
|
+
test: `${best} === ${rival.reference}`,
|
|
515
515
|
body: () => {
|
|
516
516
|
frame.emitter.append(lines);
|
|
517
517
|
if (isTrue(wins)) {
|
|
@@ -583,7 +583,7 @@ export class FilteredArrays {
|
|
|
583
583
|
test: fromEnd
|
|
584
584
|
? mapped`${held} === ${position} || ${held} === ${position - nodes.length}`
|
|
585
585
|
: mapped`${held} === ${position}`,
|
|
586
|
-
body: () => frame.emitter.line(`${result} = ${item.
|
|
586
|
+
body: () => frame.emitter.line(`${result} = ${item.reference};`),
|
|
587
587
|
})),
|
|
588
588
|
);
|
|
589
589
|
return settled({
|
|
@@ -1,8 +1,10 @@
|
|
|
1
|
-
import { dirname, join, resolve } from "node:path";
|
|
1
|
+
import { dirname, join, relative, resolve } from "node:path";
|
|
2
2
|
import {
|
|
3
3
|
type Constant,
|
|
4
4
|
type Diagnostic,
|
|
5
5
|
error,
|
|
6
|
+
identityDigest,
|
|
7
|
+
type PlcModule,
|
|
6
8
|
type SourceSpan,
|
|
7
9
|
type TypeId,
|
|
8
10
|
} from "@tsplc/compiler/ir";
|
|
@@ -188,6 +190,8 @@ export const lowerElaboration = (
|
|
|
188
190
|
/** Routines specialized from class methods, by `<entry file>:<routine>`. */
|
|
189
191
|
origins: Map<string, { name: string; instance?: string }>;
|
|
190
192
|
folded: Folded[];
|
|
193
|
+
/** Each referable object's storage path by the id a reference holds, and the fields that hold one. */
|
|
194
|
+
references: NonNullable<PlcModule["references"]>;
|
|
191
195
|
/** The string each member of a literal union's enum stands for, by `<types file>:<enum>`. */
|
|
192
196
|
literals: Map<string, Record<string, string>>;
|
|
193
197
|
} => {
|
|
@@ -196,7 +200,16 @@ export const lowerElaboration = (
|
|
|
196
200
|
const origins = new Map<string, { name: string; instance?: string }>();
|
|
197
201
|
const folded: Folded[] = [];
|
|
198
202
|
const literals = new Map<string, Record<string, string>>();
|
|
199
|
-
const
|
|
203
|
+
const references: { id: number; path: string }[] = [];
|
|
204
|
+
const referenceFields: string[] = [];
|
|
205
|
+
const result = {
|
|
206
|
+
sources,
|
|
207
|
+
diagnostics,
|
|
208
|
+
origins,
|
|
209
|
+
folded,
|
|
210
|
+
literals,
|
|
211
|
+
references: { objects: references, fields: referenceFields },
|
|
212
|
+
};
|
|
200
213
|
const runtime = runtimeSources(program).filter(
|
|
201
214
|
(source) => !source.isDeclarationFile && !inSdk(sdk, source.fileName),
|
|
202
215
|
);
|
|
@@ -229,7 +242,6 @@ export const lowerElaboration = (
|
|
|
229
242
|
/\\/g,
|
|
230
243
|
"/",
|
|
231
244
|
);
|
|
232
|
-
const rootModule = (item: Root) => `${directory}/${item.name}.ts`;
|
|
233
245
|
// Failures statements recorded before one escaped: often its cause, as a skipped declaration's name is then unknown.
|
|
234
246
|
let recorded = (): readonly SpecializeError[] => [];
|
|
235
247
|
|
|
@@ -238,7 +250,8 @@ export const lowerElaboration = (
|
|
|
238
250
|
const graph = captureGraph(entryFile, runtime, checker);
|
|
239
251
|
// Generic classes specialize per instance, through a checker that knows each one's type arguments.
|
|
240
252
|
const generics = new GenericTypes(checker);
|
|
241
|
-
const model = new Model(graph, generics.checker, program, entryFile);
|
|
253
|
+
const model = new Model(graph, generics.checker, program, entryFile, root);
|
|
254
|
+
const rootModule = rootModules(model.roots, directory, root);
|
|
242
255
|
const specializer = new Specializer(
|
|
243
256
|
model,
|
|
244
257
|
generics,
|
|
@@ -344,6 +357,9 @@ export const lowerElaboration = (
|
|
|
344
357
|
for (const { name, members } of specializer.layouts.literalEnums) {
|
|
345
358
|
literals.set(`${typesFile}:${name}`, members);
|
|
346
359
|
}
|
|
360
|
+
const table = specializer.storage.referenceTable();
|
|
361
|
+
references.push(...table.references);
|
|
362
|
+
referenceFields.push(...table.referenceFields);
|
|
347
363
|
for (const item of specializer.storage.folded()) {
|
|
348
364
|
const known = constant(item.value, item.iec);
|
|
349
365
|
if (known) {
|
|
@@ -538,3 +554,25 @@ const findEntry = (
|
|
|
538
554
|
}
|
|
539
555
|
throw new Error(`${source.fileName} exports no function ${name}.`);
|
|
540
556
|
};
|
|
557
|
+
|
|
558
|
+
/**
|
|
559
|
+
* Each root's storage module. Roots in different modules can share a name, up to case, and would
|
|
560
|
+
* then share one module and its list; each of them is qualified by its own module instead.
|
|
561
|
+
*/
|
|
562
|
+
const rootModules = (
|
|
563
|
+
roots: readonly Root[],
|
|
564
|
+
directory: string,
|
|
565
|
+
projectRoot: string,
|
|
566
|
+
): ((item: Root) => string) => {
|
|
567
|
+
const counts = new Map<string, number>();
|
|
568
|
+
for (const item of roots) {
|
|
569
|
+
const key = item.name.toLowerCase();
|
|
570
|
+
counts.set(key, (counts.get(key) ?? 0) + 1);
|
|
571
|
+
}
|
|
572
|
+
return (item) => {
|
|
573
|
+
const shared = (counts.get(item.name.toLowerCase()) ?? 0) > 1;
|
|
574
|
+
const module = relative(projectRoot, item.file).replace(/\\/g, "/");
|
|
575
|
+
const name = shared ? `${item.name}_${identityDigest(module)}` : item.name;
|
|
576
|
+
return `${directory}/${name}.ts`;
|
|
577
|
+
};
|
|
578
|
+
};
|
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { relative } from "node:path";
|
|
2
|
+
import { identityDigest } from "@tsplc/compiler/ir";
|
|
1
3
|
import ts from "typescript";
|
|
2
4
|
import type {
|
|
3
5
|
CapturedGraph,
|
|
@@ -73,6 +75,11 @@ export interface Root {
|
|
|
73
75
|
|
|
74
76
|
export interface ModelNode {
|
|
75
77
|
id: number;
|
|
78
|
+
/**
|
|
79
|
+
* The id a reference to the object holds at runtime: a digest of where setup put it, so an
|
|
80
|
+
* object added elsewhere changes no stored reference across an online change.
|
|
81
|
+
*/
|
|
82
|
+
reference: number;
|
|
76
83
|
captured: CapturedNode;
|
|
77
84
|
/** The declared type where the object is stored; undefined for functions and services. */
|
|
78
85
|
type?: ts.Type;
|
|
@@ -84,14 +91,20 @@ export interface ModelNode {
|
|
|
84
91
|
export class Model {
|
|
85
92
|
readonly nodes: ModelNode[];
|
|
86
93
|
readonly roots: Root[] = [];
|
|
94
|
+
private readonly projectRoot: string;
|
|
87
95
|
|
|
88
96
|
constructor(
|
|
89
97
|
readonly graph: CapturedGraph,
|
|
90
98
|
readonly checker: ts.TypeChecker,
|
|
91
99
|
readonly program: ts.Program,
|
|
92
100
|
entry: string,
|
|
101
|
+
projectRoot: string,
|
|
93
102
|
) {
|
|
94
|
-
this.nodes = graph.nodes.map((captured, id) => ({
|
|
103
|
+
this.nodes = graph.nodes.map((captured, id) => ({
|
|
104
|
+
id,
|
|
105
|
+
reference: id,
|
|
106
|
+
captured,
|
|
107
|
+
}));
|
|
95
108
|
// Dependencies own what they build before the entry module's instances refer to it.
|
|
96
109
|
const ordered = [
|
|
97
110
|
...graph.bindings.filter((binding) => binding.file !== entry),
|
|
@@ -115,6 +128,40 @@ export class Model {
|
|
|
115
128
|
checker.getTypeAtLocation(declaration.name),
|
|
116
129
|
);
|
|
117
130
|
}
|
|
131
|
+
this.projectRoot = projectRoot;
|
|
132
|
+
this.assignReferences();
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
/**
|
|
136
|
+
* Where setup put an object, as generated names and reference ids are made from: its root's
|
|
137
|
+
* module and its path from there. Undefined for an object no root owns.
|
|
138
|
+
*/
|
|
139
|
+
identity(node: ModelNode): string | undefined {
|
|
140
|
+
return (
|
|
141
|
+
node.owner &&
|
|
142
|
+
`${relative(this.projectRoot, node.owner.root.file).replace(/\\/g, "/")}:${tsPath(node.owner)}`
|
|
143
|
+
);
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/** Gives each object setup put somewhere its reference id, from its identity. */
|
|
147
|
+
private assignReferences(): void {
|
|
148
|
+
const taken = new Map<number, ModelNode>();
|
|
149
|
+
for (const node of this.nodes) {
|
|
150
|
+
const identity = this.identity(node);
|
|
151
|
+
if (!identity || !node.owner) {
|
|
152
|
+
continue;
|
|
153
|
+
}
|
|
154
|
+
const reference =
|
|
155
|
+
Number.parseInt(identityDigest(identity), 16) & 0x7fffffff;
|
|
156
|
+
const other = taken.get(reference);
|
|
157
|
+
if (other?.owner) {
|
|
158
|
+
throw new Error(
|
|
159
|
+
`${tsPath(other.owner)} and ${tsPath(node.owner)} would hold the same reference id; rename one of them.`,
|
|
160
|
+
);
|
|
161
|
+
}
|
|
162
|
+
taken.set(reference, node);
|
|
163
|
+
node.reference = reference;
|
|
164
|
+
}
|
|
118
165
|
}
|
|
119
166
|
|
|
120
167
|
/** The object a captured value refers to; undefined for a primitive. */
|
|
@@ -55,7 +55,7 @@ export const referenceIndex = (value: Value): string | Mapped | undefined => {
|
|
|
55
55
|
return value.index;
|
|
56
56
|
}
|
|
57
57
|
if (value.kind === "static" && referable(value.node)) {
|
|
58
|
-
return String(value.node.
|
|
58
|
+
return String(value.node.reference);
|
|
59
59
|
}
|
|
60
60
|
if (value.kind === "const" && value.value === undefined) {
|
|
61
61
|
return "-1";
|
|
@@ -75,9 +75,9 @@ const optionsOf = (value: Value): readonly ModelNode[] => {
|
|
|
75
75
|
const absentOf = (value: Value): boolean =>
|
|
76
76
|
value.kind === "choice" ? value.optional : value.kind === "const";
|
|
77
77
|
|
|
78
|
-
/** Objects without repeats, in the order
|
|
78
|
+
/** Objects without repeats, in the order of their reference ids, so the code over them is the same every build. */
|
|
79
79
|
export const union = (nodes: readonly ModelNode[]): ModelNode[] =>
|
|
80
|
-
[...new Set(nodes)].sort((left, right) => left.
|
|
80
|
+
[...new Set(nodes)].sort((left, right) => left.reference - right.reference);
|
|
81
81
|
|
|
82
82
|
const maybeAbsent = (type: ts.Type): boolean => parts(type).some(isAbsent);
|
|
83
83
|
|
|
@@ -220,7 +220,7 @@ export class References {
|
|
|
220
220
|
return mapped`(${choice.index} === ${other.index})`;
|
|
221
221
|
case "static":
|
|
222
222
|
return choice.options.includes(other.node)
|
|
223
|
-
? mapped`(${choice.index} === ${other.node.
|
|
223
|
+
? mapped`(${choice.index} === ${other.node.reference})`
|
|
224
224
|
: false;
|
|
225
225
|
case "const":
|
|
226
226
|
return other.value === undefined && choice.optional
|
|
@@ -399,7 +399,7 @@ export class References {
|
|
|
399
399
|
arms
|
|
400
400
|
.filter((arm) => arm.lines.length > 0)
|
|
401
401
|
.map((arm) => ({
|
|
402
|
-
test: mapped`${choice.index} === ${arm.option.
|
|
402
|
+
test: mapped`${choice.index} === ${arm.option.reference}`,
|
|
403
403
|
body: () => frame.emitter.append(arm.lines),
|
|
404
404
|
})),
|
|
405
405
|
);
|
|
@@ -479,7 +479,7 @@ export class References {
|
|
|
479
479
|
return constant(undefined);
|
|
480
480
|
}
|
|
481
481
|
const test = (option: ModelNode): Mapped =>
|
|
482
|
-
mapped`${choice.index} === ${option.
|
|
482
|
+
mapped`${choice.index} === ${option.reference}`;
|
|
483
483
|
const known = first.value;
|
|
484
484
|
if (
|
|
485
485
|
known.kind === "const" &&
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
// biome-ignore-all lint/style/noNonNullAssertion: Retain existing non-null assertions during the tooling migration; changing their contracts requires a separate review.
|
|
2
|
+
import { identityDigest } from "@tsplc/compiler/ir";
|
|
2
3
|
import ts from "typescript";
|
|
3
4
|
import { from, joined, type Mapped, mapped } from "../positions";
|
|
4
5
|
import { DialectText } from "./dialect";
|
|
@@ -277,7 +278,7 @@ export class Specializer implements RoutineTable {
|
|
|
277
278
|
referents: this.resultReferents(known),
|
|
278
279
|
};
|
|
279
280
|
}
|
|
280
|
-
const name = this.routineName(declaration, self);
|
|
281
|
+
const name = this.routineName(declaration, self, keys);
|
|
281
282
|
this.specialized.set(key, name);
|
|
282
283
|
if (ts.isArrowFunction(declaration) && !ts.isBlock(declaration.body)) {
|
|
283
284
|
frame.emitter.origin = declaration.body;
|
|
@@ -369,9 +370,15 @@ export class Specializer implements RoutineTable {
|
|
|
369
370
|
);
|
|
370
371
|
}
|
|
371
372
|
|
|
373
|
+
/**
|
|
374
|
+
* A specialized routine's name: its class and method, and for an instance or a known argument a
|
|
375
|
+
* digest of which. Numbering specializations in the order they were made renamed them when an
|
|
376
|
+
* instance was added before, which renamed the routines a job calls, and so its code.
|
|
377
|
+
*/
|
|
372
378
|
private routineName(
|
|
373
379
|
declaration: FunctionLike,
|
|
374
380
|
self: ModelNode | undefined,
|
|
381
|
+
keys: readonly string[],
|
|
375
382
|
): string {
|
|
376
383
|
const own =
|
|
377
384
|
declaration.name && ts.isIdentifier(declaration.name)
|
|
@@ -386,9 +393,16 @@ export class Specializer implements RoutineTable {
|
|
|
386
393
|
: undefined;
|
|
387
394
|
const owner =
|
|
388
395
|
self?.captured.kind === "instance" ? self.captured.name : undefined;
|
|
389
|
-
const
|
|
396
|
+
const named = [owner, own ?? variable ?? "callback"]
|
|
390
397
|
.filter(Boolean)
|
|
391
398
|
.join("_");
|
|
399
|
+
const instance = self && this.model.identity(self);
|
|
400
|
+
const specialized = Boolean(instance) || keys.length > 0;
|
|
401
|
+
// A callback's key holds its source position; a name mustn't move with an edit above it.
|
|
402
|
+
const stable = keys.map((key) => key.replace(/fn:[^,|\]}]*/g, "fn"));
|
|
403
|
+
const base = specialized
|
|
404
|
+
? `${named}_${identityDigest([instance ?? "", ...stable].join("\0"))}`
|
|
405
|
+
: named;
|
|
392
406
|
const name = unusedName(base, (candidate) =>
|
|
393
407
|
this.routineNames.has(candidate),
|
|
394
408
|
);
|
|
@@ -750,7 +764,7 @@ const declarationKey = (declaration: ts.Node): string =>
|
|
|
750
764
|
const valueKey = (value: Value): string => {
|
|
751
765
|
switch (value.kind) {
|
|
752
766
|
case "static":
|
|
753
|
-
return `#${value.node.
|
|
767
|
+
return `#${value.node.reference}`;
|
|
754
768
|
case "const":
|
|
755
769
|
return `=${String(value.value)}`;
|
|
756
770
|
case "function":
|
|
@@ -762,7 +776,7 @@ const valueKey = (value: Value): string => {
|
|
|
762
776
|
case "code":
|
|
763
777
|
return "code";
|
|
764
778
|
case "choice":
|
|
765
|
-
return `ref(${value.options.map((option) => option.
|
|
779
|
+
return `ref(${value.options.map((option) => option.reference).join(",")})${value.optional ? "?" : ""}`;
|
|
766
780
|
case "masked":
|
|
767
781
|
return `some[${value.entries.map((entry) => `${valueKey(entry.item)}:${valueKey(entry.present)}`).join(",")}]${value.order ? `by ${valueKey(value.order)}` : ""}`;
|
|
768
782
|
case "counted":
|