@tsplc/tmp-compiler 0.0.0-stage → 0.6.3
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/LICENSE +21 -0
- package/README.md +41 -2
- package/dist/cli.js +2325 -0
- package/dist/cli.js.map +26 -0
- package/dist/clock.js +11 -0
- package/dist/clock.js.map +11 -0
- package/dist/codesys.js +6563 -0
- package/dist/codesys.js.map +51 -0
- package/dist/collections.js +399 -0
- package/dist/collections.js.map +10 -0
- package/dist/index.js +16198 -0
- package/dist/index.js.map +62 -0
- package/dist/ir.js +3948 -0
- package/dist/ir.js.map +35 -0
- package/dist/retain.js +10 -0
- package/dist/retain.js.map +10 -0
- package/dist/signals.js +115 -0
- package/dist/signals.js.map +10 -0
- package/dist/telemetry.js +121 -0
- package/dist/telemetry.js.map +12 -0
- package/package.json +122 -4
- package/src/codesys/config.ts +50 -0
- package/src/codesys/debug.ts +655 -0
- package/src/codesys/emit.ts +185 -0
- package/src/codesys/endpoints.ts +111 -0
- package/src/codesys/engineering.ts +96 -0
- package/src/codesys/explain/expressions.ts +445 -0
- package/src/codesys/explain/flags.ts +134 -0
- package/src/codesys/explain/parameters.ts +53 -0
- package/src/codesys/explain/rows.ts +182 -0
- package/src/codesys/explain/tables.ts +79 -0
- package/src/codesys/explain/tasks.ts +68 -0
- package/src/codesys/explain/writes.ts +497 -0
- package/src/codesys/explain.ts +149 -0
- package/src/codesys/expressions.ts +100 -0
- package/src/codesys/global-lists.ts +284 -0
- package/src/codesys/global-names.ts +66 -0
- package/src/codesys/http.ts +1090 -0
- package/src/codesys/index.ts +13 -0
- package/src/codesys/instrumentation.ts +574 -0
- package/src/codesys/io-paths.ts +149 -0
- package/src/codesys/loops.ts +101 -0
- package/src/codesys/manifest.ts +684 -0
- package/src/codesys/names.ts +58 -0
- package/src/codesys/numeric.ts +516 -0
- package/src/codesys/plan.ts +688 -0
- package/src/codesys/programs.ts +138 -0
- package/src/codesys/publication.ts +99 -0
- package/src/codesys/required.ts +8 -0
- package/src/codesys/routines.ts +247 -0
- package/src/codesys/scan-clock.ts +103 -0
- package/src/codesys/scheduling.ts +96 -0
- package/src/codesys/service-channels.ts +24 -0
- package/src/codesys/sources.ts +118 -0
- package/src/codesys/st-files.ts +219 -0
- package/src/codesys/statements.ts +409 -0
- package/src/codesys/storage.ts +150 -0
- package/src/codesys/symbols.ts +240 -0
- package/src/codesys/task-access.ts +186 -0
- package/src/codesys/telemetry-settings.ts +19 -0
- package/src/codesys/telemetry.ts +852 -0
- package/src/codesys/types.ts +310 -0
- package/src/codesys/vendor.ts +113 -0
- package/src/frontend/analyzer.ts +779 -0
- package/src/frontend/async.ts +530 -0
- package/src/frontend/blocks.ts +578 -0
- package/src/frontend/configuration.ts +83 -0
- package/src/frontend/const-enums.ts +196 -0
- package/src/frontend/const-functions.ts +204 -0
- package/src/frontend/control-flow.ts +787 -0
- package/src/frontend/cooperative.ts +114 -0
- package/src/frontend/coroutines.ts +1344 -0
- package/src/frontend/dialect-names.ts +104 -0
- package/src/frontend/elaborate/array-searches.ts +224 -0
- package/src/frontend/elaborate/assignments.ts +343 -0
- package/src/frontend/elaborate/calls.ts +1342 -0
- package/src/frontend/elaborate/capture-protocol.ts +237 -0
- package/src/frontend/elaborate/capture.ts +388 -0
- package/src/frontend/elaborate/declarations.ts +124 -0
- package/src/frontend/elaborate/dialect.ts +473 -0
- package/src/frontend/elaborate/expressions.ts +2177 -0
- package/src/frontend/elaborate/filtered-arrays.ts +643 -0
- package/src/frontend/elaborate/frame.ts +145 -0
- package/src/frontend/elaborate/generics.ts +123 -0
- package/src/frontend/elaborate/graph.ts +141 -0
- package/src/frontend/elaborate/imports.ts +105 -0
- package/src/frontend/elaborate/index.ts +851 -0
- package/src/frontend/elaborate/initializers.ts +235 -0
- package/src/frontend/elaborate/iterators.ts +1541 -0
- package/src/frontend/elaborate/layouts.ts +1025 -0
- package/src/frontend/elaborate/model.ts +478 -0
- package/src/frontend/elaborate/names.ts +134 -0
- package/src/frontend/elaborate/reduce.ts +900 -0
- package/src/frontend/elaborate/references.ts +727 -0
- package/src/frontend/elaborate/retention.ts +284 -0
- package/src/frontend/elaborate/specialize.ts +1137 -0
- package/src/frontend/elaborate/statements.ts +1220 -0
- package/src/frontend/elaborate/storage.ts +836 -0
- package/src/frontend/elaborate/time-constructors.ts +34 -0
- package/src/frontend/elaborate/values.ts +200 -0
- package/src/frontend/elaborate/writes.ts +415 -0
- package/src/frontend/expressions.ts +1382 -0
- package/src/frontend/generated-names.ts +95 -0
- package/src/frontend/intrinsics.ts +382 -0
- package/src/frontend/lowering-key.ts +23 -0
- package/src/frontend/module-graph.ts +156 -0
- package/src/frontend/positions.ts +359 -0
- package/src/frontend/promise-chains.ts +872 -0
- package/src/frontend/promises.ts +419 -0
- package/src/frontend/routines.ts +239 -0
- package/src/frontend/sdk.ts +187 -0
- package/src/frontend/services.ts +612 -0
- package/src/frontend/statements.ts +871 -0
- package/src/frontend/tasks.ts +526 -0
- package/src/frontend/telemetry.ts +174 -0
- package/src/frontend/types.ts +1073 -0
- package/src/frontend/typescript.ts +659 -0
- package/src/index.ts +9 -0
- package/src/ir/aggregates.ts +291 -0
- package/src/ir/allocation.ts +96 -0
- package/src/ir/conditions.ts +855 -0
- package/src/ir/core-model.ts +289 -0
- package/src/ir/declarations.ts +281 -0
- package/src/ir/diagnostics.ts +68 -0
- package/src/ir/domains.ts +151 -0
- package/src/ir/fold.ts +279 -0
- package/src/ir/identity.ts +19 -0
- package/src/ir/index.ts +137 -0
- package/src/ir/job-errors.ts +69 -0
- package/src/ir/layouts.ts +211 -0
- package/src/ir/link.ts +302 -0
- package/src/ir/model.ts +394 -0
- package/src/ir/normalization-error.ts +10 -0
- package/src/ir/normalize.ts +52 -0
- package/src/ir/numeric.ts +163 -0
- package/src/ir/operands.ts +160 -0
- package/src/ir/ranges.ts +420 -0
- package/src/ir/routine.ts +1116 -0
- package/src/ir/scalars.ts +453 -0
- package/src/ir/share.ts +790 -0
- package/src/ir/short-circuit.ts +140 -0
- package/src/ir/tables.ts +111 -0
- package/src/ir/temporaries.ts +138 -0
- package/src/ir/types.ts +151 -0
- package/src/project/artifacts.ts +424 -0
- package/src/project/cli.ts +211 -0
- package/src/project/debugger.ts +111 -0
- package/src/project/deployments.ts +387 -0
- package/src/project/flags.ts +14 -0
- package/src/project/git.ts +35 -0
- package/src/project/plant.ts +629 -0
- package/src/project/project-commands.ts +507 -0
- package/src/project/project.ts +559 -0
- package/src/project/release.ts +152 -0
- package/src/project/server-check.ts +54 -0
- package/src/project/server.ts +165 -0
- package/src/project/terminal.ts +45 -0
- package/src/runtime/async.ts +207 -0
- package/src/runtime/launch.ts +59 -0
- package/src/runtime/main.ts +59 -0
- package/src/runtime/missing-file.ts +3 -0
- package/src/runtime/process.ts +177 -0
- package/src/runtime/program.ts +109 -0
- package/src/runtime/retain.ts +108 -0
- package/src/runtime/runtime.ts +324 -0
- package/src/runtime/settings.ts +27 -0
- package/src/runtime/storage.ts +456 -0
- package/src/runtime/symbols.ts +97 -0
- package/src/runtime/telemetry.ts +154 -0
- package/src/runtime/transport.ts +168 -0
- package/stdlib/clock.ts +8 -0
- package/stdlib/collections.ts +534 -0
- package/stdlib/plc-time.ts +2 -0
- package/stdlib/retain.ts +4 -0
- package/stdlib/signals.ts +142 -0
- package/stdlib/telemetry.ts +89 -0
- package/types/async.d.ts +87 -0
- package/types/clock.d.ts +8 -0
- package/types/config.d.ts +2 -0
- package/types/data-types.d.ts +31 -0
- package/types/dialect.d.ts +49 -0
- package/types/globals.d.ts +10 -0
- package/types/index.d.ts +212 -0
- package/types/retain.d.ts +12 -0
- package/types/telemetry.d.ts +47 -0
package/dist/ir.js
ADDED
|
@@ -0,0 +1,3948 @@
|
|
|
1
|
+
// packages/compiler/src/ir/index.ts
|
|
2
|
+
import { nanosecondsPerMillisecond as nanosecondsPerMillisecond2 } from "@tsplc/iec";
|
|
3
|
+
|
|
4
|
+
// packages/compiler/src/ir/aggregates.ts
|
|
5
|
+
import { isComparison as isComparison3 } from "@tsplc/iec/arithmetic";
|
|
6
|
+
|
|
7
|
+
// packages/compiler/src/ir/domains.ts
|
|
8
|
+
import {
|
|
9
|
+
latestCalendarSecond,
|
|
10
|
+
latestTimeNanoseconds,
|
|
11
|
+
nanosecondsPerMillisecond
|
|
12
|
+
} from "@tsplc/iec";
|
|
13
|
+
import { isComparison } from "@tsplc/iec/arithmetic";
|
|
14
|
+
|
|
15
|
+
// packages/compiler/src/ir/numeric.ts
|
|
16
|
+
import { roundFloat } from "@tsplc/iec/arithmetic";
|
|
17
|
+
|
|
18
|
+
// packages/compiler/src/ir/types.ts
|
|
19
|
+
import {
|
|
20
|
+
integerRange as elementaryIntegerRange,
|
|
21
|
+
elementaryTypes
|
|
22
|
+
} from "@tsplc/iec";
|
|
23
|
+
var instancedBlock = (id, types) => {
|
|
24
|
+
const type = types.get(id);
|
|
25
|
+
const element = type?.kind === "array" ? types.get(type.element) : type;
|
|
26
|
+
return element?.kind === "block" ? element : undefined;
|
|
27
|
+
};
|
|
28
|
+
var isValueType = (id, types) => {
|
|
29
|
+
const seen = new Set;
|
|
30
|
+
const valueType = (current) => {
|
|
31
|
+
if (seen.has(current)) {
|
|
32
|
+
return true;
|
|
33
|
+
}
|
|
34
|
+
seen.add(current);
|
|
35
|
+
const type = types.get(current);
|
|
36
|
+
return Boolean(type && type.kind !== "block" && (type.kind !== "record" || type.fields.every((field) => !field.mode && valueType(field.type))) && (type.kind !== "array" || valueType(type.element)));
|
|
37
|
+
};
|
|
38
|
+
return valueType(id);
|
|
39
|
+
};
|
|
40
|
+
var primitiveType = (type) => {
|
|
41
|
+
switch (type.family) {
|
|
42
|
+
case "bool":
|
|
43
|
+
return [{ id: type.name, kind: "bool" }];
|
|
44
|
+
case "integer":
|
|
45
|
+
return [
|
|
46
|
+
{
|
|
47
|
+
id: type.name,
|
|
48
|
+
kind: "integer",
|
|
49
|
+
bits: type.bits,
|
|
50
|
+
signed: type.signed
|
|
51
|
+
}
|
|
52
|
+
];
|
|
53
|
+
case "bits":
|
|
54
|
+
return [{ id: type.name, kind: "bits", bits: type.bits }];
|
|
55
|
+
case "real":
|
|
56
|
+
return [{ id: type.name, kind: "float", bits: type.bits }];
|
|
57
|
+
case "duration":
|
|
58
|
+
return type.bits === 32 ? [{ id: type.name, kind: "duration" }] : [];
|
|
59
|
+
case "date":
|
|
60
|
+
case "timeOfDay":
|
|
61
|
+
case "dateTime":
|
|
62
|
+
return type.bits === 32 ? [{ id: type.name, kind: "calendar", domain: type.family }] : [];
|
|
63
|
+
case "char":
|
|
64
|
+
case "string":
|
|
65
|
+
return [];
|
|
66
|
+
}
|
|
67
|
+
};
|
|
68
|
+
var integerType = (type) => type.kind === "integer" || type.kind === "bits";
|
|
69
|
+
var integerKindRank = (type) => {
|
|
70
|
+
if (type.kind === "bits") {
|
|
71
|
+
return 2;
|
|
72
|
+
}
|
|
73
|
+
return type.signed ? 0 : 1;
|
|
74
|
+
};
|
|
75
|
+
var elementaryPrimitives = elementaryTypes.flatMap(primitiveType);
|
|
76
|
+
var primitiveTypes = [
|
|
77
|
+
...elementaryPrimitives.filter((type) => type.kind === "bool"),
|
|
78
|
+
...elementaryPrimitives.filter(integerType).sort((left, right) => left.bits - right.bits || integerKindRank(left) - integerKindRank(right)),
|
|
79
|
+
...elementaryPrimitives.filter((type) => type.kind !== "bool" && !integerType(type))
|
|
80
|
+
];
|
|
81
|
+
function integerRange(type) {
|
|
82
|
+
return elementaryIntegerRange({
|
|
83
|
+
bits: type.bits,
|
|
84
|
+
signed: type.kind === "integer" && type.signed
|
|
85
|
+
});
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
// packages/compiler/src/ir/numeric.ts
|
|
89
|
+
var lowest = (a, b) => a < b ? a : b;
|
|
90
|
+
var highest = (a, b) => a > b ? a : b;
|
|
91
|
+
var within = (inner, outer) => inner[0] >= outer[0] && inner[1] <= outer[1] && (outer[2] === undefined || !admits(inner, outer[2]));
|
|
92
|
+
var admits = (interval, value) => interval[0] <= value && value <= interval[1] && interval[2] !== value;
|
|
93
|
+
var canonicalInteger = /^(?:0|-?[1-9][0-9]*)$/;
|
|
94
|
+
var floatPrecision = { 32: 24, 64: 53 };
|
|
95
|
+
var exactIntegerLimit = (type) => 1n << BigInt(floatPrecision[type.bits]);
|
|
96
|
+
var exactDecimal = (text, scale) => {
|
|
97
|
+
const match = /^(-?\d+)(?:\.(\d*))?(?:e([+-]?\d+))?$/i.exec(text);
|
|
98
|
+
if (!match) {
|
|
99
|
+
return "malformed";
|
|
100
|
+
}
|
|
101
|
+
const [, whole, fraction = "", exponentText = "0"] = match;
|
|
102
|
+
const exponent = Number(exponentText) - fraction.length;
|
|
103
|
+
if (!Number.isSafeInteger(exponent) || Math.abs(exponent) > 400) {
|
|
104
|
+
return "exponent";
|
|
105
|
+
}
|
|
106
|
+
const digits = BigInt(`${whole}${fraction}`) * scale;
|
|
107
|
+
if (exponent >= 0) {
|
|
108
|
+
return digits * 10n ** BigInt(exponent);
|
|
109
|
+
}
|
|
110
|
+
const divisor = 10n ** BigInt(-exponent);
|
|
111
|
+
return digits % divisor ? "fraction" : digits / divisor;
|
|
112
|
+
};
|
|
113
|
+
var integerLiteralIssues = {
|
|
114
|
+
malformed: "Expected an exact integer literal.",
|
|
115
|
+
exponent: "Integer literal exponent is out of range.",
|
|
116
|
+
fraction: "Integer literals cannot have a fractional part; to hold fractions, annotate the field or variable REAL or LREAL."
|
|
117
|
+
};
|
|
118
|
+
var isRadixLiteral = (text) => /^-?0[xob]/i.test(text);
|
|
119
|
+
var parseInteger = (text) => {
|
|
120
|
+
const clean = text.replaceAll("_", "").replace(/n$/, "");
|
|
121
|
+
if (isRadixLiteral(clean)) {
|
|
122
|
+
return clean.startsWith("-") ? -BigInt(clean.slice(1)) : BigInt(clean);
|
|
123
|
+
}
|
|
124
|
+
const value = exactDecimal(clean, 1n);
|
|
125
|
+
if (typeof value !== "bigint") {
|
|
126
|
+
throw new Error(integerLiteralIssues[value]);
|
|
127
|
+
}
|
|
128
|
+
return value;
|
|
129
|
+
};
|
|
130
|
+
var parseFloatLiteral = (text, type) => {
|
|
131
|
+
const clean = text.replaceAll("_", "");
|
|
132
|
+
const value = isRadixLiteral(clean) ? Number(parseInteger(clean)) : Number(clean);
|
|
133
|
+
return roundFloat(value, type);
|
|
134
|
+
};
|
|
135
|
+
var literalOutsideType = "Literal is outside its PLC type or has the wrong domain.";
|
|
136
|
+
var constantFits = (value, type) => {
|
|
137
|
+
if (type.kind === "bool") {
|
|
138
|
+
return value.kind === "bool";
|
|
139
|
+
}
|
|
140
|
+
if (integerType(type)) {
|
|
141
|
+
return value.kind === "integer" && canonicalInteger.test(value.value) && admits(integerRange(type), BigInt(value.value));
|
|
142
|
+
}
|
|
143
|
+
if (type.kind === "float") {
|
|
144
|
+
return value.kind === "float" && Number.isFinite(value.value) && Object.is(roundFloat(value.value, type), value.value);
|
|
145
|
+
}
|
|
146
|
+
return false;
|
|
147
|
+
};
|
|
148
|
+
var canAssign = (source, destination, value) => {
|
|
149
|
+
if (value) {
|
|
150
|
+
return source.kind === destination.kind && constantFits(value, destination);
|
|
151
|
+
}
|
|
152
|
+
if (source.id === destination.id) {
|
|
153
|
+
return true;
|
|
154
|
+
}
|
|
155
|
+
if (source.kind === "integer" && destination.kind === "integer") {
|
|
156
|
+
return within(integerRange(source), integerRange(destination));
|
|
157
|
+
}
|
|
158
|
+
return source.kind === "float" && destination.kind === "float" && source.bits <= destination.bits;
|
|
159
|
+
};
|
|
160
|
+
var wrappingOperators = new Set([
|
|
161
|
+
"add",
|
|
162
|
+
"subtract",
|
|
163
|
+
"multiply"
|
|
164
|
+
]);
|
|
165
|
+
var wrapsNatively = (expression) => expression.kind === "binary" && !expression.policy && expression.operator !== undefined && wrappingOperators.has(expression.operator);
|
|
166
|
+
|
|
167
|
+
// packages/compiler/src/ir/domains.ts
|
|
168
|
+
var latestDateTime = new Date(Number(latestCalendarSecond) * 1000).toISOString().slice(0, "YYYY-MM-DDTHH:mm:ss".length);
|
|
169
|
+
var latestDate = latestDateTime.slice(0, "YYYY-MM-DD".length);
|
|
170
|
+
var calendarZero = {
|
|
171
|
+
date: "1970-01-01",
|
|
172
|
+
timeOfDay: "00:00:00.000",
|
|
173
|
+
dateTime: "1970-01-01T00:00:00"
|
|
174
|
+
};
|
|
175
|
+
function durationLiteral(text, scaleNanoseconds) {
|
|
176
|
+
const clean = text.replaceAll("_", "").replace(/^(-?)\./, (_, sign) => `${sign}0.`);
|
|
177
|
+
const value = exactDecimal(clean, scaleNanoseconds);
|
|
178
|
+
return typeof value === "bigint" && validDuration(value) ? { kind: "duration", nanoseconds: String(value) } : undefined;
|
|
179
|
+
}
|
|
180
|
+
function validDuration(nanoseconds) {
|
|
181
|
+
return nanoseconds >= 0n && nanoseconds <= latestTimeNanoseconds && nanoseconds % nanosecondsPerMillisecond === 0n;
|
|
182
|
+
}
|
|
183
|
+
function validDate(text) {
|
|
184
|
+
const match = /^(\d{4})-(\d{2})-(\d{2})$/.exec(text);
|
|
185
|
+
if (!match) {
|
|
186
|
+
return false;
|
|
187
|
+
}
|
|
188
|
+
const year = Number(match[1]);
|
|
189
|
+
const month = Number(match[2]);
|
|
190
|
+
const day = Number(match[3]);
|
|
191
|
+
const leap = year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);
|
|
192
|
+
const length = [31, leap ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month - 1];
|
|
193
|
+
return Boolean(length && day >= 1 && day <= length && text >= calendarZero.date && text <= latestDate);
|
|
194
|
+
}
|
|
195
|
+
function validClock(text, milliseconds) {
|
|
196
|
+
const match = (milliseconds ? /^(\d{2}):(\d{2}):(\d{2})\.(\d{3})$/ : /^(\d{2}):(\d{2}):(\d{2})$/).exec(text);
|
|
197
|
+
return Boolean(match && Number(match[1]) < 24 && Number(match[2]) < 60 && Number(match[3]) < 60);
|
|
198
|
+
}
|
|
199
|
+
function calendarLiteral(domain, text) {
|
|
200
|
+
if (domain === "date") {
|
|
201
|
+
return validDate(text) ? { kind: "calendar", value: text } : undefined;
|
|
202
|
+
}
|
|
203
|
+
if (domain === "timeOfDay") {
|
|
204
|
+
const canonical = /^\d{2}:\d{2}:\d{2}$/.test(text) ? `${text}.000` : text;
|
|
205
|
+
return validClock(canonical, true) ? { kind: "calendar", value: canonical } : undefined;
|
|
206
|
+
}
|
|
207
|
+
return text.length === 19 && text[10] === "T" && validDate(text.slice(0, 10)) && validClock(text.slice(11), false) && text <= latestDateTime ? { kind: "calendar", value: text } : undefined;
|
|
208
|
+
}
|
|
209
|
+
function domainConstantFits(value, type) {
|
|
210
|
+
if (type.kind === "duration") {
|
|
211
|
+
return value.kind === "duration" && canonicalInteger.test(value.nanoseconds) && validDuration(BigInt(value.nanoseconds));
|
|
212
|
+
}
|
|
213
|
+
if (type.kind === "calendar" && value.kind === "calendar") {
|
|
214
|
+
const parsed = calendarLiteral(type.domain, value.value);
|
|
215
|
+
return parsed?.kind === "calendar" && parsed.value === value.value;
|
|
216
|
+
}
|
|
217
|
+
return false;
|
|
218
|
+
}
|
|
219
|
+
function domainIssue(value, types) {
|
|
220
|
+
const type = types.get(value.type);
|
|
221
|
+
if (value.kind === "constant") {
|
|
222
|
+
return type && domainConstantFits(value.value, type) ? undefined : "Invalid TIME/calendar constant.";
|
|
223
|
+
}
|
|
224
|
+
if (value.kind === "load" || value.kind === "call" || value.kind === "conditional") {
|
|
225
|
+
return;
|
|
226
|
+
}
|
|
227
|
+
if (value.kind === "binary" && isComparison(value.operator)) {
|
|
228
|
+
return comparedType(value, types, ["duration", "calendar"]) ? undefined : "Time comparisons require matching domains.";
|
|
229
|
+
}
|
|
230
|
+
return "TIME and calendar domains permit storage, typed copies and comparisons; implicit numeric arithmetic is unsupported.";
|
|
231
|
+
}
|
|
232
|
+
function comparedType(value, types, kinds) {
|
|
233
|
+
const left = types.get(value.left.type);
|
|
234
|
+
return value.type === "BOOL" && left && kinds.includes(left.kind) && value.left.type === value.right.type ? left : undefined;
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
// packages/compiler/src/ir/ranges.ts
|
|
238
|
+
import { loopIterations } from "@tsplc/iec/arithmetic";
|
|
239
|
+
|
|
240
|
+
// packages/compiler/src/ir/fold.ts
|
|
241
|
+
import {
|
|
242
|
+
applyIntegerPolicy,
|
|
243
|
+
booleanOperation,
|
|
244
|
+
compare,
|
|
245
|
+
floatArithmetic,
|
|
246
|
+
floatUnary,
|
|
247
|
+
integerArithmetic,
|
|
248
|
+
integerUnary,
|
|
249
|
+
roundFloat as roundFloat2,
|
|
250
|
+
saturateFloat,
|
|
251
|
+
saturateFloatToInteger
|
|
252
|
+
} from "@tsplc/iec/arithmetic";
|
|
253
|
+
|
|
254
|
+
// packages/compiler/src/ir/model.ts
|
|
255
|
+
import {
|
|
256
|
+
comparisonOperatorNames
|
|
257
|
+
} from "@tsplc/iec/arithmetic";
|
|
258
|
+
var isLogicalIo = (variable) => variable.storage === "input" || variable.storage === "output";
|
|
259
|
+
var optionalRecord = {
|
|
260
|
+
prefix: "Optional_",
|
|
261
|
+
has: "has",
|
|
262
|
+
value: "value"
|
|
263
|
+
};
|
|
264
|
+
var comparisonOperators = new Set(comparisonOperatorNames);
|
|
265
|
+
var telemetryOperands = ({
|
|
266
|
+
record,
|
|
267
|
+
properties
|
|
268
|
+
}) => [
|
|
269
|
+
...record.kind === "exception" ? [record.code] : [],
|
|
270
|
+
...properties.flatMap(({ value, length }) => length ? [value, length] : [value])
|
|
271
|
+
];
|
|
272
|
+
var timer = (input, output) => ({
|
|
273
|
+
inputs: [
|
|
274
|
+
[input, "IN", "BOOL"],
|
|
275
|
+
["duration", "PT", "TIME"]
|
|
276
|
+
],
|
|
277
|
+
outputs: [
|
|
278
|
+
[output, "Q", "BOOL"],
|
|
279
|
+
["elapsed", "ET", "TIME"]
|
|
280
|
+
]
|
|
281
|
+
});
|
|
282
|
+
var standardBlocks = {
|
|
283
|
+
OnDelayTimer: { native: "TON", ...timer("enabled", "done") },
|
|
284
|
+
OffDelayTimer: { native: "TOF", ...timer("enabled", "active") },
|
|
285
|
+
PulseTimer: { native: "TP", ...timer("start", "active") },
|
|
286
|
+
RisingEdge: {
|
|
287
|
+
native: "R_TRIG",
|
|
288
|
+
inputs: [["signal", "CLK", "BOOL"]],
|
|
289
|
+
outputs: [["rose", "Q", "BOOL"]]
|
|
290
|
+
},
|
|
291
|
+
FallingEdge: {
|
|
292
|
+
native: "F_TRIG",
|
|
293
|
+
inputs: [["signal", "CLK", "BOOL"]],
|
|
294
|
+
outputs: [["fell", "Q", "BOOL"]]
|
|
295
|
+
},
|
|
296
|
+
UpCounter: {
|
|
297
|
+
native: "CTU",
|
|
298
|
+
inputs: [
|
|
299
|
+
["countUp", "CU", "BOOL"],
|
|
300
|
+
["reset", "RESET", "BOOL"],
|
|
301
|
+
["preset", "PV", "WORD"]
|
|
302
|
+
],
|
|
303
|
+
outputs: [
|
|
304
|
+
["reachedPreset", "Q", "BOOL"],
|
|
305
|
+
["value", "CV", "WORD"]
|
|
306
|
+
]
|
|
307
|
+
},
|
|
308
|
+
DownCounter: {
|
|
309
|
+
native: "CTD",
|
|
310
|
+
inputs: [
|
|
311
|
+
["countDown", "CD", "BOOL"],
|
|
312
|
+
["load", "LOAD", "BOOL"],
|
|
313
|
+
["preset", "PV", "WORD"]
|
|
314
|
+
],
|
|
315
|
+
outputs: [
|
|
316
|
+
["atZero", "Q", "BOOL"],
|
|
317
|
+
["value", "CV", "WORD"]
|
|
318
|
+
]
|
|
319
|
+
},
|
|
320
|
+
UpDownCounter: {
|
|
321
|
+
native: "CTUD",
|
|
322
|
+
inputs: [
|
|
323
|
+
["countUp", "CU", "BOOL"],
|
|
324
|
+
["countDown", "CD", "BOOL"],
|
|
325
|
+
["reset", "RESET", "BOOL"],
|
|
326
|
+
["load", "LOAD", "BOOL"],
|
|
327
|
+
["preset", "PV", "WORD"]
|
|
328
|
+
],
|
|
329
|
+
outputs: [
|
|
330
|
+
["reachedPreset", "QU", "BOOL"],
|
|
331
|
+
["atZero", "QD", "BOOL"],
|
|
332
|
+
["value", "CV", "WORD"]
|
|
333
|
+
]
|
|
334
|
+
},
|
|
335
|
+
Blinker: {
|
|
336
|
+
native: "Util.BLINK",
|
|
337
|
+
inputs: [
|
|
338
|
+
["enabled", "ENABLE", "BOOL"],
|
|
339
|
+
["offTime", "TIMELOW", "TIME"],
|
|
340
|
+
["onTime", "TIMEHIGH", "TIME"]
|
|
341
|
+
],
|
|
342
|
+
outputs: [["on", "OUT", "BOOL"]]
|
|
343
|
+
}
|
|
344
|
+
};
|
|
345
|
+
var httpMethods = ["GET", "POST", "PUT", "PATCH", "DELETE"];
|
|
346
|
+
|
|
347
|
+
// packages/compiler/src/ir/fold.ts
|
|
348
|
+
var fold = (expression, variables, types) => {
|
|
349
|
+
switch (expression.kind) {
|
|
350
|
+
case "constant":
|
|
351
|
+
return expression.value;
|
|
352
|
+
case "copy":
|
|
353
|
+
return fold(expression.operand, variables, types);
|
|
354
|
+
case "length":
|
|
355
|
+
return foldLength(expression, variables, types);
|
|
356
|
+
case "record":
|
|
357
|
+
return foldRecord(expression, variables, types);
|
|
358
|
+
case "array": {
|
|
359
|
+
const items = expression.items.map((item) => fold(item, variables, types));
|
|
360
|
+
return items.every((item) => item !== undefined) ? { kind: "array", items } : undefined;
|
|
361
|
+
}
|
|
362
|
+
case "load": {
|
|
363
|
+
if (expression.place.path.length) {
|
|
364
|
+
return;
|
|
365
|
+
}
|
|
366
|
+
const variable = variables.get(expression.place.root);
|
|
367
|
+
return variable?.storage === "constant" ? variable.initial : undefined;
|
|
368
|
+
}
|
|
369
|
+
case "convert":
|
|
370
|
+
return foldConvert(expression, fold(expression.operand, variables, types), types.get(expression.type));
|
|
371
|
+
case "unary":
|
|
372
|
+
return foldUnary(expression, fold(expression.operand, variables, types), types.get(expression.type));
|
|
373
|
+
case "binary": {
|
|
374
|
+
const left = fold(expression.left, variables, types);
|
|
375
|
+
const right = fold(expression.right, variables, types);
|
|
376
|
+
return left && right ? foldBinary(expression, left, right, types.get(expression.type)) : undefined;
|
|
377
|
+
}
|
|
378
|
+
default:
|
|
379
|
+
return;
|
|
380
|
+
}
|
|
381
|
+
};
|
|
382
|
+
var foldLength = (expression, variables, types) => {
|
|
383
|
+
const type = types.get(expression.operand.type);
|
|
384
|
+
const receiver = expression.operand.kind === "load" ? variables.get(expression.operand.place.root) : undefined;
|
|
385
|
+
const pure = expression.operand.kind === "load" && expression.operand.place.path.every((segment) => segment.kind === "field") && Boolean(receiver && (receiver.initial || isLogicalIo(receiver)));
|
|
386
|
+
if (type?.kind === "array" && (pure || fold(expression.operand, variables, types))) {
|
|
387
|
+
return { kind: "integer", value: String(type.length) };
|
|
388
|
+
}
|
|
389
|
+
return;
|
|
390
|
+
};
|
|
391
|
+
var foldRecord = (expression, variables, types) => {
|
|
392
|
+
const fields = Object.create(null);
|
|
393
|
+
for (const [name, operand] of Object.entries(expression.fields)) {
|
|
394
|
+
const value = fold(operand, variables, types);
|
|
395
|
+
if (!value) {
|
|
396
|
+
return;
|
|
397
|
+
}
|
|
398
|
+
fields[name] = value;
|
|
399
|
+
}
|
|
400
|
+
return { kind: "record", fields };
|
|
401
|
+
};
|
|
402
|
+
var foldConvert = (expression, value, target) => {
|
|
403
|
+
if (value?.kind === "integer" && target && integerType(target)) {
|
|
404
|
+
const integer = BigInt(value.value);
|
|
405
|
+
return {
|
|
406
|
+
kind: "integer",
|
|
407
|
+
value: String(expression.policy === "exact" ? integer : applyIntegerPolicy(integer, target, expression.policy))
|
|
408
|
+
};
|
|
409
|
+
}
|
|
410
|
+
if (value?.kind === "integer" && target?.kind === "float") {
|
|
411
|
+
return { kind: "float", value: roundFloat2(Number(value.value), target) };
|
|
412
|
+
}
|
|
413
|
+
if (value?.kind === "float" && target && integerType(target) && expression.policy === "saturate") {
|
|
414
|
+
return {
|
|
415
|
+
kind: "integer",
|
|
416
|
+
value: String(saturateFloatToInteger(value.value, target))
|
|
417
|
+
};
|
|
418
|
+
}
|
|
419
|
+
if (value?.kind === "float" && target?.kind === "float") {
|
|
420
|
+
return {
|
|
421
|
+
kind: "float",
|
|
422
|
+
value: expression.policy === "saturate" ? saturateFloat(value.value, target) : roundFloat2(value.value, target)
|
|
423
|
+
};
|
|
424
|
+
}
|
|
425
|
+
return;
|
|
426
|
+
};
|
|
427
|
+
var foldUnary = ({ operator }, value, target) => {
|
|
428
|
+
if (value?.kind === "bool") {
|
|
429
|
+
return operator === "not" ? { kind: "bool", value: !value.value } : undefined;
|
|
430
|
+
}
|
|
431
|
+
if (value?.kind === "float") {
|
|
432
|
+
const result = floatUnary(operator, value.value);
|
|
433
|
+
return result === undefined ? undefined : finiteFloat(result, target);
|
|
434
|
+
}
|
|
435
|
+
if (value?.kind === "duration") {
|
|
436
|
+
const result = integerUnary(operator, BigInt(value.nanoseconds));
|
|
437
|
+
return operator === "timeToMilliseconds" && result !== undefined ? { kind: "integer", value: String(result) } : undefined;
|
|
438
|
+
}
|
|
439
|
+
if (value?.kind !== "integer" || operator === "timeToMilliseconds") {
|
|
440
|
+
return;
|
|
441
|
+
}
|
|
442
|
+
const result = integerUnary(operator, BigInt(value.value));
|
|
443
|
+
if (result === undefined) {
|
|
444
|
+
return;
|
|
445
|
+
}
|
|
446
|
+
if (operator !== "bitNot") {
|
|
447
|
+
return { kind: "integer", value: String(result) };
|
|
448
|
+
}
|
|
449
|
+
return target?.kind === "bits" ? {
|
|
450
|
+
kind: "integer",
|
|
451
|
+
value: String(applyIntegerPolicy(result, target, "wrap"))
|
|
452
|
+
} : undefined;
|
|
453
|
+
};
|
|
454
|
+
var ordered = (value) => value.kind !== "bool" && value.kind !== "array" && value.kind !== "record";
|
|
455
|
+
var comparable = (value) => {
|
|
456
|
+
switch (value.kind) {
|
|
457
|
+
case "integer":
|
|
458
|
+
return BigInt(value.value);
|
|
459
|
+
case "duration":
|
|
460
|
+
return BigInt(value.nanoseconds);
|
|
461
|
+
default:
|
|
462
|
+
return value.value;
|
|
463
|
+
}
|
|
464
|
+
};
|
|
465
|
+
var foldBinary = (expression, left, right, target) => {
|
|
466
|
+
if (left.kind === "bool" && right.kind === "bool") {
|
|
467
|
+
const value = booleanOperation(expression.operator, left.value, right.value);
|
|
468
|
+
return value === undefined ? undefined : { kind: "bool", value };
|
|
469
|
+
}
|
|
470
|
+
if (left.kind !== right.kind || !ordered(left) || !ordered(right)) {
|
|
471
|
+
return;
|
|
472
|
+
}
|
|
473
|
+
const compared = compare(expression.operator, comparable(left), comparable(right));
|
|
474
|
+
if (compared !== undefined) {
|
|
475
|
+
return { kind: "bool", value: compared };
|
|
476
|
+
}
|
|
477
|
+
if (left.kind === "integer" && right.kind === "integer") {
|
|
478
|
+
const value = integerArithmetic(expression.operator, BigInt(left.value), BigInt(right.value));
|
|
479
|
+
if (value === undefined) {
|
|
480
|
+
return;
|
|
481
|
+
}
|
|
482
|
+
const wrapped = target && integerType(target) && (expression.policy || target.kind === "bits") ? applyIntegerPolicy(value, target, expression.policy ?? "wrap") : value;
|
|
483
|
+
return { kind: "integer", value: String(wrapped) };
|
|
484
|
+
}
|
|
485
|
+
if (left.kind === "float" && right.kind === "float") {
|
|
486
|
+
const value = floatArithmetic(expression.operator, left.value, right.value);
|
|
487
|
+
if (value === undefined) {
|
|
488
|
+
return;
|
|
489
|
+
}
|
|
490
|
+
return {
|
|
491
|
+
kind: "float",
|
|
492
|
+
value: target?.kind === "float" ? roundFloat2(value, target) : value
|
|
493
|
+
};
|
|
494
|
+
}
|
|
495
|
+
return;
|
|
496
|
+
};
|
|
497
|
+
var finiteFloat = (value, target) => {
|
|
498
|
+
const rounded = target?.kind === "float" ? roundFloat2(value, target) : value;
|
|
499
|
+
return Number.isFinite(rounded) ? { kind: "float", value: rounded } : undefined;
|
|
500
|
+
};
|
|
501
|
+
|
|
502
|
+
// packages/compiler/src/ir/ranges.ts
|
|
503
|
+
var interval = (expression, types, variables, ranges) => factInterval(expression, { types, variables, ranges, facts: [] });
|
|
504
|
+
var factInterval = (expression, context) => {
|
|
505
|
+
const own = ownInterval(expression, context);
|
|
506
|
+
const fact = context.facts.find((known) => sameValue(known.expression, expression));
|
|
507
|
+
if (!own || !fact) {
|
|
508
|
+
return own;
|
|
509
|
+
}
|
|
510
|
+
const met = excluding(excluding([highest(own[0], fact.range[0]), lowest(own[1], fact.range[1])], own[2]), fact.range[2]);
|
|
511
|
+
return met[0] <= met[1] ? met : own;
|
|
512
|
+
};
|
|
513
|
+
var ownInterval = (expression, context) => {
|
|
514
|
+
const { types, variables, ranges } = context;
|
|
515
|
+
const interval = (operand) => factInterval(operand, context);
|
|
516
|
+
if (expression.kind === "length") {
|
|
517
|
+
const array = types.get(expression.operand.type);
|
|
518
|
+
if (array?.kind === "array") {
|
|
519
|
+
return [BigInt(array.length), BigInt(array.length)];
|
|
520
|
+
}
|
|
521
|
+
}
|
|
522
|
+
const value = fold(expression, variables, types);
|
|
523
|
+
if (value?.kind === "integer") {
|
|
524
|
+
return [BigInt(value.value), BigInt(value.value)];
|
|
525
|
+
}
|
|
526
|
+
const type = types.get(expression.type);
|
|
527
|
+
if (!type || !integerType(type)) {
|
|
528
|
+
return;
|
|
529
|
+
}
|
|
530
|
+
if (expression.kind === "load") {
|
|
531
|
+
return ranges.get(expression.place.root) ?? integerRange(type);
|
|
532
|
+
}
|
|
533
|
+
if (expression.kind === "convert") {
|
|
534
|
+
return expression.policy === "exact" ? interval(expression.operand) : integerRange(type);
|
|
535
|
+
}
|
|
536
|
+
if (expression.kind === "unary" && expression.operator === "negate") {
|
|
537
|
+
const operand = interval(expression.operand);
|
|
538
|
+
return operand && [-operand[1], -operand[0]];
|
|
539
|
+
}
|
|
540
|
+
if (expression.kind === "binary" && !expression.policy) {
|
|
541
|
+
const left = interval(expression.left);
|
|
542
|
+
const right = interval(expression.right);
|
|
543
|
+
return left && right && arithmeticInterval(expression.operator, left, right, integerRange(type));
|
|
544
|
+
}
|
|
545
|
+
if (expression.kind === "conditional") {
|
|
546
|
+
const whenTrue = branchInterval(expression, true, context);
|
|
547
|
+
const whenFalse = branchInterval(expression, false, context);
|
|
548
|
+
return whenTrue && whenFalse && [
|
|
549
|
+
lowest(whenTrue[0], whenFalse[0]),
|
|
550
|
+
highest(whenTrue[1], whenFalse[1])
|
|
551
|
+
];
|
|
552
|
+
}
|
|
553
|
+
return integerRange(type);
|
|
554
|
+
};
|
|
555
|
+
var branchInterval = (expression, truth, context) => {
|
|
556
|
+
const { condition } = expression;
|
|
557
|
+
const narrowed = {
|
|
558
|
+
...context,
|
|
559
|
+
ranges: narrowRanges(condition, truth, context.types, context.variables, context.ranges),
|
|
560
|
+
facts: [...context.facts, ...comparisonFacts(condition, truth, context)]
|
|
561
|
+
};
|
|
562
|
+
return factInterval(truth ? expression.then : expression.else, narrowed);
|
|
563
|
+
};
|
|
564
|
+
var flippedComparisons = {
|
|
565
|
+
less: "greater",
|
|
566
|
+
lessEqual: "greaterEqual",
|
|
567
|
+
greater: "less",
|
|
568
|
+
greaterEqual: "lessEqual"
|
|
569
|
+
};
|
|
570
|
+
var comparisonFacts = (condition, truth, context) => {
|
|
571
|
+
if (condition.kind !== "binary") {
|
|
572
|
+
return [];
|
|
573
|
+
}
|
|
574
|
+
const operator = truth ? condition.operator : negatedComparisons[condition.operator];
|
|
575
|
+
const flipped = operator && flippedComparisons[operator];
|
|
576
|
+
if (!operator || !flipped) {
|
|
577
|
+
return [];
|
|
578
|
+
}
|
|
579
|
+
const left = factInterval(condition.left, context);
|
|
580
|
+
const right = factInterval(condition.right, context);
|
|
581
|
+
if (!left || !right) {
|
|
582
|
+
return [];
|
|
583
|
+
}
|
|
584
|
+
const side = (expression, own, comparison, other) => pure(expression) ? [{ expression, range: boundedBy(own, comparison, other) }] : [];
|
|
585
|
+
return [
|
|
586
|
+
...side(condition.left, left, operator, right),
|
|
587
|
+
...side(condition.right, right, flipped, left)
|
|
588
|
+
];
|
|
589
|
+
};
|
|
590
|
+
var boundedBy = (own, comparison, other) => {
|
|
591
|
+
switch (comparison) {
|
|
592
|
+
case "less":
|
|
593
|
+
case "lessEqual":
|
|
594
|
+
return bounded(own, comparison, other[1]);
|
|
595
|
+
default:
|
|
596
|
+
return bounded(own, comparison, other[0]);
|
|
597
|
+
}
|
|
598
|
+
};
|
|
599
|
+
var pure = (expression) => {
|
|
600
|
+
switch (expression.kind) {
|
|
601
|
+
case "constant":
|
|
602
|
+
return true;
|
|
603
|
+
case "load":
|
|
604
|
+
return expression.place.path.every((segment) => segment.kind === "field" || pure(segment.value));
|
|
605
|
+
case "unary":
|
|
606
|
+
case "convert":
|
|
607
|
+
case "length":
|
|
608
|
+
return pure(expression.operand);
|
|
609
|
+
case "binary":
|
|
610
|
+
return pure(expression.left) && pure(expression.right);
|
|
611
|
+
default:
|
|
612
|
+
return false;
|
|
613
|
+
}
|
|
614
|
+
};
|
|
615
|
+
var sameValue = (left, right) => pure(left) && valueKey(left) === valueKey(right);
|
|
616
|
+
var valueKey = (expression) => JSON.stringify(expression, (key, value) => {
|
|
617
|
+
if (key === "span") {
|
|
618
|
+
return;
|
|
619
|
+
}
|
|
620
|
+
return typeof value === "bigint" ? String(value) : value;
|
|
621
|
+
});
|
|
622
|
+
var arithmeticInterval = (operator, left, right, type) => {
|
|
623
|
+
const unwrapped = (result) => within(result, type) ? result : type;
|
|
624
|
+
const corners = (combine, divisor = right) => [
|
|
625
|
+
combine(left[0], divisor[0]),
|
|
626
|
+
combine(left[0], divisor[1]),
|
|
627
|
+
combine(left[1], divisor[0]),
|
|
628
|
+
combine(left[1], divisor[1])
|
|
629
|
+
];
|
|
630
|
+
switch (operator) {
|
|
631
|
+
case "add":
|
|
632
|
+
return unwrapped([left[0] + right[0], left[1] + right[1]]);
|
|
633
|
+
case "subtract":
|
|
634
|
+
return unwrapped([left[0] - right[1], left[1] - right[0]]);
|
|
635
|
+
case "multiply": {
|
|
636
|
+
const products = corners((a, b) => a * b);
|
|
637
|
+
return unwrapped([products.reduce(lowest), products.reduce(highest)]);
|
|
638
|
+
}
|
|
639
|
+
case "divide": {
|
|
640
|
+
if (admits(right, 0n)) {
|
|
641
|
+
return;
|
|
642
|
+
}
|
|
643
|
+
const divisors = right[2] === 0n ? [
|
|
644
|
+
[right[0], -1n],
|
|
645
|
+
[1n, right[1]]
|
|
646
|
+
] : [right];
|
|
647
|
+
const quotients = divisors.flatMap((divisor) => corners((a, b) => a / b, divisor));
|
|
648
|
+
return [quotients.reduce(lowest), quotients.reduce(highest)];
|
|
649
|
+
}
|
|
650
|
+
case "remainder": {
|
|
651
|
+
if (admits(right, 0n)) {
|
|
652
|
+
return;
|
|
653
|
+
}
|
|
654
|
+
const magnitude = (value) => value < 0n ? -value : value;
|
|
655
|
+
const largest = highest(magnitude(right[0]), magnitude(right[1])) - 1n;
|
|
656
|
+
return [left[0] < 0n ? -largest : 0n, left[1] > 0n ? largest : 0n];
|
|
657
|
+
}
|
|
658
|
+
default:
|
|
659
|
+
return type;
|
|
660
|
+
}
|
|
661
|
+
};
|
|
662
|
+
var maxLoopIterations = 1000000n;
|
|
663
|
+
var loopBounds = (start, limit, step, exclusive = false) => {
|
|
664
|
+
const excluded = exclusive ? 1n : 0n;
|
|
665
|
+
const first = step > 0n ? start[0] : start[1];
|
|
666
|
+
const last = step > 0n ? limit[1] - excluded : limit[0] + excluded;
|
|
667
|
+
const count = loopIterations(first, limit[step > 0n ? 1 : 0], exclusive, step);
|
|
668
|
+
const range = first <= last ? [first, last] : [last, first];
|
|
669
|
+
const fixed = start[0] === start[1] && limit[0] === limit[1];
|
|
670
|
+
const terminal = fixed ? first + count * step : (step > 0n ? range[1] : range[0]) + step;
|
|
671
|
+
return { first, last, count, range, terminal };
|
|
672
|
+
};
|
|
673
|
+
var negatedComparisons = {
|
|
674
|
+
less: "greaterEqual",
|
|
675
|
+
lessEqual: "greater",
|
|
676
|
+
greater: "lessEqual",
|
|
677
|
+
greaterEqual: "less",
|
|
678
|
+
equal: "notEqual",
|
|
679
|
+
notEqual: "equal"
|
|
680
|
+
};
|
|
681
|
+
var bounded = (current, operator, value) => {
|
|
682
|
+
const [lower, upper, excluded] = current;
|
|
683
|
+
switch (operator) {
|
|
684
|
+
case "less":
|
|
685
|
+
return excluding([lower, lowest(upper, value - 1n)], excluded);
|
|
686
|
+
case "lessEqual":
|
|
687
|
+
return excluding([lower, lowest(upper, value)], excluded);
|
|
688
|
+
case "greater":
|
|
689
|
+
return excluding([highest(lower, value + 1n), upper], excluded);
|
|
690
|
+
case "greaterEqual":
|
|
691
|
+
return excluding([highest(lower, value), upper], excluded);
|
|
692
|
+
case "equal":
|
|
693
|
+
return excluding([highest(lower, value), lowest(upper, value)], excluded);
|
|
694
|
+
case "notEqual":
|
|
695
|
+
return excluding(current, value);
|
|
696
|
+
default:
|
|
697
|
+
return current;
|
|
698
|
+
}
|
|
699
|
+
};
|
|
700
|
+
var excluding = (range, value) => {
|
|
701
|
+
const [lower, upper, held] = range;
|
|
702
|
+
if (value === undefined || value < lower || value > upper) {
|
|
703
|
+
return range;
|
|
704
|
+
}
|
|
705
|
+
if (value === lower) {
|
|
706
|
+
return excluding([lower + 1n, upper], held);
|
|
707
|
+
}
|
|
708
|
+
if (value === upper) {
|
|
709
|
+
return excluding([lower, upper - 1n], held);
|
|
710
|
+
}
|
|
711
|
+
return [lower, upper, held === undefined || value === 0n ? value : held];
|
|
712
|
+
};
|
|
713
|
+
var narrowRanges = (condition, truth, types, variables, ranges) => {
|
|
714
|
+
const narrowed = new Map(ranges);
|
|
715
|
+
if (condition.kind !== "binary") {
|
|
716
|
+
return narrowed;
|
|
717
|
+
}
|
|
718
|
+
if (condition.operator === "and") {
|
|
719
|
+
return truth ? narrowRanges(condition.right, truth, types, variables, narrowRanges(condition.left, truth, types, variables, ranges)) : narrowed;
|
|
720
|
+
}
|
|
721
|
+
if (condition.left.kind !== "load" || condition.left.place.path.length) {
|
|
722
|
+
return narrowed;
|
|
723
|
+
}
|
|
724
|
+
const root = condition.left.place.root;
|
|
725
|
+
const variable = variables.get(root);
|
|
726
|
+
const type = types.get(condition.left.type);
|
|
727
|
+
const fixed = variable && (variable.storage === "parameter" && !variable.mode || variable.storage === "local" && !variable.mutable);
|
|
728
|
+
const current = ranges.get(root) ?? (fixed && type && integerType(type) ? integerRange(type) : undefined);
|
|
729
|
+
const bound = interval(condition.right, types, variables, ranges);
|
|
730
|
+
if (!current || !bound || bound[0] !== bound[1]) {
|
|
731
|
+
return narrowed;
|
|
732
|
+
}
|
|
733
|
+
const range = bounded(current, truth ? condition.operator : negatedComparisons[condition.operator], bound[0]);
|
|
734
|
+
if (range[0] <= range[1]) {
|
|
735
|
+
narrowed.set(root, range);
|
|
736
|
+
}
|
|
737
|
+
return narrowed;
|
|
738
|
+
};
|
|
739
|
+
|
|
740
|
+
// packages/compiler/src/ir/scalars.ts
|
|
741
|
+
import {
|
|
742
|
+
floatMaximum,
|
|
743
|
+
isComparison as isComparison2,
|
|
744
|
+
isElementary,
|
|
745
|
+
roundFloat as roundFloat3
|
|
746
|
+
} from "@tsplc/iec/arithmetic";
|
|
747
|
+
var scalarKinds = new Set([
|
|
748
|
+
"bool",
|
|
749
|
+
"integer",
|
|
750
|
+
"bits",
|
|
751
|
+
"float"
|
|
752
|
+
]);
|
|
753
|
+
var bitwiseOperators = new Set([
|
|
754
|
+
"bitAnd",
|
|
755
|
+
"bitOr",
|
|
756
|
+
"bitXor",
|
|
757
|
+
"shiftLeft",
|
|
758
|
+
"shiftRight"
|
|
759
|
+
]);
|
|
760
|
+
var scalarIssue = (expression, types, variables, ranges) => {
|
|
761
|
+
const proof = {
|
|
762
|
+
fold: (value) => fold(value, variables, types),
|
|
763
|
+
interval: (value) => interval(value, types, variables, ranges)
|
|
764
|
+
};
|
|
765
|
+
const type = types.get(expression.type);
|
|
766
|
+
if (!type || !scalarKinds.has(type.kind)) {
|
|
767
|
+
return "Unknown scalar expression type.";
|
|
768
|
+
}
|
|
769
|
+
if (expression.kind === "constant") {
|
|
770
|
+
return constantFits(expression.value, type) ? undefined : literalOutsideType;
|
|
771
|
+
}
|
|
772
|
+
if (expression.kind === "load" || expression.kind === "call") {
|
|
773
|
+
return;
|
|
774
|
+
}
|
|
775
|
+
if (expression.kind === "convert" || expression.kind === "unary") {
|
|
776
|
+
const source = types.get(expression.operand.type);
|
|
777
|
+
if (!source) {
|
|
778
|
+
return "Unknown operand type.";
|
|
779
|
+
}
|
|
780
|
+
return expression.kind === "convert" ? conversionIssue(expression, source, type, proof) : unaryIssue(expression, source, type, proof);
|
|
781
|
+
}
|
|
782
|
+
if (expression.kind === "binary") {
|
|
783
|
+
const left = types.get(expression.left.type);
|
|
784
|
+
const right = types.get(expression.right.type);
|
|
785
|
+
if (!left || !right) {
|
|
786
|
+
return "Unknown operand type.";
|
|
787
|
+
}
|
|
788
|
+
return binaryIssue(expression, left, right, type, proof);
|
|
789
|
+
}
|
|
790
|
+
if ("operand" in expression && !types.has(expression.operand.type)) {
|
|
791
|
+
return "Unknown operand type.";
|
|
792
|
+
}
|
|
793
|
+
return "Expression has not been reduced to a scalar operation.";
|
|
794
|
+
};
|
|
795
|
+
var conversionIssue = (expression, source, type, proof) => {
|
|
796
|
+
if (source.kind === "bool" || type.kind === "bool") {
|
|
797
|
+
return "Numeric conversions cannot use BOOL.";
|
|
798
|
+
}
|
|
799
|
+
if (expression.policy === "exact") {
|
|
800
|
+
return exactConversionIssue(expression, source, type, proof);
|
|
801
|
+
}
|
|
802
|
+
if (expression.policy === "saturate" && source.kind === "float" && (type.kind === "float" || integerType(type))) {
|
|
803
|
+
return;
|
|
804
|
+
}
|
|
805
|
+
if (integerType(source) && integerType(type)) {
|
|
806
|
+
return;
|
|
807
|
+
}
|
|
808
|
+
return expression.policy === "saturate" ? "Saturate conversions go to an integer/bit-string type from an integer, bit-string or floating operand, or between floating types." : "Wrap conversions require integer or bit-string operands.";
|
|
809
|
+
};
|
|
810
|
+
var exactConversionIssue = (expression, source, type, proof) => {
|
|
811
|
+
const value = proof.fold(expression.operand);
|
|
812
|
+
if (canAssign(source, type, value) || value && integerType(source) && integerType(type) && constantFits(value, type)) {
|
|
813
|
+
return;
|
|
814
|
+
}
|
|
815
|
+
if (!integerType(source)) {
|
|
816
|
+
return "Exact conversion cannot be proved lossless.";
|
|
817
|
+
}
|
|
818
|
+
if (type.kind === "float" && value?.kind === "integer") {
|
|
819
|
+
const converted = roundFloat3(Number(value.value), type);
|
|
820
|
+
if (Number.isFinite(converted) && Number.isInteger(converted) && BigInt(converted) === BigInt(value.value)) {
|
|
821
|
+
return;
|
|
822
|
+
}
|
|
823
|
+
}
|
|
824
|
+
const proved = proof.interval(expression.operand) ?? integerRange(source);
|
|
825
|
+
if (type.kind === "float") {
|
|
826
|
+
const limit = exactIntegerLimit(type);
|
|
827
|
+
if (within(proved, [-limit, limit])) {
|
|
828
|
+
return;
|
|
829
|
+
}
|
|
830
|
+
}
|
|
831
|
+
if (integerType(type) && within(proved, integerRange(type))) {
|
|
832
|
+
return;
|
|
833
|
+
}
|
|
834
|
+
return "Exact conversion cannot be proved lossless.";
|
|
835
|
+
};
|
|
836
|
+
var unaryIssue = (expression, source, type, proof) => {
|
|
837
|
+
if (isElementary(expression.operator)) {
|
|
838
|
+
if (source.kind !== "float" || source.id !== type.id) {
|
|
839
|
+
return "Elementary functions take and return one floating type.";
|
|
840
|
+
}
|
|
841
|
+
return operandDomainIssue(expression.operator, expression.operand, type, proof);
|
|
842
|
+
}
|
|
843
|
+
switch (expression.operator) {
|
|
844
|
+
case "truncate":
|
|
845
|
+
return source.kind === "float" && source.id === type.id ? undefined : "trunc takes and returns one floating type.";
|
|
846
|
+
case "clock":
|
|
847
|
+
return type.id === "DINT" ? undefined : "now() returns DINT milliseconds.";
|
|
848
|
+
case "timeToMilliseconds":
|
|
849
|
+
return source.id === "TIME" && source.kind === "duration" && type.id === "UDINT" ? undefined : "timeToMilliseconds requires TIME and returns UDINT.";
|
|
850
|
+
case "not":
|
|
851
|
+
return type.kind === "bool" && source.kind === "bool" ? undefined : "Logical negation requires BOOL.";
|
|
852
|
+
case "bitNot":
|
|
853
|
+
return type.kind === "bits" && source.id === type.id ? undefined : "Bitwise complement requires a bit string.";
|
|
854
|
+
case "negate":
|
|
855
|
+
if (source.id !== type.id || !(type.kind === "integer" || type.kind === "float")) {
|
|
856
|
+
return "Numeric negation requires one arithmetic type.";
|
|
857
|
+
}
|
|
858
|
+
return resultIssue(expression, type, proof);
|
|
859
|
+
}
|
|
860
|
+
};
|
|
861
|
+
var binaryIssue = (expression, left, right, type, proof) => {
|
|
862
|
+
if (expression.operator === "and" || expression.operator === "or") {
|
|
863
|
+
return type.kind === "bool" && left.kind === "bool" && right.kind === "bool" ? undefined : "Logical operators require BOOL.";
|
|
864
|
+
}
|
|
865
|
+
if (isComparison2(expression.operator)) {
|
|
866
|
+
return type.kind === "bool" && left.id === right.id && scalarKinds.has(left.kind) && (left.kind !== "bool" || ["equal", "notEqual"].includes(expression.operator)) ? undefined : "Comparison operands need the same PLC domain.";
|
|
867
|
+
}
|
|
868
|
+
if (bitwiseOperators.has(expression.operator)) {
|
|
869
|
+
if (type.kind !== "bits" || left.id !== type.id) {
|
|
870
|
+
return "Bitwise operators require bit strings.";
|
|
871
|
+
}
|
|
872
|
+
if (expression.operator === "shiftLeft" || expression.operator === "shiftRight") {
|
|
873
|
+
const count = proof.fold(expression.right);
|
|
874
|
+
return count?.kind === "integer" && BigInt(count.value) >= 0n && BigInt(count.value) < BigInt(type.bits) ? undefined : "Shift count must be a compile-time integer within the bit width.";
|
|
875
|
+
}
|
|
876
|
+
return right.id === type.id ? undefined : "Bit-string widths differ.";
|
|
877
|
+
}
|
|
878
|
+
if (expression.operator === "power") {
|
|
879
|
+
if (type.kind !== "float" || left.id !== type.id || right.id !== type.id) {
|
|
880
|
+
return "A power takes and returns one floating type.";
|
|
881
|
+
}
|
|
882
|
+
return powerIssue(expression, type, proof);
|
|
883
|
+
}
|
|
884
|
+
if (left.id !== type.id || right.id !== type.id || type.kind !== "integer" && type.kind !== "float") {
|
|
885
|
+
return "Arithmetic operands need one integer or floating type.";
|
|
886
|
+
}
|
|
887
|
+
if (expression.policy) {
|
|
888
|
+
return type.kind === "integer" && wrappingOperators.has(expression.operator) ? undefined : "Explicit arithmetic policies require integer addition, subtraction or multiplication.";
|
|
889
|
+
}
|
|
890
|
+
if ((expression.operator === "divide" || expression.operator === "remainder") && type.kind === "integer") {
|
|
891
|
+
const divisor = proof.interval(expression.right);
|
|
892
|
+
if (!divisor || admits(divisor, 0n)) {
|
|
893
|
+
return "Division requires a proved nonzero divisor.";
|
|
894
|
+
}
|
|
895
|
+
const dividend = proof.interval(expression.left);
|
|
896
|
+
const [minimum] = integerRange(type);
|
|
897
|
+
if (type.signed && dividend && dividend[0] <= minimum && admits(divisor, -1n)) {
|
|
898
|
+
return "Signed minimum divided by -1 cannot be represented.";
|
|
899
|
+
}
|
|
900
|
+
}
|
|
901
|
+
return resultIssue(expression, type, proof);
|
|
902
|
+
};
|
|
903
|
+
var floatBounds = (expression, proof) => {
|
|
904
|
+
const value = proof.fold(expression);
|
|
905
|
+
if (value?.kind === "float") {
|
|
906
|
+
return [value.value, value.value];
|
|
907
|
+
}
|
|
908
|
+
if (value?.kind === "integer") {
|
|
909
|
+
return [Number(value.value), Number(value.value)];
|
|
910
|
+
}
|
|
911
|
+
if (expression.kind === "convert" && expression.policy === "exact") {
|
|
912
|
+
const proved = proof.interval(expression.operand);
|
|
913
|
+
return proved && [Number(proved[0]), Number(proved[1])];
|
|
914
|
+
}
|
|
915
|
+
return;
|
|
916
|
+
};
|
|
917
|
+
var domains = {
|
|
918
|
+
sqrt: { holds: (low) => low >= 0, needs: "not negative" },
|
|
919
|
+
ln: { holds: (low) => low > 0, needs: "greater than zero" },
|
|
920
|
+
log10: { holds: (low) => low > 0, needs: "greater than zero" },
|
|
921
|
+
exp: {
|
|
922
|
+
holds: (_, high, type) => type.kind === "float" && Number.isFinite(roundFloat3(Math.exp(high), type)),
|
|
923
|
+
needs: "small enough for a finite result"
|
|
924
|
+
},
|
|
925
|
+
asin: {
|
|
926
|
+
holds: (low, high) => low >= -1 && high <= 1,
|
|
927
|
+
needs: "between -1 and 1"
|
|
928
|
+
},
|
|
929
|
+
acos: {
|
|
930
|
+
holds: (low, high) => low >= -1 && high <= 1,
|
|
931
|
+
needs: "between -1 and 1"
|
|
932
|
+
},
|
|
933
|
+
sin: undefined,
|
|
934
|
+
cos: undefined,
|
|
935
|
+
tan: undefined,
|
|
936
|
+
atan: undefined
|
|
937
|
+
};
|
|
938
|
+
var operandDomainIssue = (operator, operand, type, proof) => {
|
|
939
|
+
const domain = domains[operator];
|
|
940
|
+
if (!domain) {
|
|
941
|
+
return;
|
|
942
|
+
}
|
|
943
|
+
const bounds = floatBounds(operand, proof);
|
|
944
|
+
if (bounds && domain.holds(bounds[0], bounds[1], type)) {
|
|
945
|
+
return;
|
|
946
|
+
}
|
|
947
|
+
return `${operator} needs its operand proved ${domain.needs}, as a constant or an integer converted exactly is.`;
|
|
948
|
+
};
|
|
949
|
+
var powerIssue = (expression, type, proof) => {
|
|
950
|
+
const folded = proof.fold(expression);
|
|
951
|
+
if (folded) {
|
|
952
|
+
return constantFits(folded, type) ? undefined : "Floating result is not finite or representable.";
|
|
953
|
+
}
|
|
954
|
+
const exponent = proof.fold(expression.right);
|
|
955
|
+
const base = floatBounds(expression.left, proof);
|
|
956
|
+
if (exponent?.kind !== "float" || !base || type.kind !== "float") {
|
|
957
|
+
return "A power needs a constant exponent and a base proved within bounds, as a constant or an integer converted exactly is.";
|
|
958
|
+
}
|
|
959
|
+
const [low, high] = base;
|
|
960
|
+
if (!Number.isInteger(exponent.value) && low < 0) {
|
|
961
|
+
return "A fractional power needs its base proved not negative.";
|
|
962
|
+
}
|
|
963
|
+
if (exponent.value < 0 && low <= 0 && high >= 0) {
|
|
964
|
+
return "A negative power needs its base proved not zero.";
|
|
965
|
+
}
|
|
966
|
+
const magnitudes = [Math.abs(low), Math.abs(high)];
|
|
967
|
+
const largest = exponent.value >= 0 ? Math.max(...magnitudes) ** exponent.value : Math.min(...magnitudes) ** exponent.value;
|
|
968
|
+
return Number.isFinite(roundFloat3(largest, type)) ? undefined : "The power may not be finite.";
|
|
969
|
+
};
|
|
970
|
+
var resultIssue = (expression, type, proof) => {
|
|
971
|
+
if (integerType(type)) {
|
|
972
|
+
const result = proof.interval(expression);
|
|
973
|
+
if (!(wrapsNatively(expression) && !proof.fold(expression)) && (!result || !within(result, integerRange(type)))) {
|
|
974
|
+
return "Arithmetic may overflow; widen the result or use an explicit wrap/saturate operation.";
|
|
975
|
+
}
|
|
976
|
+
return;
|
|
977
|
+
}
|
|
978
|
+
if (type.kind !== "float") {
|
|
979
|
+
return;
|
|
980
|
+
}
|
|
981
|
+
const result = proof.fold(expression);
|
|
982
|
+
if (result) {
|
|
983
|
+
return constantFits(result, type) ? undefined : "Floating result is not finite or representable.";
|
|
984
|
+
}
|
|
985
|
+
if (expression.kind === "unary") {
|
|
986
|
+
return;
|
|
987
|
+
}
|
|
988
|
+
const lhs = proof.fold(expression.left);
|
|
989
|
+
const rhs = proof.fold(expression.right);
|
|
990
|
+
if (["add", "subtract"].includes(expression.operator) && (lhs?.kind === "float" || rhs?.kind === "float")) {
|
|
991
|
+
const maximum = floatMaximum(type);
|
|
992
|
+
const finite = [-maximum, maximum].every((endpoint) => {
|
|
993
|
+
const a = lhs?.kind === "float" ? lhs.value : endpoint;
|
|
994
|
+
const b = rhs?.kind === "float" ? rhs.value : endpoint;
|
|
995
|
+
const value = expression.operator === "add" ? a + b : a - b;
|
|
996
|
+
return Number.isFinite(roundFloat3(value, type));
|
|
997
|
+
});
|
|
998
|
+
if (finite) {
|
|
999
|
+
return;
|
|
1000
|
+
}
|
|
1001
|
+
}
|
|
1002
|
+
if (rhs?.kind === "float" && rhs.value === 1 && ["multiply", "divide"].includes(expression.operator)) {
|
|
1003
|
+
return;
|
|
1004
|
+
}
|
|
1005
|
+
return "Floating arithmetic must prove a finite result.";
|
|
1006
|
+
};
|
|
1007
|
+
|
|
1008
|
+
// packages/compiler/src/ir/core-model.ts
|
|
1009
|
+
var wholeAssign = (item, root) => item?.kind === "assign" && item.root === root && !item.path?.length;
|
|
1010
|
+
var nestedBodies = (item) => {
|
|
1011
|
+
if (item.kind === "if") {
|
|
1012
|
+
return [item.then, item.else];
|
|
1013
|
+
}
|
|
1014
|
+
if (item.kind === "switch") {
|
|
1015
|
+
return [...item.cases.map((branch) => branch.body), item.fallback];
|
|
1016
|
+
}
|
|
1017
|
+
if (item.kind === "for") {
|
|
1018
|
+
return [item.body];
|
|
1019
|
+
}
|
|
1020
|
+
return [];
|
|
1021
|
+
};
|
|
1022
|
+
var mapBodies = (item, map) => {
|
|
1023
|
+
switch (item.kind) {
|
|
1024
|
+
case "if":
|
|
1025
|
+
return { ...item, then: map(item.then), else: map(item.else) };
|
|
1026
|
+
case "switch":
|
|
1027
|
+
return {
|
|
1028
|
+
...item,
|
|
1029
|
+
cases: item.cases.map((branch) => ({
|
|
1030
|
+
...branch,
|
|
1031
|
+
body: map(branch.body)
|
|
1032
|
+
})),
|
|
1033
|
+
fallback: map(item.fallback)
|
|
1034
|
+
};
|
|
1035
|
+
case "for":
|
|
1036
|
+
return { ...item, body: map(item.body) };
|
|
1037
|
+
default:
|
|
1038
|
+
return item;
|
|
1039
|
+
}
|
|
1040
|
+
};
|
|
1041
|
+
var directWrites = (item) => {
|
|
1042
|
+
if (item.kind === "assign") {
|
|
1043
|
+
return [item.root];
|
|
1044
|
+
}
|
|
1045
|
+
if (item.kind === "for") {
|
|
1046
|
+
return [item.counter];
|
|
1047
|
+
}
|
|
1048
|
+
if (item.kind === "invoke") {
|
|
1049
|
+
return [
|
|
1050
|
+
...item.destination ? [item.destination] : [],
|
|
1051
|
+
...item.arguments.flatMap((argument) => argument.kind === "borrow" ? [argument.place.root] : [])
|
|
1052
|
+
];
|
|
1053
|
+
}
|
|
1054
|
+
if (item.kind === "blockUpdate") {
|
|
1055
|
+
return Object.values(item.inputs).flatMap((input) => input.kind === "borrow" ? [input.place.root] : []);
|
|
1056
|
+
}
|
|
1057
|
+
return [];
|
|
1058
|
+
};
|
|
1059
|
+
var calledRoutine = (item, variableOf, types) => {
|
|
1060
|
+
if (item.kind === "invoke") {
|
|
1061
|
+
return item.function;
|
|
1062
|
+
}
|
|
1063
|
+
if (item.kind !== "blockUpdate") {
|
|
1064
|
+
return;
|
|
1065
|
+
}
|
|
1066
|
+
const variable = variableOf(item.instance);
|
|
1067
|
+
return variable && instancedBlock(variable.type, types)?.block;
|
|
1068
|
+
};
|
|
1069
|
+
var verified = Symbol("verified core");
|
|
1070
|
+
var verifiedModules = new WeakSet;
|
|
1071
|
+
function isVerifiedCore(value) {
|
|
1072
|
+
return typeof value === "object" && value !== null && verifiedModules.has(value);
|
|
1073
|
+
}
|
|
1074
|
+
function freeze(value) {
|
|
1075
|
+
if (typeof value !== "object" || value === null || Object.isFrozen(value)) {
|
|
1076
|
+
return;
|
|
1077
|
+
}
|
|
1078
|
+
for (const child of Object.values(value)) {
|
|
1079
|
+
freeze(child);
|
|
1080
|
+
}
|
|
1081
|
+
Object.freeze(value);
|
|
1082
|
+
}
|
|
1083
|
+
function admitCore(core) {
|
|
1084
|
+
freeze(core);
|
|
1085
|
+
verifiedModules.add(core);
|
|
1086
|
+
return core;
|
|
1087
|
+
}
|
|
1088
|
+
function isBlockRoutine(routine) {
|
|
1089
|
+
return "inputs" in routine;
|
|
1090
|
+
}
|
|
1091
|
+
var instanceFields = (block) => [...block.inputs, ...block.outputs, ...block.state];
|
|
1092
|
+
var routineVariables = (routine) => isBlockRoutine(routine) ? [...instanceFields(routine), ...routine.locals] : [...routine.parameters, ...routine.locals];
|
|
1093
|
+
var temporaryPrefix = (routine) => `${routine}:temporary:`;
|
|
1094
|
+
var temporaryId = (routine, index) => `${temporaryPrefix(routine)}${index}`;
|
|
1095
|
+
function isTemporary(routine, variable) {
|
|
1096
|
+
const prefix = temporaryPrefix(routine);
|
|
1097
|
+
return variable.storage === "local" && variable.id.startsWith(prefix) && /^\d+$/.test(variable.id.slice(prefix.length));
|
|
1098
|
+
}
|
|
1099
|
+
var constantIndex = (expression) => expression.kind === "constant" && expression.value?.kind === "integer" ? Number(expression.value.value) : undefined;
|
|
1100
|
+
|
|
1101
|
+
// packages/compiler/src/ir/tables.ts
|
|
1102
|
+
var lookup = (table, id, kind) => {
|
|
1103
|
+
const entry = table.get(id);
|
|
1104
|
+
if (entry === undefined) {
|
|
1105
|
+
throw new Error(`Unknown ${kind} ${String(id)}.`);
|
|
1106
|
+
}
|
|
1107
|
+
return entry;
|
|
1108
|
+
};
|
|
1109
|
+
var built = new WeakMap;
|
|
1110
|
+
var buildTables = (core) => {
|
|
1111
|
+
const types = new Map(core.types.map((type) => [type.id, type]));
|
|
1112
|
+
const functions = new Map(core.functions.map((fn) => [fn.id, fn]));
|
|
1113
|
+
const blocks = new Map(core.blocks.map((block) => [block.id, block]));
|
|
1114
|
+
const variables = new Map([
|
|
1115
|
+
...core.variables,
|
|
1116
|
+
...core.functions.flatMap(routineVariables),
|
|
1117
|
+
...core.blocks.flatMap(routineVariables)
|
|
1118
|
+
].map((variable) => [variable.id, variable]));
|
|
1119
|
+
const functionOf = (id) => lookup(functions, id, "function");
|
|
1120
|
+
const blockOf = (id) => lookup(blocks, id, "block");
|
|
1121
|
+
const variableOf = (id) => lookup(variables, id, "variable");
|
|
1122
|
+
return {
|
|
1123
|
+
types,
|
|
1124
|
+
functions,
|
|
1125
|
+
blocks,
|
|
1126
|
+
variables,
|
|
1127
|
+
typeOf: (id) => lookup(types, id, "type"),
|
|
1128
|
+
functionOf,
|
|
1129
|
+
blockOf,
|
|
1130
|
+
variableOf,
|
|
1131
|
+
calledRoutineOf: (item) => {
|
|
1132
|
+
const called = calledRoutine(item, variableOf, types);
|
|
1133
|
+
if (called === undefined) {
|
|
1134
|
+
return;
|
|
1135
|
+
}
|
|
1136
|
+
return item.kind === "invoke" ? functionOf(called) : blockOf(called);
|
|
1137
|
+
},
|
|
1138
|
+
updatedBlock: (item) => {
|
|
1139
|
+
const called = calledRoutine(item, variableOf, types);
|
|
1140
|
+
if (called === undefined) {
|
|
1141
|
+
throw new Error(`${item.instance} is not a block instance.`);
|
|
1142
|
+
}
|
|
1143
|
+
return blockOf(called);
|
|
1144
|
+
},
|
|
1145
|
+
placeType: (rootType, path) => path.reduce((type, segment) => {
|
|
1146
|
+
if (segment.kind === "field" && type?.kind === "record") {
|
|
1147
|
+
const field = type.fields.find((candidate) => candidate.name === segment.name);
|
|
1148
|
+
return field && types.get(field.type);
|
|
1149
|
+
}
|
|
1150
|
+
if (segment.kind === "index" && type?.kind === "array") {
|
|
1151
|
+
return types.get(type.element);
|
|
1152
|
+
}
|
|
1153
|
+
return;
|
|
1154
|
+
}, types.get(rootType))
|
|
1155
|
+
};
|
|
1156
|
+
};
|
|
1157
|
+
var coreTables = (core) => {
|
|
1158
|
+
const known = built.get(core);
|
|
1159
|
+
if (known) {
|
|
1160
|
+
return known;
|
|
1161
|
+
}
|
|
1162
|
+
const tables = buildTables(core);
|
|
1163
|
+
built.set(core, tables);
|
|
1164
|
+
return tables;
|
|
1165
|
+
};
|
|
1166
|
+
|
|
1167
|
+
// packages/compiler/src/ir/aggregates.ts
|
|
1168
|
+
function aggregate(type) {
|
|
1169
|
+
return type?.kind === "record" || type?.kind === "array";
|
|
1170
|
+
}
|
|
1171
|
+
function valueFits(value, type, types) {
|
|
1172
|
+
if (type.kind === "duration" || type.kind === "calendar") {
|
|
1173
|
+
return domainConstantFits(value, type);
|
|
1174
|
+
}
|
|
1175
|
+
if (type.kind === "enum") {
|
|
1176
|
+
return value.kind === "integer" && type.members.some((member) => member.value === value.value);
|
|
1177
|
+
}
|
|
1178
|
+
if (type.kind === "string") {
|
|
1179
|
+
return value.kind === "string" && !value.value.includes("\x00") && (type.encoding === "utf8" ? new TextEncoder().encode(value.value).length <= type.capacity : value.value.length <= type.capacity);
|
|
1180
|
+
}
|
|
1181
|
+
if (type.kind === "array") {
|
|
1182
|
+
return value.kind === "array" && value.items.length === type.length && value.items.every((item) => valueFits(item, lookup(types, type.element, "type"), types));
|
|
1183
|
+
}
|
|
1184
|
+
if (type.kind === "record") {
|
|
1185
|
+
return value.kind === "record" && Object.keys(value.fields).length === type.fields.length && type.fields.every((field) => {
|
|
1186
|
+
const fieldValue = Object.hasOwn(value.fields, field.name) ? value.fields[field.name] : undefined;
|
|
1187
|
+
return fieldValue !== undefined && valueFits(fieldValue, lookup(types, field.type, "type"), types);
|
|
1188
|
+
});
|
|
1189
|
+
}
|
|
1190
|
+
return constantFits(value, type);
|
|
1191
|
+
}
|
|
1192
|
+
function defaultValue(typeId, types) {
|
|
1193
|
+
const type = types.get(typeId);
|
|
1194
|
+
if (!type) {
|
|
1195
|
+
throw new Error("Unknown default-value type");
|
|
1196
|
+
}
|
|
1197
|
+
if (type.kind === "bool") {
|
|
1198
|
+
return { kind: "bool", value: false };
|
|
1199
|
+
}
|
|
1200
|
+
if (type.kind === "float") {
|
|
1201
|
+
return { kind: "float", value: 0 };
|
|
1202
|
+
}
|
|
1203
|
+
if (type.kind === "string") {
|
|
1204
|
+
return { kind: "string", value: "" };
|
|
1205
|
+
}
|
|
1206
|
+
if (type.kind === "enum") {
|
|
1207
|
+
const member = type.members.find((item) => item.value === "0") ?? type.members[0];
|
|
1208
|
+
if (!member) {
|
|
1209
|
+
throw new Error(`Enum ${type.id} has no members.`);
|
|
1210
|
+
}
|
|
1211
|
+
return { kind: "integer", value: member.value };
|
|
1212
|
+
}
|
|
1213
|
+
if (type.kind === "array") {
|
|
1214
|
+
return {
|
|
1215
|
+
kind: "array",
|
|
1216
|
+
items: Array.from({ length: type.length }, () => defaultValue(type.element, types))
|
|
1217
|
+
};
|
|
1218
|
+
}
|
|
1219
|
+
if (type.kind === "record") {
|
|
1220
|
+
return {
|
|
1221
|
+
kind: "record",
|
|
1222
|
+
fields: Object.fromEntries(type.fields.map((field) => [
|
|
1223
|
+
field.name,
|
|
1224
|
+
defaultValue(field.type, types)
|
|
1225
|
+
]))
|
|
1226
|
+
};
|
|
1227
|
+
}
|
|
1228
|
+
if (type.kind === "duration") {
|
|
1229
|
+
return { kind: "duration", nanoseconds: "0" };
|
|
1230
|
+
}
|
|
1231
|
+
if (type.kind === "calendar") {
|
|
1232
|
+
return { kind: "calendar", value: calendarZero[type.domain] };
|
|
1233
|
+
}
|
|
1234
|
+
if (type.kind === "integer" || type.kind === "bits") {
|
|
1235
|
+
return { kind: "integer", value: "0" };
|
|
1236
|
+
}
|
|
1237
|
+
throw new Error("Unsupported default-value type");
|
|
1238
|
+
}
|
|
1239
|
+
function placeType(place, types, variables, ranges, writable = false) {
|
|
1240
|
+
const root = variables.get(place.root);
|
|
1241
|
+
if (!root) {
|
|
1242
|
+
return { issue: "Unknown storage root." };
|
|
1243
|
+
}
|
|
1244
|
+
if (writable && (root.storage === "input" || root.storage === "constant" || root.storage === "blockOutput" || root.storage === "parameter" && root.mode !== "inOut" || !place.path.length && !root.mutable)) {
|
|
1245
|
+
return {
|
|
1246
|
+
issue: "This storage is read-only here: copy it into a let and change the copy."
|
|
1247
|
+
};
|
|
1248
|
+
}
|
|
1249
|
+
return place.path.reduce((walk, segment) => ("issue" in walk) ? walk : segmentType(walk.type, segment, types, variables, ranges, writable), { type: root.type });
|
|
1250
|
+
}
|
|
1251
|
+
function segmentType(id, segment, types, variables, ranges, writable) {
|
|
1252
|
+
const type = types.get(id);
|
|
1253
|
+
if (segment.kind === "field") {
|
|
1254
|
+
if (type?.kind === "block" && segment.name === "out" && type.output) {
|
|
1255
|
+
return writable ? { issue: "Function block output views are read-only." } : { type: type.output };
|
|
1256
|
+
}
|
|
1257
|
+
if (type?.kind !== "record") {
|
|
1258
|
+
return { issue: "Field access requires a record." };
|
|
1259
|
+
}
|
|
1260
|
+
const field = type.fields.find((field) => field.name === segment.name);
|
|
1261
|
+
if (!field) {
|
|
1262
|
+
return { issue: "Unknown record field." };
|
|
1263
|
+
}
|
|
1264
|
+
if (writable && field.readonly) {
|
|
1265
|
+
return { issue: "This field is read-only." };
|
|
1266
|
+
}
|
|
1267
|
+
return { type: field.type };
|
|
1268
|
+
}
|
|
1269
|
+
if (type?.kind !== "array") {
|
|
1270
|
+
return { issue: "Index access requires a fixed array." };
|
|
1271
|
+
}
|
|
1272
|
+
if (type.index && segment.value.type === type.index) {
|
|
1273
|
+
return { type: type.element };
|
|
1274
|
+
}
|
|
1275
|
+
const indexType = types.get(segment.value.type);
|
|
1276
|
+
const bounds = interval(segment.value, types, variables, ranges);
|
|
1277
|
+
if (indexType?.kind !== "integer" || !bounds || bounds[0] < BigInt(type.lowerBound) || bounds[1] >= BigInt(type.lowerBound + type.length)) {
|
|
1278
|
+
return { issue: "Array index must be proved within the declared bounds." };
|
|
1279
|
+
}
|
|
1280
|
+
return { type: type.element };
|
|
1281
|
+
}
|
|
1282
|
+
function aggregateIssue(value, types) {
|
|
1283
|
+
const type = types.get(value.type);
|
|
1284
|
+
if (!type) {
|
|
1285
|
+
return "Unknown expression type.";
|
|
1286
|
+
}
|
|
1287
|
+
if (value.kind === "constant") {
|
|
1288
|
+
return valueFits(value.value, type, types) ? undefined : "Constant does not fit its closed PLC layout.";
|
|
1289
|
+
}
|
|
1290
|
+
if (value.kind === "record") {
|
|
1291
|
+
return type.kind === "record" && Object.keys(value.fields).length === type.fields.length && type.fields.every((field) => Object.hasOwn(value.fields, field.name) && value.fields[field.name]?.type === field.type) ? undefined : "Record expression differs from its layout.";
|
|
1292
|
+
}
|
|
1293
|
+
if (value.kind === "array") {
|
|
1294
|
+
return type.kind === "array" && value.items.length === type.length && value.items.every((item) => item.type === type.element) ? undefined : "Array expression differs from its layout.";
|
|
1295
|
+
}
|
|
1296
|
+
if (value.kind === "copy") {
|
|
1297
|
+
return aggregate(type) && value.operand.type === value.type ? undefined : "Copy requires one matching fixed aggregate.";
|
|
1298
|
+
}
|
|
1299
|
+
if (value.kind === "convert") {
|
|
1300
|
+
const source = types.get(value.operand.type);
|
|
1301
|
+
return type.kind === "string" && source?.kind === "string" && source.encoding === type.encoding && source.capacity <= type.capacity && value.policy === "exact" ? undefined : "Unsupported aggregate/domain conversion.";
|
|
1302
|
+
}
|
|
1303
|
+
if (value.kind === "load" || value.kind === "call" || value.kind === "conditional") {
|
|
1304
|
+
return;
|
|
1305
|
+
}
|
|
1306
|
+
if (value.kind === "binary" && isComparison3(value.operator)) {
|
|
1307
|
+
const compared = comparedType(value, types, ["enum", "string"]);
|
|
1308
|
+
return compared && (compared.kind !== "enum" || ["equal", "notEqual"].includes(value.operator)) ? undefined : "Comparison requires compatible scalar domains; object identity is unsupported.";
|
|
1309
|
+
}
|
|
1310
|
+
return "Operation is unsupported for this PLC domain.";
|
|
1311
|
+
}
|
|
1312
|
+
function expressionIssue(value, types, variables, ranges) {
|
|
1313
|
+
const kinds = [
|
|
1314
|
+
value.type,
|
|
1315
|
+
...value.kind === "binary" ? [value.left.type] : []
|
|
1316
|
+
].map((id) => types.get(id)?.kind ?? "");
|
|
1317
|
+
if (kinds.some((kind) => ["duration", "calendar"].includes(kind))) {
|
|
1318
|
+
return domainIssue(value, types);
|
|
1319
|
+
}
|
|
1320
|
+
if (["copy", "record", "array"].includes(value.kind) || kinds.some((kind) => ["record", "array", "enum", "string"].includes(kind))) {
|
|
1321
|
+
return aggregateIssue(value, types);
|
|
1322
|
+
}
|
|
1323
|
+
return scalarIssue(value, types, variables, ranges);
|
|
1324
|
+
}
|
|
1325
|
+
// packages/compiler/src/ir/short-circuit.ts
|
|
1326
|
+
var store = (result, value, span) => ({ kind: "assign", root: result.root, value, span });
|
|
1327
|
+
var lowerLogical = ({
|
|
1328
|
+
operator,
|
|
1329
|
+
result,
|
|
1330
|
+
left,
|
|
1331
|
+
right,
|
|
1332
|
+
span
|
|
1333
|
+
}) => {
|
|
1334
|
+
const tested = {
|
|
1335
|
+
kind: "load",
|
|
1336
|
+
root: result.root,
|
|
1337
|
+
type: result.type,
|
|
1338
|
+
span
|
|
1339
|
+
};
|
|
1340
|
+
return [
|
|
1341
|
+
store(result, left, span),
|
|
1342
|
+
{
|
|
1343
|
+
kind: "if",
|
|
1344
|
+
condition: operator === "and" ? tested : {
|
|
1345
|
+
kind: "unary",
|
|
1346
|
+
operator: "not",
|
|
1347
|
+
operand: tested,
|
|
1348
|
+
type: "BOOL",
|
|
1349
|
+
span
|
|
1350
|
+
},
|
|
1351
|
+
then: [...right.statements, store(result, right.value, span)],
|
|
1352
|
+
else: [],
|
|
1353
|
+
span
|
|
1354
|
+
}
|
|
1355
|
+
];
|
|
1356
|
+
};
|
|
1357
|
+
var loweredLogical = (item, next) => {
|
|
1358
|
+
if (item.kind !== "assign" || item.path?.length || next?.kind !== "if" || next.else.length) {
|
|
1359
|
+
return;
|
|
1360
|
+
}
|
|
1361
|
+
const { condition } = next;
|
|
1362
|
+
const negated = condition.kind === "unary" && condition.operator === "not";
|
|
1363
|
+
const tested = negated ? condition.operand : condition;
|
|
1364
|
+
const right = next.then.at(-1);
|
|
1365
|
+
if (tested.kind !== "load" || tested.path?.length || tested.root !== item.root || !wholeAssign(right, item.root)) {
|
|
1366
|
+
return;
|
|
1367
|
+
}
|
|
1368
|
+
return { operator: negated ? "or" : "and", left: item, right, test: next };
|
|
1369
|
+
};
|
|
1370
|
+
var lowerSelect = ({
|
|
1371
|
+
result,
|
|
1372
|
+
condition,
|
|
1373
|
+
whenTrue,
|
|
1374
|
+
whenFalse,
|
|
1375
|
+
span
|
|
1376
|
+
}) => ({
|
|
1377
|
+
kind: "if",
|
|
1378
|
+
condition,
|
|
1379
|
+
then: [...whenTrue.statements, store(result, whenTrue.value, span)],
|
|
1380
|
+
else: [...whenFalse.statements, store(result, whenFalse.value, span)],
|
|
1381
|
+
span
|
|
1382
|
+
});
|
|
1383
|
+
var loweredSelect = (item) => {
|
|
1384
|
+
if (item.kind !== "if") {
|
|
1385
|
+
return;
|
|
1386
|
+
}
|
|
1387
|
+
const then = item.then.at(-1);
|
|
1388
|
+
const otherwise = item.else.at(-1);
|
|
1389
|
+
if (then?.kind !== "assign" || !wholeAssign(then, then.root) || !wholeAssign(otherwise, then.root)) {
|
|
1390
|
+
return;
|
|
1391
|
+
}
|
|
1392
|
+
return { root: then.root, test: item, then, else: otherwise };
|
|
1393
|
+
};
|
|
1394
|
+
|
|
1395
|
+
// packages/compiler/src/ir/conditions.ts
|
|
1396
|
+
var noExits = { returns: [], breaks: [], continues: [] };
|
|
1397
|
+
var prefixed = (conditions, exits) => ({
|
|
1398
|
+
returns: exits.returns.map((item) => [...conditions, ...item]),
|
|
1399
|
+
breaks: exits.breaks.map((item) => [...conditions, ...item]),
|
|
1400
|
+
continues: exits.continues.map((item) => [...conditions, ...item])
|
|
1401
|
+
});
|
|
1402
|
+
var merged = (...all) => ({
|
|
1403
|
+
returns: all.flatMap((exits) => exits.returns),
|
|
1404
|
+
breaks: all.flatMap((exits) => exits.breaks),
|
|
1405
|
+
continues: all.flatMap((exits) => exits.continues)
|
|
1406
|
+
});
|
|
1407
|
+
var jobField = (job, name) => job.state.find((field) => field.name === name)?.id;
|
|
1408
|
+
var constantPart = (value, segment) => {
|
|
1409
|
+
if (segment.kind === "field") {
|
|
1410
|
+
return value.kind === "record" ? value.fields[segment.name] : undefined;
|
|
1411
|
+
}
|
|
1412
|
+
const index = constantIndex(segment.value);
|
|
1413
|
+
return value.kind === "array" && index !== undefined ? value.items[index] : undefined;
|
|
1414
|
+
};
|
|
1415
|
+
var staticNames = (path) => {
|
|
1416
|
+
const names = [];
|
|
1417
|
+
for (const segment of path) {
|
|
1418
|
+
if (segment.kind === "field") {
|
|
1419
|
+
names.push(segment.name);
|
|
1420
|
+
continue;
|
|
1421
|
+
}
|
|
1422
|
+
if (segment.value.kind !== "constant" || segment.value.value.kind !== "integer") {
|
|
1423
|
+
return;
|
|
1424
|
+
}
|
|
1425
|
+
names.push(segment.value.value.value);
|
|
1426
|
+
}
|
|
1427
|
+
return names;
|
|
1428
|
+
};
|
|
1429
|
+
var opaque = (reason, type, span, reads = []) => ({ kind: "opaque", reason, reads, type, span });
|
|
1430
|
+
var projectReconstruction = (node, path, type) => {
|
|
1431
|
+
const [segment, ...rest] = path;
|
|
1432
|
+
if (!segment) {
|
|
1433
|
+
return node;
|
|
1434
|
+
}
|
|
1435
|
+
switch (node.kind) {
|
|
1436
|
+
case "read":
|
|
1437
|
+
case "local":
|
|
1438
|
+
case "parameter":
|
|
1439
|
+
return { ...node, path: [...node.path, ...path], type };
|
|
1440
|
+
case "call": {
|
|
1441
|
+
const names = staticNames(path);
|
|
1442
|
+
return names ? { ...node, path: [...node.path, ...names], type } : opaque("a call result at a dynamic index", type, node.span);
|
|
1443
|
+
}
|
|
1444
|
+
case "record": {
|
|
1445
|
+
const field = segment.kind === "field" ? node.fields[segment.name] : undefined;
|
|
1446
|
+
return field ? projectReconstruction(field, rest, type) : opaque("a field the record doesn't set", type, node.span);
|
|
1447
|
+
}
|
|
1448
|
+
case "array": {
|
|
1449
|
+
const index = segment.kind === "index" ? constantIndex(segment.value) : undefined;
|
|
1450
|
+
const item = index === undefined ? undefined : node.items[index - node.lower];
|
|
1451
|
+
return item ? projectReconstruction(item, rest, type) : opaque("an element at a dynamic index", type, node.span);
|
|
1452
|
+
}
|
|
1453
|
+
case "constant": {
|
|
1454
|
+
const part = constantPart(node.value, segment);
|
|
1455
|
+
return part ? projectReconstruction({ kind: "constant", value: part, type, span: node.span }, rest, type) : opaque("a part of a constant", type, node.span);
|
|
1456
|
+
}
|
|
1457
|
+
case "select":
|
|
1458
|
+
return {
|
|
1459
|
+
...node,
|
|
1460
|
+
type,
|
|
1461
|
+
then: projectReconstruction(node.then, path, type),
|
|
1462
|
+
else: projectReconstruction(node.else, path, type)
|
|
1463
|
+
};
|
|
1464
|
+
default:
|
|
1465
|
+
return opaque("a part of a computed value", type, node.span, [node]);
|
|
1466
|
+
}
|
|
1467
|
+
};
|
|
1468
|
+
function pathConditions(routine, variables) {
|
|
1469
|
+
const temporaries = new Set(routine.locals.filter((local) => isTemporary(routine.id, local)).map((local) => local.id));
|
|
1470
|
+
const locals = new Map(routine.locals.filter((local) => !temporaries.has(local.id)).map((local) => [local.id, local]));
|
|
1471
|
+
const parameters = new Map(isBlockRoutine(routine) ? [] : routine.parameters.map((parameter, index) => [parameter.id, index]));
|
|
1472
|
+
const typeOf = (root) => locals.get(root)?.type ?? (isBlockRoutine(routine) ? undefined : routine.parameters.find((parameter) => parameter.id === root)?.type) ?? variables.get(root)?.type;
|
|
1473
|
+
const positions = new Map;
|
|
1474
|
+
const calls = [];
|
|
1475
|
+
const definitions = new Map;
|
|
1476
|
+
const logicals = new Map;
|
|
1477
|
+
const synthetic = new Map;
|
|
1478
|
+
const selects = new Map;
|
|
1479
|
+
const sequences = [];
|
|
1480
|
+
const number = (items) => {
|
|
1481
|
+
sequences.push(items);
|
|
1482
|
+
for (const item of items) {
|
|
1483
|
+
positions.set(item, positions.size);
|
|
1484
|
+
if (item.kind === "invoke" || item.kind === "blockUpdate") {
|
|
1485
|
+
calls.push(positions.size - 1);
|
|
1486
|
+
}
|
|
1487
|
+
const defined = item.kind === "assign" ? item.root : item.kind === "invoke" && item.destination || undefined;
|
|
1488
|
+
if (defined && temporaries.has(defined)) {
|
|
1489
|
+
definitions.set(defined, [...definitions.get(defined) ?? [], item]);
|
|
1490
|
+
}
|
|
1491
|
+
nestedBodies(item).forEach(number);
|
|
1492
|
+
}
|
|
1493
|
+
};
|
|
1494
|
+
number(routine.body);
|
|
1495
|
+
const position = (item) => lookup(positions, item, "statement");
|
|
1496
|
+
const lowered = (root) => temporaries.has(root) && definitions.get(root)?.length === 2;
|
|
1497
|
+
for (const items of sequences) {
|
|
1498
|
+
items.forEach((item, index) => {
|
|
1499
|
+
const logical = loweredLogical(item, items[index + 1]);
|
|
1500
|
+
if (logical && lowered(logical.left.root)) {
|
|
1501
|
+
const { operator, left, right, test } = logical;
|
|
1502
|
+
logicals.set(left.root, { operator, left, right });
|
|
1503
|
+
synthetic.set(test, { operator, left });
|
|
1504
|
+
}
|
|
1505
|
+
const select = loweredSelect(item);
|
|
1506
|
+
if (select && lowered(select.root)) {
|
|
1507
|
+
selects.set(select.root, select);
|
|
1508
|
+
}
|
|
1509
|
+
});
|
|
1510
|
+
}
|
|
1511
|
+
const interleaved = (capturedAt, at) => calls.some((call) => call > capturedAt && call < at);
|
|
1512
|
+
const segments = (path, at) => path.map((segment) => segment.kind === "field" ? segment : { kind: "index", value: reconstruct(segment.value, at) });
|
|
1513
|
+
const place = (root, path, capturedAt, at, type, span) => {
|
|
1514
|
+
if (temporaries.has(root)) {
|
|
1515
|
+
return temporary(root, path, at, type, span);
|
|
1516
|
+
}
|
|
1517
|
+
if (locals.has(root)) {
|
|
1518
|
+
return { kind: "local", root, path, at: capturedAt, type, span };
|
|
1519
|
+
}
|
|
1520
|
+
const parameter = parameters.get(root);
|
|
1521
|
+
if (parameter !== undefined) {
|
|
1522
|
+
return {
|
|
1523
|
+
kind: "parameter",
|
|
1524
|
+
parameter,
|
|
1525
|
+
root,
|
|
1526
|
+
path,
|
|
1527
|
+
at: capturedAt,
|
|
1528
|
+
type,
|
|
1529
|
+
span
|
|
1530
|
+
};
|
|
1531
|
+
}
|
|
1532
|
+
return {
|
|
1533
|
+
kind: "read",
|
|
1534
|
+
root,
|
|
1535
|
+
path,
|
|
1536
|
+
capturedAt,
|
|
1537
|
+
interleaved: interleaved(capturedAt, at),
|
|
1538
|
+
type,
|
|
1539
|
+
span
|
|
1540
|
+
};
|
|
1541
|
+
};
|
|
1542
|
+
const temporary = (root, path, at, type, span) => {
|
|
1543
|
+
const logical = logicals.get(root);
|
|
1544
|
+
if (logical) {
|
|
1545
|
+
return projectReconstruction({
|
|
1546
|
+
kind: "logical",
|
|
1547
|
+
operator: logical.operator,
|
|
1548
|
+
left: reconstruct(logical.left.value, position(logical.left)),
|
|
1549
|
+
right: reconstruct(logical.right.value, position(logical.right)),
|
|
1550
|
+
type: "BOOL",
|
|
1551
|
+
span
|
|
1552
|
+
}, path, type);
|
|
1553
|
+
}
|
|
1554
|
+
const select = selects.get(root);
|
|
1555
|
+
if (select) {
|
|
1556
|
+
const branch = (item) => reconstruct(item.value, position(item));
|
|
1557
|
+
return projectReconstruction({
|
|
1558
|
+
kind: "select",
|
|
1559
|
+
condition: reconstruct(select.test.condition, position(select.test)),
|
|
1560
|
+
then: branch(select.then),
|
|
1561
|
+
else: branch(select.else),
|
|
1562
|
+
type: select.then.value.type,
|
|
1563
|
+
span
|
|
1564
|
+
}, path, type);
|
|
1565
|
+
}
|
|
1566
|
+
const defined = definitions.get(root) ?? [];
|
|
1567
|
+
const [only] = defined;
|
|
1568
|
+
if (defined.length === 1 && only?.kind === "invoke") {
|
|
1569
|
+
return projectReconstruction({
|
|
1570
|
+
kind: "call",
|
|
1571
|
+
call: only,
|
|
1572
|
+
path: [],
|
|
1573
|
+
type: typeOf(root) ?? type,
|
|
1574
|
+
span: only.span
|
|
1575
|
+
}, path, type);
|
|
1576
|
+
}
|
|
1577
|
+
if (defined.length === 1 && only && wholeAssign(only, root)) {
|
|
1578
|
+
const value = only.value;
|
|
1579
|
+
if (value.kind === "load") {
|
|
1580
|
+
return place(value.root, [...segments(value.path ?? [], position(only)), ...path], position(only), at, type, value.span);
|
|
1581
|
+
}
|
|
1582
|
+
return projectReconstruction(reconstruct(value, position(only)), path, type);
|
|
1583
|
+
}
|
|
1584
|
+
return parts(root, defined, path, type, span);
|
|
1585
|
+
};
|
|
1586
|
+
const parts = (root, defined, path, type, span) => {
|
|
1587
|
+
const fields = new Map;
|
|
1588
|
+
const items = new Map;
|
|
1589
|
+
for (const item of defined) {
|
|
1590
|
+
const [segment, ...rest] = item.kind === "assign" ? item.path ?? [] : [];
|
|
1591
|
+
const index = segment?.kind === "index" ? constantIndex(segment.value) : undefined;
|
|
1592
|
+
if (item.kind !== "assign" || !segment || rest.length) {
|
|
1593
|
+
return opaque("a value set in several places", type, span);
|
|
1594
|
+
}
|
|
1595
|
+
if (segment.kind === "field" && !fields.has(segment.name)) {
|
|
1596
|
+
fields.set(segment.name, item);
|
|
1597
|
+
} else if (index !== undefined && !items.has(index) && !fields.size) {
|
|
1598
|
+
items.set(index, item);
|
|
1599
|
+
} else {
|
|
1600
|
+
return opaque("a value set in several places", type, span);
|
|
1601
|
+
}
|
|
1602
|
+
}
|
|
1603
|
+
const value = (item) => reconstruct(item.value, position(item));
|
|
1604
|
+
if (items.size) {
|
|
1605
|
+
const indexes = [...items.keys()].sort((a, b) => a - b);
|
|
1606
|
+
const lower = indexes[0] ?? 0;
|
|
1607
|
+
const contiguous = indexes.every((index, offset) => index === lower + offset);
|
|
1608
|
+
if (!contiguous) {
|
|
1609
|
+
return opaque("an array with gaps", type, span);
|
|
1610
|
+
}
|
|
1611
|
+
return projectReconstruction({
|
|
1612
|
+
kind: "array",
|
|
1613
|
+
lower,
|
|
1614
|
+
items: indexes.flatMap((index) => {
|
|
1615
|
+
const item = items.get(index);
|
|
1616
|
+
return item ? [value(item)] : [];
|
|
1617
|
+
}),
|
|
1618
|
+
type: typeOf(root) ?? type,
|
|
1619
|
+
span
|
|
1620
|
+
}, path, type);
|
|
1621
|
+
}
|
|
1622
|
+
if (!fields.size) {
|
|
1623
|
+
return opaque("a value with no definition", type, span);
|
|
1624
|
+
}
|
|
1625
|
+
return projectReconstruction({
|
|
1626
|
+
kind: "record",
|
|
1627
|
+
fields: Object.fromEntries([...fields].map(([name, item]) => [name, value(item)])),
|
|
1628
|
+
type: typeOf(root) ?? type,
|
|
1629
|
+
span
|
|
1630
|
+
}, path, type);
|
|
1631
|
+
};
|
|
1632
|
+
const reconstruct = (expression, at) => {
|
|
1633
|
+
const { type, span } = expression;
|
|
1634
|
+
switch (expression.kind) {
|
|
1635
|
+
case "constant":
|
|
1636
|
+
return { kind: "constant", value: expression.value, type, span };
|
|
1637
|
+
case "borrow":
|
|
1638
|
+
return place(expression.place.root, segments(expression.place.path, at), at, at, type, span);
|
|
1639
|
+
case "load":
|
|
1640
|
+
return place(expression.root, segments(expression.path ?? [], at), at, at, type, span);
|
|
1641
|
+
case "unary":
|
|
1642
|
+
if (expression.operator === "clock") {
|
|
1643
|
+
return { kind: "clock", type, span };
|
|
1644
|
+
}
|
|
1645
|
+
return {
|
|
1646
|
+
kind: "unary",
|
|
1647
|
+
operator: expression.operator,
|
|
1648
|
+
operand: reconstruct(expression.operand, at),
|
|
1649
|
+
type,
|
|
1650
|
+
span
|
|
1651
|
+
};
|
|
1652
|
+
case "convert":
|
|
1653
|
+
return {
|
|
1654
|
+
kind: "convert",
|
|
1655
|
+
policy: expression.policy,
|
|
1656
|
+
operand: reconstruct(expression.operand, at),
|
|
1657
|
+
type,
|
|
1658
|
+
span
|
|
1659
|
+
};
|
|
1660
|
+
case "binary": {
|
|
1661
|
+
const left = reconstruct(expression.left, at);
|
|
1662
|
+
const right = reconstruct(expression.right, at);
|
|
1663
|
+
if (expression.operator === "and" || expression.operator === "or") {
|
|
1664
|
+
return {
|
|
1665
|
+
kind: "logical",
|
|
1666
|
+
operator: expression.operator,
|
|
1667
|
+
left,
|
|
1668
|
+
right,
|
|
1669
|
+
type,
|
|
1670
|
+
span
|
|
1671
|
+
};
|
|
1672
|
+
}
|
|
1673
|
+
return {
|
|
1674
|
+
kind: "binary",
|
|
1675
|
+
operator: expression.operator,
|
|
1676
|
+
...expression.policy && { policy: expression.policy },
|
|
1677
|
+
left,
|
|
1678
|
+
right,
|
|
1679
|
+
type,
|
|
1680
|
+
span
|
|
1681
|
+
};
|
|
1682
|
+
}
|
|
1683
|
+
}
|
|
1684
|
+
};
|
|
1685
|
+
const job = isBlockRoutine(routine) && routine.job ? { busy: jobField(routine, "busy"), step: jobField(routine, "step") } : undefined;
|
|
1686
|
+
const isField = (node, field) => field !== undefined && node.kind === "read" && node.root === field && !node.path.length;
|
|
1687
|
+
const busyGuard = (item) => {
|
|
1688
|
+
if (item.kind !== "if" || item.else.length || item.then.length !== 1 || item.then[0]?.kind !== "return") {
|
|
1689
|
+
return false;
|
|
1690
|
+
}
|
|
1691
|
+
const test = reconstruct(item.condition, position(item));
|
|
1692
|
+
return test.kind === "unary" && test.operator === "not" && isField(test.operand, job?.busy);
|
|
1693
|
+
};
|
|
1694
|
+
const stepSwitch = (item) => item.kind === "switch" && isField(reconstruct(item.value, position(item)), job?.step);
|
|
1695
|
+
const statements = new Map;
|
|
1696
|
+
const loops = [];
|
|
1697
|
+
const sequence = (items, conditions, loop, mode) => {
|
|
1698
|
+
const guards = [];
|
|
1699
|
+
const exits = [];
|
|
1700
|
+
for (const item of items) {
|
|
1701
|
+
const here = [...conditions, ...guards];
|
|
1702
|
+
statements.set(item, {
|
|
1703
|
+
position: position(item),
|
|
1704
|
+
conditions: here,
|
|
1705
|
+
loop
|
|
1706
|
+
});
|
|
1707
|
+
if (mode === "jobDispatcher" && busyGuard(item)) {
|
|
1708
|
+
for (const branch of nestedBodies(item)) {
|
|
1709
|
+
sequence(branch, here, loop, "plain");
|
|
1710
|
+
}
|
|
1711
|
+
guards.push({ kind: "jobBusy" });
|
|
1712
|
+
continue;
|
|
1713
|
+
}
|
|
1714
|
+
if (mode === "jobDispatcher" && item.kind === "for" && item.body.some(stepSwitch)) {
|
|
1715
|
+
sequence(item.body, here, loop, "jobTransitions");
|
|
1716
|
+
continue;
|
|
1717
|
+
}
|
|
1718
|
+
const own = statementExits(item, here, loop, mode);
|
|
1719
|
+
exits.push(prefixed(guards, own));
|
|
1720
|
+
const any = [...own.returns, ...own.breaks, ...own.continues];
|
|
1721
|
+
if (any.length) {
|
|
1722
|
+
guards.push({ kind: "exits", any });
|
|
1723
|
+
}
|
|
1724
|
+
}
|
|
1725
|
+
return merged(...exits);
|
|
1726
|
+
};
|
|
1727
|
+
const statementExits = (item, here, loop, mode) => {
|
|
1728
|
+
const at = position(item);
|
|
1729
|
+
switch (item.kind) {
|
|
1730
|
+
case "return":
|
|
1731
|
+
return { ...noExits, returns: [[]] };
|
|
1732
|
+
case "break":
|
|
1733
|
+
return { ...noExits, breaks: [[]] };
|
|
1734
|
+
case "continue":
|
|
1735
|
+
return { ...noExits, continues: [[]] };
|
|
1736
|
+
case "if": {
|
|
1737
|
+
const lowered = synthetic.get(item);
|
|
1738
|
+
const tested = lowered ? lowered.left.value : item.condition;
|
|
1739
|
+
const test = reconstruct(tested, lowered ? position(lowered.left) : at);
|
|
1740
|
+
const holds = lowered?.operator !== "or";
|
|
1741
|
+
const condition = (truth) => ({
|
|
1742
|
+
kind: "test",
|
|
1743
|
+
test,
|
|
1744
|
+
holds: truth === holds,
|
|
1745
|
+
at,
|
|
1746
|
+
span: tested.span
|
|
1747
|
+
});
|
|
1748
|
+
const yes = condition(true);
|
|
1749
|
+
const no = condition(false);
|
|
1750
|
+
return merged(prefixed([yes], sequence(item.then, [...here, yes], loop, "plain")), prefixed([no], sequence(item.else, [...here, no], loop, "plain")));
|
|
1751
|
+
}
|
|
1752
|
+
case "switch": {
|
|
1753
|
+
const test = reconstruct(item.value, at);
|
|
1754
|
+
const steps = mode === "jobTransitions" && stepSwitch(item);
|
|
1755
|
+
const inside = steps ? here.filter((condition) => condition.kind !== "jobBusy") : here;
|
|
1756
|
+
const branch = (condition, body) => prefixed([condition], sequence(body, [...inside, condition], loop, "plain"));
|
|
1757
|
+
const cases = item.cases.map((entry) => {
|
|
1758
|
+
const [value] = entry.values;
|
|
1759
|
+
const step = steps && value?.kind === "integer" && entry.values.length === 1 ? Number(value.value) : undefined;
|
|
1760
|
+
return branch(step === undefined ? {
|
|
1761
|
+
kind: "cases",
|
|
1762
|
+
test,
|
|
1763
|
+
values: entry.values,
|
|
1764
|
+
member: true,
|
|
1765
|
+
at,
|
|
1766
|
+
span: item.value.span
|
|
1767
|
+
} : { kind: "job", step }, entry.body);
|
|
1768
|
+
});
|
|
1769
|
+
const fallback = branch({
|
|
1770
|
+
kind: "cases",
|
|
1771
|
+
test,
|
|
1772
|
+
values: item.cases.flatMap((entry) => entry.values),
|
|
1773
|
+
member: false,
|
|
1774
|
+
at,
|
|
1775
|
+
span: item.value.span
|
|
1776
|
+
}, item.fallback);
|
|
1777
|
+
return merged(...cases, fallback);
|
|
1778
|
+
}
|
|
1779
|
+
case "for": {
|
|
1780
|
+
const id = loops.length;
|
|
1781
|
+
const counter = typeOf(item.counter) ?? "DINT";
|
|
1782
|
+
const bound = (value) => ({
|
|
1783
|
+
kind: "constant",
|
|
1784
|
+
value,
|
|
1785
|
+
type: counter,
|
|
1786
|
+
span: item.span
|
|
1787
|
+
});
|
|
1788
|
+
const slot = {
|
|
1789
|
+
statement: item,
|
|
1790
|
+
position: at,
|
|
1791
|
+
counter: item.counter,
|
|
1792
|
+
first: item.dynamic ? reconstruct(item.dynamic.start, at) : bound(item.start),
|
|
1793
|
+
limit: item.dynamic ? reconstruct(item.dynamic.limit, at) : bound(item.limit),
|
|
1794
|
+
exclusive: item.dynamic?.exclusive === true,
|
|
1795
|
+
step: BigInt(item.step),
|
|
1796
|
+
maxIterations: item.maxIterations,
|
|
1797
|
+
breaks: [],
|
|
1798
|
+
returns: false,
|
|
1799
|
+
parent: loop
|
|
1800
|
+
};
|
|
1801
|
+
loops.push(slot);
|
|
1802
|
+
const body = sequence(item.body, [...here, { kind: "loop", loop: id }], id, "plain");
|
|
1803
|
+
loops[id] = {
|
|
1804
|
+
...slot,
|
|
1805
|
+
breaks: body.breaks,
|
|
1806
|
+
returns: body.returns.length > 0
|
|
1807
|
+
};
|
|
1808
|
+
return body.returns.length ? { ...noExits, returns: [[{ kind: "loopReturns", loop: id }]] } : noExits;
|
|
1809
|
+
}
|
|
1810
|
+
default:
|
|
1811
|
+
return noExits;
|
|
1812
|
+
}
|
|
1813
|
+
};
|
|
1814
|
+
sequence(routine.body, [], null, job ? "jobDispatcher" : "plain");
|
|
1815
|
+
return { statements, loops, reconstruct };
|
|
1816
|
+
}
|
|
1817
|
+
// packages/compiler/src/ir/diagnostics.ts
|
|
1818
|
+
function error(code, message, span) {
|
|
1819
|
+
return {
|
|
1820
|
+
origin: "plc",
|
|
1821
|
+
code,
|
|
1822
|
+
severity: "error",
|
|
1823
|
+
message,
|
|
1824
|
+
...span && { span }
|
|
1825
|
+
};
|
|
1826
|
+
}
|
|
1827
|
+
function hasErrors(diagnostics) {
|
|
1828
|
+
return diagnostics.some((diagnostic) => diagnostic.severity === "error");
|
|
1829
|
+
}
|
|
1830
|
+
function formatDiagnostic(diagnostic, source) {
|
|
1831
|
+
const { span } = diagnostic;
|
|
1832
|
+
const location = span ? `${span.file}:${span.line}:${span.column}: ` : "";
|
|
1833
|
+
return [
|
|
1834
|
+
`${location}${diagnostic.code}: ${diagnostic.message}`,
|
|
1835
|
+
...source !== undefined && span ? excerpt(span, source) : [],
|
|
1836
|
+
...(diagnostic.related ?? []).map((related) => ` ${related.span.file}:${related.span.line}:${related.span.column}: ${related.message}`),
|
|
1837
|
+
...(diagnostic.notes ?? []).map((note) => ` ${note}`)
|
|
1838
|
+
].join(`
|
|
1839
|
+
`);
|
|
1840
|
+
}
|
|
1841
|
+
var excerpt = (span, source) => {
|
|
1842
|
+
const line = source.split(/\r?\n/)[span.line - 1];
|
|
1843
|
+
if (line === undefined) {
|
|
1844
|
+
return [];
|
|
1845
|
+
}
|
|
1846
|
+
const width = Math.max(1, Math.min(span.end - span.start, line.length - span.column + 2));
|
|
1847
|
+
return [
|
|
1848
|
+
`${span.line} | ${line}`,
|
|
1849
|
+
`${" ".repeat(String(span.line).length + 3 + span.column - 1)}${"^".repeat(width)}`
|
|
1850
|
+
];
|
|
1851
|
+
};
|
|
1852
|
+
// packages/compiler/src/ir/identity.ts
|
|
1853
|
+
import { createHash } from "node:crypto";
|
|
1854
|
+
var identityDigest = (identity) => createHash("sha256").update(identity).digest("hex").slice(0, 8);
|
|
1855
|
+
var pascalCase = (text) => text.split(/[^A-Za-z0-9]+/).map((word) => word.charAt(0).toUpperCase() + word.slice(1)).join("");
|
|
1856
|
+
// packages/compiler/src/ir/job-errors.ts
|
|
1857
|
+
var jobError = {
|
|
1858
|
+
cancelled: 1,
|
|
1859
|
+
timeout: 2,
|
|
1860
|
+
tooLarge: 3,
|
|
1861
|
+
malformedResponse: 4,
|
|
1862
|
+
network: 5,
|
|
1863
|
+
tls: 6,
|
|
1864
|
+
noRequestSlot: 7,
|
|
1865
|
+
codeChanged: 11001
|
|
1866
|
+
};
|
|
1867
|
+
var httpBase = 1e4;
|
|
1868
|
+
var httpErrors = {
|
|
1869
|
+
base: httpBase,
|
|
1870
|
+
last: 10999,
|
|
1871
|
+
refused: httpBase + 400
|
|
1872
|
+
};
|
|
1873
|
+
var reservedErrors = { first: 11000, last: 11099 };
|
|
1874
|
+
var errorMeanings = {
|
|
1875
|
+
[jobError.cancelled]: "cancelled",
|
|
1876
|
+
[jobError.timeout]: "timeout",
|
|
1877
|
+
[jobError.tooLarge]: "request or response too large to encode",
|
|
1878
|
+
[jobError.malformedResponse]: "malformed response",
|
|
1879
|
+
[jobError.network]: "network error or server restarted",
|
|
1880
|
+
[jobError.tls]: "TLS error",
|
|
1881
|
+
[jobError.noRequestSlot]: "no free request slot",
|
|
1882
|
+
[jobError.codeChanged]: "an online change replaced the job's code while it ran"
|
|
1883
|
+
};
|
|
1884
|
+
var jobErrors = {
|
|
1885
|
+
...errorMeanings,
|
|
1886
|
+
[httpErrors.base]: `HTTP status: ${httpErrors.base} + status code`
|
|
1887
|
+
};
|
|
1888
|
+
var errorName = (code) => {
|
|
1889
|
+
if (code > httpErrors.base && code <= httpErrors.last) {
|
|
1890
|
+
return `HTTP ${code - httpErrors.base}`;
|
|
1891
|
+
}
|
|
1892
|
+
return errorMeanings[code];
|
|
1893
|
+
};
|
|
1894
|
+
var failureCode = (reason) => typeof reason === "number" ? reason : 0;
|
|
1895
|
+
var failureName = (reason) => {
|
|
1896
|
+
if (typeof reason === "number") {
|
|
1897
|
+
return errorName(reason);
|
|
1898
|
+
}
|
|
1899
|
+
return reason instanceof Error ? reason.message : String(reason);
|
|
1900
|
+
};
|
|
1901
|
+
// packages/compiler/src/ir/layouts.ts
|
|
1902
|
+
import { elementaryType, integerRange as integerRange2 } from "@tsplc/iec";
|
|
1903
|
+
|
|
1904
|
+
// packages/compiler/src/ir/normalization-error.ts
|
|
1905
|
+
class InvalidCore extends Error {
|
|
1906
|
+
diagnostic;
|
|
1907
|
+
constructor(diagnostic) {
|
|
1908
|
+
super(diagnostic.message);
|
|
1909
|
+
this.diagnostic = diagnostic;
|
|
1910
|
+
}
|
|
1911
|
+
}
|
|
1912
|
+
function reject(message, span) {
|
|
1913
|
+
throw new InvalidCore(error("PLC6001", message, span));
|
|
1914
|
+
}
|
|
1915
|
+
|
|
1916
|
+
// packages/compiler/src/ir/layouts.ts
|
|
1917
|
+
var maxScalarElements = 1e6;
|
|
1918
|
+
var maxScalarElementsText = "one million";
|
|
1919
|
+
var maxNestingDepth = 64;
|
|
1920
|
+
var maxStringCapacity = 65535;
|
|
1921
|
+
var [firstIndex, lastIndex] = integerRange2(elementaryType("DINT"));
|
|
1922
|
+
var definitionIssue = (type, types) => {
|
|
1923
|
+
const canonical = primitiveTypes.find((item) => item.id === type.id);
|
|
1924
|
+
if (canonical) {
|
|
1925
|
+
return type.kind !== canonical.kind || "bits" in canonical && (!("bits" in type) || type.bits !== canonical.bits) || "signed" in canonical && (!("signed" in type) || type.signed !== canonical.signed) || "domain" in canonical && (!("domain" in type) || type.domain !== canonical.domain) ? `Conflicting primitive type ${type.id}` : undefined;
|
|
1926
|
+
}
|
|
1927
|
+
switch (type.kind) {
|
|
1928
|
+
case "record":
|
|
1929
|
+
return !type.fields.length || new Set(type.fields.map((field) => field.name)).size !== type.fields.length || type.fields.some((field) => !field.name || !types.has(field.type)) ? `Invalid closed record layout ${type.id}` : undefined;
|
|
1930
|
+
case "array": {
|
|
1931
|
+
if (!types.has(type.element) || !Number.isSafeInteger(type.length) || type.length < 1 || type.length > maxScalarElements || !Number.isInteger(type.lowerBound) || BigInt(type.lowerBound) < firstIndex || BigInt(type.lowerBound + type.length - 1) > lastIndex) {
|
|
1932
|
+
return `Invalid fixed array layout ${type.id}`;
|
|
1933
|
+
}
|
|
1934
|
+
if (type.index === undefined) {
|
|
1935
|
+
return;
|
|
1936
|
+
}
|
|
1937
|
+
const index = types.get(type.index);
|
|
1938
|
+
return index?.kind !== "enum" || index.members.length !== type.length || index.members.some((member) => Number(member.value) < type.lowerBound || Number(member.value) >= type.lowerBound + type.length) ? `Invalid enum-keyed array layout ${type.id}` : undefined;
|
|
1939
|
+
}
|
|
1940
|
+
case "enum": {
|
|
1941
|
+
const base = types.get(type.base);
|
|
1942
|
+
return type.base !== "DINT" || base?.kind !== "integer" || !type.members.length || new Set(type.members.map((member) => member.name)).size !== type.members.length || new Set(type.members.map((member) => member.value)).size !== type.members.length || type.members.some((member) => !member.name || !constantFits({ kind: "integer", value: member.value }, base)) ? `Invalid enum layout ${type.id}` : undefined;
|
|
1943
|
+
}
|
|
1944
|
+
case "string":
|
|
1945
|
+
return !Number.isInteger(type.capacity) || type.capacity < 1 || type.capacity > maxStringCapacity ? `Invalid bounded string layout ${type.id}` : undefined;
|
|
1946
|
+
case "block":
|
|
1947
|
+
return !type.block || type.output && types.get(type.output)?.kind !== "record" ? `Invalid block type ${type.id}` : undefined;
|
|
1948
|
+
default:
|
|
1949
|
+
return `Unsupported core type definition ${type.id}`;
|
|
1950
|
+
}
|
|
1951
|
+
};
|
|
1952
|
+
var layoutMeasure = (types, exceeded) => {
|
|
1953
|
+
const active = new Set;
|
|
1954
|
+
const layouts = new Map;
|
|
1955
|
+
const measure = (id, depth) => {
|
|
1956
|
+
if (active.has(id) || depth > maxNestingDepth) {
|
|
1957
|
+
exceeded("nesting", `Recursive or excessively nested by-value layout ${id}`);
|
|
1958
|
+
}
|
|
1959
|
+
const cached = layouts.get(id);
|
|
1960
|
+
if (cached) {
|
|
1961
|
+
if (depth + cached.height > maxNestingDepth) {
|
|
1962
|
+
exceeded("nesting", `Layout nesting exceeds ${maxNestingDepth} levels ${id}`);
|
|
1963
|
+
}
|
|
1964
|
+
return cached;
|
|
1965
|
+
}
|
|
1966
|
+
active.add(id);
|
|
1967
|
+
const layout = composite(lookup(types, id, "type"), depth);
|
|
1968
|
+
active.delete(id);
|
|
1969
|
+
if (layout.size > maxScalarElements) {
|
|
1970
|
+
exceeded("size", `Layout exceeds ${maxScalarElementsText} scalar elements ${id}`);
|
|
1971
|
+
}
|
|
1972
|
+
if (depth + layout.height > maxNestingDepth) {
|
|
1973
|
+
exceeded("nesting", `Layout nesting exceeds ${maxNestingDepth} levels ${id}`);
|
|
1974
|
+
}
|
|
1975
|
+
layouts.set(id, layout);
|
|
1976
|
+
return layout;
|
|
1977
|
+
};
|
|
1978
|
+
const composite = (type, depth) => {
|
|
1979
|
+
if (type.kind === "array") {
|
|
1980
|
+
const element = measure(type.element, depth + 1);
|
|
1981
|
+
return { size: type.length * element.size, height: 1 + element.height };
|
|
1982
|
+
}
|
|
1983
|
+
if (type.kind === "record") {
|
|
1984
|
+
const fields = type.fields.map((field) => measure(field.type, depth + 1));
|
|
1985
|
+
return {
|
|
1986
|
+
size: fields.reduce((sum, field) => sum + field.size, 0),
|
|
1987
|
+
height: 1 + fields.reduce((maximum, field) => Math.max(maximum, field.height), 0)
|
|
1988
|
+
};
|
|
1989
|
+
}
|
|
1990
|
+
return { size: 1, height: 0 };
|
|
1991
|
+
};
|
|
1992
|
+
return (id) => measure(id, 0);
|
|
1993
|
+
};
|
|
1994
|
+
var admitLayouts = (types) => {
|
|
1995
|
+
for (const type of types.values()) {
|
|
1996
|
+
const issue = definitionIssue(type, types);
|
|
1997
|
+
if (issue) {
|
|
1998
|
+
reject(issue);
|
|
1999
|
+
}
|
|
2000
|
+
}
|
|
2001
|
+
const measure = layoutMeasure(types, (_budget, message) => reject(message));
|
|
2002
|
+
return new Map([...types.keys()].map((id) => [id, measure(id).size]));
|
|
2003
|
+
};
|
|
2004
|
+
|
|
2005
|
+
class BudgetExceeded {
|
|
2006
|
+
budget;
|
|
2007
|
+
constructor(budget) {
|
|
2008
|
+
this.budget = budget;
|
|
2009
|
+
}
|
|
2010
|
+
}
|
|
2011
|
+
var layoutIssue = (types, id) => {
|
|
2012
|
+
try {
|
|
2013
|
+
layoutMeasure(types, (budget) => {
|
|
2014
|
+
throw new BudgetExceeded(budget);
|
|
2015
|
+
})(id);
|
|
2016
|
+
return;
|
|
2017
|
+
} catch (cause) {
|
|
2018
|
+
if (cause instanceof BudgetExceeded) {
|
|
2019
|
+
return cause.budget;
|
|
2020
|
+
}
|
|
2021
|
+
throw cause;
|
|
2022
|
+
}
|
|
2023
|
+
};
|
|
2024
|
+
// packages/compiler/src/ir/allocation.ts
|
|
2025
|
+
function checkStaticAllocation(module, declarations) {
|
|
2026
|
+
const { types, blocks, layoutSizes } = declarations;
|
|
2027
|
+
const payload = (id) => lookup(layoutSizes, id, "layout");
|
|
2028
|
+
const instance = (id) => {
|
|
2029
|
+
const instanced = instancedBlock(id, types);
|
|
2030
|
+
if (!instanced) {
|
|
2031
|
+
throw new Error(`Type ${id} instantiates no block.`);
|
|
2032
|
+
}
|
|
2033
|
+
const block = allocation(instanced.block);
|
|
2034
|
+
const type = lookup(types, id, "type");
|
|
2035
|
+
return type.kind === "array" ? { size: type.length * block.size, height: block.height } : block;
|
|
2036
|
+
};
|
|
2037
|
+
const allocations = new Map;
|
|
2038
|
+
const allocating = new Set;
|
|
2039
|
+
const allocation = (id) => {
|
|
2040
|
+
if (allocating.size >= maxNestingDepth) {
|
|
2041
|
+
reject(`Static block allocation nesting exceeds ${maxNestingDepth} levels.`, blocks.get(id)?.span);
|
|
2042
|
+
}
|
|
2043
|
+
if (allocating.has(id)) {
|
|
2044
|
+
reject("Recursive static block allocation.", blocks.get(id)?.span);
|
|
2045
|
+
}
|
|
2046
|
+
const cached = allocations.get(id);
|
|
2047
|
+
if (cached) {
|
|
2048
|
+
return cached;
|
|
2049
|
+
}
|
|
2050
|
+
allocating.add(id);
|
|
2051
|
+
const block = lookup(blocks, id, "block");
|
|
2052
|
+
const children = block.state.filter((item) => item.storage === "instance").map((item) => instance(item.type));
|
|
2053
|
+
const own = [
|
|
2054
|
+
...block.inputs,
|
|
2055
|
+
...block.outputs,
|
|
2056
|
+
...block.state.filter((item) => item.storage !== "instance")
|
|
2057
|
+
].reduce((sum, item) => sum + (item.mode === "inOut" ? 1 : payload(item.type)), 1);
|
|
2058
|
+
const size = own + children.reduce((sum, child) => sum + child.size, 0);
|
|
2059
|
+
const height = children.length ? 1 + Math.max(...children.map((child) => child.height)) : 1;
|
|
2060
|
+
if (size > maxScalarElements || height > maxNestingDepth) {
|
|
2061
|
+
reject("Static block allocation exceeds its finite budget.", block.span);
|
|
2062
|
+
}
|
|
2063
|
+
allocating.delete(id);
|
|
2064
|
+
const result = { size, height };
|
|
2065
|
+
allocations.set(id, result);
|
|
2066
|
+
return result;
|
|
2067
|
+
};
|
|
2068
|
+
for (const block of module.blocks) {
|
|
2069
|
+
allocation(block.id);
|
|
2070
|
+
}
|
|
2071
|
+
const staticPayload = module.variables.reduce((sum, variable) => {
|
|
2072
|
+
return sum + (instancedBlock(variable.type, types) ? instance(variable.type).size : payload(variable.type));
|
|
2073
|
+
}, 0);
|
|
2074
|
+
if (staticPayload > maxScalarElements) {
|
|
2075
|
+
reject(`Static module storage exceeds ${maxScalarElementsText} scalar elements.`);
|
|
2076
|
+
}
|
|
2077
|
+
}
|
|
2078
|
+
|
|
2079
|
+
// packages/compiler/src/ir/declarations.ts
|
|
2080
|
+
var matchesPorts = (variables, schema) => variables.length === schema.length && schema.every(([name, , type]) => variables.some((variable) => variable.name === name && variable.type === type && !variable.mode && variable.retention === "none"));
|
|
2081
|
+
var checkStandardBlock = (block, standard) => {
|
|
2082
|
+
const expected = standardBlocks[standard];
|
|
2083
|
+
if (block.name !== standard || block.body.length || block.state.length || block.locals.length || !matchesPorts(block.inputs, expected.inputs) || !matchesPorts(block.outputs, expected.outputs) || block.outputs.some(({ initial }) => {
|
|
2084
|
+
switch (initial?.kind) {
|
|
2085
|
+
case "bool":
|
|
2086
|
+
return initial.value !== false;
|
|
2087
|
+
case "duration":
|
|
2088
|
+
return initial.nanoseconds !== "0";
|
|
2089
|
+
case "integer":
|
|
2090
|
+
return initial.value !== "0";
|
|
2091
|
+
default:
|
|
2092
|
+
return true;
|
|
2093
|
+
}
|
|
2094
|
+
})) {
|
|
2095
|
+
reject("Invalid canonical standard block definition.", block.span);
|
|
2096
|
+
}
|
|
2097
|
+
};
|
|
2098
|
+
|
|
2099
|
+
class ModuleDeclarations {
|
|
2100
|
+
ids = new Set;
|
|
2101
|
+
types = new Map;
|
|
2102
|
+
layoutSizes;
|
|
2103
|
+
globals = new Map;
|
|
2104
|
+
blocks;
|
|
2105
|
+
signatures;
|
|
2106
|
+
constructor(module) {
|
|
2107
|
+
for (const type of module.types) {
|
|
2108
|
+
if (this.types.has(type.id)) {
|
|
2109
|
+
reject(`Duplicate type ${type.id}.`);
|
|
2110
|
+
}
|
|
2111
|
+
this.types.set(type.id, type);
|
|
2112
|
+
}
|
|
2113
|
+
this.layoutSizes = admitLayouts(this.types);
|
|
2114
|
+
if (this.types.get("BOOL")?.kind !== "bool") {
|
|
2115
|
+
reject("Missing canonical BOOL type.");
|
|
2116
|
+
}
|
|
2117
|
+
this.blocks = new Map(module.blocks.map((block) => [block.id, block]));
|
|
2118
|
+
for (const item of module.variables) {
|
|
2119
|
+
this.checkVariable(item, [
|
|
2120
|
+
"module",
|
|
2121
|
+
"instance",
|
|
2122
|
+
"input",
|
|
2123
|
+
"output",
|
|
2124
|
+
"constant"
|
|
2125
|
+
]);
|
|
2126
|
+
this.globals.set(item.id, item);
|
|
2127
|
+
}
|
|
2128
|
+
this.signatures = new Map(module.functions.map((fn) => [fn.id, fn]));
|
|
2129
|
+
for (const fn of module.functions) {
|
|
2130
|
+
this.claimId(fn.id, fn.span);
|
|
2131
|
+
if (fn.owner && (!this.blocks.has(fn.owner.block) || this.blocks.get(fn.owner.block)?.standard)) {
|
|
2132
|
+
reject("Methods require a user block owner and a valid access modifier.", fn.span);
|
|
2133
|
+
}
|
|
2134
|
+
if (fn.result && !isValueType(fn.result, this.types)) {
|
|
2135
|
+
reject("Unknown or non-value function result type.", fn.span);
|
|
2136
|
+
}
|
|
2137
|
+
for (const parameter of fn.parameters) {
|
|
2138
|
+
this.checkVariable(parameter, ["parameter"], { allowBorrow: true });
|
|
2139
|
+
if (parameter.mutable && !parameter.mode) {
|
|
2140
|
+
reject("Value parameters are readonly.", parameter.span);
|
|
2141
|
+
}
|
|
2142
|
+
}
|
|
2143
|
+
for (const local of fn.locals) {
|
|
2144
|
+
this.checkVariable(local, ["local"]);
|
|
2145
|
+
}
|
|
2146
|
+
}
|
|
2147
|
+
for (const block of module.blocks) {
|
|
2148
|
+
this.claimId(block.id, block.span);
|
|
2149
|
+
for (const input of block.inputs) {
|
|
2150
|
+
this.checkVariable(input, ["parameter"], { allowBorrow: true });
|
|
2151
|
+
if (!input.mode && input.mutable) {
|
|
2152
|
+
reject("Value block inputs are readonly.", input.span);
|
|
2153
|
+
}
|
|
2154
|
+
}
|
|
2155
|
+
for (const output of block.outputs) {
|
|
2156
|
+
this.checkVariable(output, ["blockOutput"]);
|
|
2157
|
+
}
|
|
2158
|
+
for (const state of block.state) {
|
|
2159
|
+
this.checkVariable(state, ["field", "instance"]);
|
|
2160
|
+
if (state.retention === "persist") {
|
|
2161
|
+
reject("Only module state may persist; persist the module binding that holds the instance.", state.span);
|
|
2162
|
+
}
|
|
2163
|
+
}
|
|
2164
|
+
for (const local of block.locals) {
|
|
2165
|
+
this.checkVariable(local, ["local"]);
|
|
2166
|
+
}
|
|
2167
|
+
for (const ports of [block.inputs, block.outputs]) {
|
|
2168
|
+
if (new Set(ports.map((variable) => variable.name)).size !== ports.length) {
|
|
2169
|
+
reject("Block input and output names must each be unique within their schema.", block.span);
|
|
2170
|
+
}
|
|
2171
|
+
}
|
|
2172
|
+
const result = block.result ? this.types.get(block.result) : undefined;
|
|
2173
|
+
if (block.outputs.length ? result?.kind !== "record" || !isValueType(result.id, this.types) || result.fields.length !== block.outputs.length || result.fields.some((field) => !block.outputs.some((output) => output.name === field.name && output.type === field.type)) : Boolean(block.result)) {
|
|
2174
|
+
reject("Block output schema differs from its result record.", block.span);
|
|
2175
|
+
}
|
|
2176
|
+
if (block.standard) {
|
|
2177
|
+
checkStandardBlock(block, block.standard);
|
|
2178
|
+
}
|
|
2179
|
+
}
|
|
2180
|
+
for (const type of this.types.values()) {
|
|
2181
|
+
if (type.kind === "block") {
|
|
2182
|
+
const definition = this.blocks.get(type.block);
|
|
2183
|
+
if (!definition || definition.result !== type.output) {
|
|
2184
|
+
reject("Block type differs from its definition.");
|
|
2185
|
+
}
|
|
2186
|
+
}
|
|
2187
|
+
}
|
|
2188
|
+
}
|
|
2189
|
+
hasId(id) {
|
|
2190
|
+
return this.ids.has(id);
|
|
2191
|
+
}
|
|
2192
|
+
claimId(id, span) {
|
|
2193
|
+
if (this.ids.has(id)) {
|
|
2194
|
+
reject(`Duplicate symbol ${id}.`, span);
|
|
2195
|
+
}
|
|
2196
|
+
this.ids.add(id);
|
|
2197
|
+
}
|
|
2198
|
+
checkVariable(item, storage, { allowBorrow } = {}) {
|
|
2199
|
+
this.claimId(item.id, item.span);
|
|
2200
|
+
const type = this.types.get(item.type);
|
|
2201
|
+
if (!type || !storage.includes(item.storage)) {
|
|
2202
|
+
reject("Invalid storage type or class.", item.span);
|
|
2203
|
+
}
|
|
2204
|
+
if (item.mode && (item.mode !== "inOut" || !allowBorrow || !item.mutable || item.storage !== "parameter")) {
|
|
2205
|
+
reject("InOut belongs only on mutable parameters.", item.span);
|
|
2206
|
+
}
|
|
2207
|
+
const mutableState = item.mutable || type.kind === "array" || type.kind === "record" && type.fields.some((field) => !field.readonly);
|
|
2208
|
+
if (item.retention !== "none" && !(item.storage === "instance" || ["module", "field"].includes(item.storage) && mutableState)) {
|
|
2209
|
+
reject("Only mutable static state or block instances may retain.", item.span);
|
|
2210
|
+
}
|
|
2211
|
+
if (item.storage === "instance") {
|
|
2212
|
+
const instanced = instancedBlock(item.type, this.types);
|
|
2213
|
+
if (!instanced || !this.blocks.has(instanced.block) || item.initial || item.mode) {
|
|
2214
|
+
reject("Instances require a known static block and cannot have value initializers.", item.span);
|
|
2215
|
+
}
|
|
2216
|
+
} else if (!isValueType(item.type, this.types) && !(allowBorrow && item.mode === "inOut" && type.kind === "block")) {
|
|
2217
|
+
reject("Block instances and reference schemas cannot be stored as values.", item.span);
|
|
2218
|
+
}
|
|
2219
|
+
if (item.storage === "parameter" && item.initial) {
|
|
2220
|
+
reject("Inputs are supplied at each invocation and cannot have stored initializers.", item.span);
|
|
2221
|
+
}
|
|
2222
|
+
if (item.initial && !valueFits(item.initial, type, this.types)) {
|
|
2223
|
+
reject("Initializer has the wrong type or is out of range.", item.span);
|
|
2224
|
+
}
|
|
2225
|
+
if (["module", "field", "constant", "blockOutput"].includes(item.storage) && !item.initial) {
|
|
2226
|
+
reject("Persistent storage requires initialization.", item.span);
|
|
2227
|
+
}
|
|
2228
|
+
if (["input", "constant", "blockOutput"].includes(item.storage) && item.mutable) {
|
|
2229
|
+
reject("Readonly storage marked mutable.", item.span);
|
|
2230
|
+
}
|
|
2231
|
+
}
|
|
2232
|
+
}
|
|
2233
|
+
|
|
2234
|
+
// packages/compiler/src/ir/link.ts
|
|
2235
|
+
function linkModule(module, declarations, functions, normalizedBlocks, edges) {
|
|
2236
|
+
const entries = checkPrograms(module, declarations);
|
|
2237
|
+
const routines = new Map([...functions, ...normalizedBlocks].map((fn) => [fn.id, fn]));
|
|
2238
|
+
checkRecursion(routines, edges, entries, declarations);
|
|
2239
|
+
checkLoopCounterWrites(module, declarations, routines, edges);
|
|
2240
|
+
const reachable = reachableRoutines(module, declarations, functions, entries, edges);
|
|
2241
|
+
const linkedFunctions = functions.filter((fn) => reachable.has(fn.id));
|
|
2242
|
+
const linkedBlocks = normalizedBlocks.filter((block) => reachable.has(block.id));
|
|
2243
|
+
const usedTypes = usedTypeIds(module, declarations.types, linkedFunctions, linkedBlocks);
|
|
2244
|
+
return {
|
|
2245
|
+
types: module.types.filter((type) => usedTypes.has(type.id)),
|
|
2246
|
+
variables: module.variables,
|
|
2247
|
+
functions: linkedFunctions,
|
|
2248
|
+
blocks: linkedBlocks,
|
|
2249
|
+
programs: module.programs,
|
|
2250
|
+
...module.folded && { folded: module.folded },
|
|
2251
|
+
...module.references && { references: module.references }
|
|
2252
|
+
};
|
|
2253
|
+
}
|
|
2254
|
+
var checkPrograms = (module, declarations) => {
|
|
2255
|
+
const names = new Set;
|
|
2256
|
+
const entries = new Set;
|
|
2257
|
+
for (const program of module.programs) {
|
|
2258
|
+
declarations.claimId(program.id);
|
|
2259
|
+
const entry = declarations.signatures.get(program.entry);
|
|
2260
|
+
if (!entry || entry.owner || entry.parameters.length || entry.result) {
|
|
2261
|
+
reject("Program entry must be a parameterless void helper.");
|
|
2262
|
+
}
|
|
2263
|
+
if (names.has(program.name)) {
|
|
2264
|
+
reject(`Duplicate program ${program.name}.`);
|
|
2265
|
+
}
|
|
2266
|
+
names.add(program.name);
|
|
2267
|
+
entries.add(program.entry);
|
|
2268
|
+
}
|
|
2269
|
+
if (!module.programs.length) {
|
|
2270
|
+
reject("At least one program is required.");
|
|
2271
|
+
}
|
|
2272
|
+
return entries;
|
|
2273
|
+
};
|
|
2274
|
+
var checkRecursion = (routines, edges, entries, { signatures }) => {
|
|
2275
|
+
const visited = new Set;
|
|
2276
|
+
const active = new Set;
|
|
2277
|
+
const visit = (id) => {
|
|
2278
|
+
if (active.has(id)) {
|
|
2279
|
+
reject("Recursive scan calls are prohibited.", signatures.get(id)?.span);
|
|
2280
|
+
}
|
|
2281
|
+
if (visited.has(id)) {
|
|
2282
|
+
return;
|
|
2283
|
+
}
|
|
2284
|
+
active.add(id);
|
|
2285
|
+
for (const child of edges.get(id) ?? []) {
|
|
2286
|
+
if (entries.has(child)) {
|
|
2287
|
+
reject("Program entries cannot be called as ordinary helpers.", signatures.get(id)?.span);
|
|
2288
|
+
}
|
|
2289
|
+
visit(child);
|
|
2290
|
+
}
|
|
2291
|
+
active.delete(id);
|
|
2292
|
+
visited.add(id);
|
|
2293
|
+
};
|
|
2294
|
+
for (const id of routines.keys()) {
|
|
2295
|
+
visit(id);
|
|
2296
|
+
}
|
|
2297
|
+
};
|
|
2298
|
+
var checkLoopCounterWrites = (module, { types }, routines, edges) => {
|
|
2299
|
+
const variables = new Map([
|
|
2300
|
+
...module.variables,
|
|
2301
|
+
...[...routines.values()].flatMap(routineVariables)
|
|
2302
|
+
].map((variable) => [variable.id, variable]));
|
|
2303
|
+
const writes = new Map;
|
|
2304
|
+
const routineWrites = (id) => {
|
|
2305
|
+
const cached = writes.get(id);
|
|
2306
|
+
if (cached) {
|
|
2307
|
+
return cached;
|
|
2308
|
+
}
|
|
2309
|
+
const result = new Set;
|
|
2310
|
+
const inspect = (body) => {
|
|
2311
|
+
for (const item of body) {
|
|
2312
|
+
for (const root of directWrites(item)) {
|
|
2313
|
+
result.add(root);
|
|
2314
|
+
}
|
|
2315
|
+
for (const nested of nestedBodies(item)) {
|
|
2316
|
+
inspect(nested);
|
|
2317
|
+
}
|
|
2318
|
+
}
|
|
2319
|
+
};
|
|
2320
|
+
inspect(lookup(routines, id, "routine").body);
|
|
2321
|
+
for (const child of edges.get(id) ?? []) {
|
|
2322
|
+
for (const root of routineWrites(child)) {
|
|
2323
|
+
result.add(root);
|
|
2324
|
+
}
|
|
2325
|
+
}
|
|
2326
|
+
writes.set(id, result);
|
|
2327
|
+
return result;
|
|
2328
|
+
};
|
|
2329
|
+
const checkCalls = (body, counters) => {
|
|
2330
|
+
for (const item of body) {
|
|
2331
|
+
const called = calledRoutine(item, (id) => variables.get(id), types);
|
|
2332
|
+
if (called && [...counters].some((counter) => routineWrites(called).has(counter))) {
|
|
2333
|
+
reject("A called routine may mutate an active loop counter.", item.span);
|
|
2334
|
+
}
|
|
2335
|
+
const nestedCounters = item.kind === "for" ? new Set([...counters, item.counter]) : counters;
|
|
2336
|
+
for (const nested of nestedBodies(item)) {
|
|
2337
|
+
checkCalls(nested, nestedCounters);
|
|
2338
|
+
}
|
|
2339
|
+
}
|
|
2340
|
+
};
|
|
2341
|
+
for (const routine of routines.values()) {
|
|
2342
|
+
checkCalls(routine.body, new Set);
|
|
2343
|
+
}
|
|
2344
|
+
};
|
|
2345
|
+
var reachableRoutines = (module, { signatures, blocks, types }, functions, entries, edges) => {
|
|
2346
|
+
const reachable = new Set;
|
|
2347
|
+
const link = (id) => {
|
|
2348
|
+
if (reachable.has(id)) {
|
|
2349
|
+
return;
|
|
2350
|
+
}
|
|
2351
|
+
reachable.add(id);
|
|
2352
|
+
for (const child of edges.get(id) ?? []) {
|
|
2353
|
+
link(child);
|
|
2354
|
+
}
|
|
2355
|
+
const owner = signatures.get(id)?.owner;
|
|
2356
|
+
if (owner) {
|
|
2357
|
+
link(owner.block);
|
|
2358
|
+
}
|
|
2359
|
+
for (const method of functions.filter((fn) => fn.owner?.block === id)) {
|
|
2360
|
+
link(method.id);
|
|
2361
|
+
}
|
|
2362
|
+
for (const instance of blocks.get(id)?.state.filter((variable) => variable.storage === "instance") ?? []) {
|
|
2363
|
+
const type = instancedBlock(instance.type, types);
|
|
2364
|
+
if (type) {
|
|
2365
|
+
link(type.block);
|
|
2366
|
+
}
|
|
2367
|
+
}
|
|
2368
|
+
};
|
|
2369
|
+
for (const entry of entries) {
|
|
2370
|
+
link(entry);
|
|
2371
|
+
}
|
|
2372
|
+
for (const variable of module.variables) {
|
|
2373
|
+
const type = instancedBlock(variable.type, types);
|
|
2374
|
+
if (type) {
|
|
2375
|
+
link(type.block);
|
|
2376
|
+
}
|
|
2377
|
+
}
|
|
2378
|
+
return reachable;
|
|
2379
|
+
};
|
|
2380
|
+
var usedTypeIds = (module, types, linkedFunctions, linkedBlocks) => {
|
|
2381
|
+
const usedTypes = new Set;
|
|
2382
|
+
const useType = (id) => {
|
|
2383
|
+
if (usedTypes.has(id)) {
|
|
2384
|
+
return;
|
|
2385
|
+
}
|
|
2386
|
+
usedTypes.add(id);
|
|
2387
|
+
const type = lookup(types, id, "type");
|
|
2388
|
+
if (type.kind === "record") {
|
|
2389
|
+
for (const field of type.fields) {
|
|
2390
|
+
useType(field.type);
|
|
2391
|
+
}
|
|
2392
|
+
}
|
|
2393
|
+
if (type.kind === "array") {
|
|
2394
|
+
useType(type.element);
|
|
2395
|
+
if (type.index) {
|
|
2396
|
+
useType(type.index);
|
|
2397
|
+
}
|
|
2398
|
+
}
|
|
2399
|
+
if (type.kind === "enum") {
|
|
2400
|
+
useType(type.base);
|
|
2401
|
+
}
|
|
2402
|
+
if (type.kind === "block" && type.output) {
|
|
2403
|
+
useType(type.output);
|
|
2404
|
+
}
|
|
2405
|
+
};
|
|
2406
|
+
types.forEach((type) => {
|
|
2407
|
+
if (["bool", "integer", "bits", "float", "duration", "calendar"].includes(type.kind)) {
|
|
2408
|
+
useType(type.id);
|
|
2409
|
+
}
|
|
2410
|
+
});
|
|
2411
|
+
for (const variable of module.variables) {
|
|
2412
|
+
useType(variable.type);
|
|
2413
|
+
}
|
|
2414
|
+
for (const routine of [...linkedFunctions, ...linkedBlocks]) {
|
|
2415
|
+
if (routine.result) {
|
|
2416
|
+
useType(routine.result);
|
|
2417
|
+
}
|
|
2418
|
+
for (const variable of routineVariables(routine)) {
|
|
2419
|
+
useType(variable.type);
|
|
2420
|
+
}
|
|
2421
|
+
}
|
|
2422
|
+
const useTelemetryTypes = (body) => {
|
|
2423
|
+
for (const item of body) {
|
|
2424
|
+
if (item.kind === "telemetry") {
|
|
2425
|
+
for (const operand of telemetryOperands(item)) {
|
|
2426
|
+
useType(operand.type);
|
|
2427
|
+
}
|
|
2428
|
+
}
|
|
2429
|
+
for (const nested of nestedBodies(item)) {
|
|
2430
|
+
useTelemetryTypes(nested);
|
|
2431
|
+
}
|
|
2432
|
+
}
|
|
2433
|
+
};
|
|
2434
|
+
for (const routine of [...linkedFunctions, ...linkedBlocks]) {
|
|
2435
|
+
useTelemetryTypes(routine.body);
|
|
2436
|
+
}
|
|
2437
|
+
return usedTypes;
|
|
2438
|
+
};
|
|
2439
|
+
|
|
2440
|
+
// packages/compiler/src/ir/routine.ts
|
|
2441
|
+
var join = (branches, initialized) => {
|
|
2442
|
+
const [falling, ...others] = branches.filter((branch) => branch.flow === "fallthrough");
|
|
2443
|
+
if (falling) {
|
|
2444
|
+
return {
|
|
2445
|
+
flow: "fallthrough",
|
|
2446
|
+
initialized: new Set([...falling.initialized].filter((id) => others.every((branch) => branch.initialized.has(id))))
|
|
2447
|
+
};
|
|
2448
|
+
}
|
|
2449
|
+
const [{ flow }] = branches;
|
|
2450
|
+
return {
|
|
2451
|
+
flow: branches.every((branch) => branch.flow === flow) ? flow : "mixed",
|
|
2452
|
+
initialized
|
|
2453
|
+
};
|
|
2454
|
+
};
|
|
2455
|
+
|
|
2456
|
+
class RoutineNormalizer {
|
|
2457
|
+
routine;
|
|
2458
|
+
declarations;
|
|
2459
|
+
parameters;
|
|
2460
|
+
owner;
|
|
2461
|
+
scope;
|
|
2462
|
+
locals;
|
|
2463
|
+
ranges = new Map;
|
|
2464
|
+
counters = new Set;
|
|
2465
|
+
callees = new Set;
|
|
2466
|
+
temporaryCount = 0;
|
|
2467
|
+
constructor(routine, declarations) {
|
|
2468
|
+
this.routine = routine;
|
|
2469
|
+
this.declarations = declarations;
|
|
2470
|
+
if (isBlockRoutine(routine)) {
|
|
2471
|
+
this.owner = routine;
|
|
2472
|
+
this.parameters = routine.inputs;
|
|
2473
|
+
} else {
|
|
2474
|
+
this.owner = routine.owner ? declarations.blocks.get(routine.owner.block) : undefined;
|
|
2475
|
+
this.parameters = routine.parameters;
|
|
2476
|
+
}
|
|
2477
|
+
this.scope = new Map(declarations.globals);
|
|
2478
|
+
for (const item of [
|
|
2479
|
+
...this.parameters,
|
|
2480
|
+
...this.owner ? [...this.owner.state, ...this.owner.outputs] : [],
|
|
2481
|
+
...routine.locals
|
|
2482
|
+
]) {
|
|
2483
|
+
this.scope.set(item.id, item);
|
|
2484
|
+
}
|
|
2485
|
+
this.locals = [...routine.locals];
|
|
2486
|
+
}
|
|
2487
|
+
normalize() {
|
|
2488
|
+
const { routine } = this;
|
|
2489
|
+
if (isBlockRoutine(routine) && routine.standard) {
|
|
2490
|
+
return { routine: { ...routine, body: [] }, callees: this.callees };
|
|
2491
|
+
}
|
|
2492
|
+
return {
|
|
2493
|
+
routine: { ...routine, locals: this.locals, body: this.routineBody() },
|
|
2494
|
+
callees: this.callees
|
|
2495
|
+
};
|
|
2496
|
+
}
|
|
2497
|
+
routineBody() {
|
|
2498
|
+
const normalized = this.body(this.routine.body, new Set(this.parameters.map((item) => item.id)));
|
|
2499
|
+
if (this.routine.result && normalized.flow !== "return") {
|
|
2500
|
+
reject("A typed helper must return on every path.", this.routine.span);
|
|
2501
|
+
}
|
|
2502
|
+
return normalized.body;
|
|
2503
|
+
}
|
|
2504
|
+
temporary(type, span) {
|
|
2505
|
+
const id = this.unclaimedTemporaryId();
|
|
2506
|
+
this.declarations.claimId(id);
|
|
2507
|
+
const item = {
|
|
2508
|
+
id,
|
|
2509
|
+
name: `temporary_${this.temporaryCount}`,
|
|
2510
|
+
type,
|
|
2511
|
+
storage: "local",
|
|
2512
|
+
mutable: true,
|
|
2513
|
+
retention: "none",
|
|
2514
|
+
span
|
|
2515
|
+
};
|
|
2516
|
+
this.locals.push(item);
|
|
2517
|
+
return item;
|
|
2518
|
+
}
|
|
2519
|
+
unclaimedTemporaryId() {
|
|
2520
|
+
const id = temporaryId(this.routine.id, this.temporaryCount++);
|
|
2521
|
+
return this.declarations.hasId(id) ? this.unclaimedTemporaryId() : id;
|
|
2522
|
+
}
|
|
2523
|
+
load(variable, span) {
|
|
2524
|
+
return { kind: "load", root: variable.id, type: variable.type, span };
|
|
2525
|
+
}
|
|
2526
|
+
receiverBlock(id) {
|
|
2527
|
+
const variable = this.scope.get(id);
|
|
2528
|
+
if (variable?.storage !== "instance" && variable?.mode !== "inOut") {
|
|
2529
|
+
return;
|
|
2530
|
+
}
|
|
2531
|
+
return instancedBlock(variable.type, this.declarations.types)?.block;
|
|
2532
|
+
}
|
|
2533
|
+
verifyCall(id, arguments_, span, instance) {
|
|
2534
|
+
const called = this.declarations.signatures.get(id);
|
|
2535
|
+
if (!called || called.parameters.length !== arguments_.length) {
|
|
2536
|
+
reject("Unknown helper or wrong argument count.", span);
|
|
2537
|
+
}
|
|
2538
|
+
if (called.owner) {
|
|
2539
|
+
if (instance) {
|
|
2540
|
+
if (this.receiverBlock(instance) !== called.owner.block) {
|
|
2541
|
+
reject("Method calls require a matching static block instance.", span);
|
|
2542
|
+
}
|
|
2543
|
+
} else if (this.owner?.id !== called.owner.block) {
|
|
2544
|
+
reject("An implicit method call requires its owning block scope.", span);
|
|
2545
|
+
}
|
|
2546
|
+
if (called.owner.access !== "public" && this.owner?.id !== called.owner.block) {
|
|
2547
|
+
reject("Private and protected methods require their owning block scope.", span);
|
|
2548
|
+
}
|
|
2549
|
+
} else if (instance) {
|
|
2550
|
+
reject("Ordinary functions cannot have an instance receiver.", span);
|
|
2551
|
+
}
|
|
2552
|
+
this.callees.add(id);
|
|
2553
|
+
arguments_.forEach((argument, index) => {
|
|
2554
|
+
if (argument.type !== called.parameters[index]?.type) {
|
|
2555
|
+
reject("Helper argument has the wrong PLC type.", argument.span);
|
|
2556
|
+
}
|
|
2557
|
+
});
|
|
2558
|
+
return called;
|
|
2559
|
+
}
|
|
2560
|
+
expression(value, initialized, output, { allowAggregateLoad } = {}) {
|
|
2561
|
+
const type = this.declarations.types.get(value.type);
|
|
2562
|
+
if (!type || !isValueType(value.type, this.declarations.types)) {
|
|
2563
|
+
reject("Unknown or non-value expression type.", value.span);
|
|
2564
|
+
}
|
|
2565
|
+
if (value.kind === "borrow") {
|
|
2566
|
+
reject("Borrowed places are only valid in block update arguments.", value.span);
|
|
2567
|
+
}
|
|
2568
|
+
const common = { type: value.type, span: value.span };
|
|
2569
|
+
if (value.kind === "length") {
|
|
2570
|
+
const array = this.declarations.types.get(value.operand.type);
|
|
2571
|
+
if (array?.kind !== "array" || value.type !== "DINT") {
|
|
2572
|
+
reject("Length requires a fixed array and DINT result.", value.span);
|
|
2573
|
+
}
|
|
2574
|
+
if (value.operand.kind === "load") {
|
|
2575
|
+
const source = this.scope.get(value.operand.place.root);
|
|
2576
|
+
const checked = placeType(value.operand.place, this.declarations.types, this.scope, this.ranges);
|
|
2577
|
+
if (!source || checked.issue || checked.type !== value.operand.type || source.storage === "local" && !initialized.has(source.id)) {
|
|
2578
|
+
reject(checked.issue ?? "Invalid array receiver.", value.span);
|
|
2579
|
+
}
|
|
2580
|
+
this.normalizePath(value.operand.place, initialized, output);
|
|
2581
|
+
} else {
|
|
2582
|
+
this.expression(value.operand, initialized, output, {
|
|
2583
|
+
allowAggregateLoad: true
|
|
2584
|
+
});
|
|
2585
|
+
}
|
|
2586
|
+
return {
|
|
2587
|
+
...common,
|
|
2588
|
+
kind: "constant",
|
|
2589
|
+
value: { kind: "integer", value: String(array.length) }
|
|
2590
|
+
};
|
|
2591
|
+
}
|
|
2592
|
+
if (value.kind === "conditional") {
|
|
2593
|
+
if (value.condition.type !== "BOOL" || value.then.type !== value.type || value.else.type !== value.type) {
|
|
2594
|
+
reject("Invalid conditional types.", value.span);
|
|
2595
|
+
}
|
|
2596
|
+
const condition = this.expression(value.condition, initialized, output);
|
|
2597
|
+
const result = this.temporary(value.type, value.span);
|
|
2598
|
+
const whenTrue = this.branchOperand(value.then, initialized);
|
|
2599
|
+
const whenFalse = this.branchOperand(value.else, initialized);
|
|
2600
|
+
output.push(lowerSelect({
|
|
2601
|
+
result: { root: result.id, type: result.type },
|
|
2602
|
+
condition,
|
|
2603
|
+
whenTrue,
|
|
2604
|
+
whenFalse,
|
|
2605
|
+
span: value.span
|
|
2606
|
+
}));
|
|
2607
|
+
initialized.add(result.id);
|
|
2608
|
+
return this.load(result, value.span);
|
|
2609
|
+
}
|
|
2610
|
+
if (value.kind === "call") {
|
|
2611
|
+
const called = this.verifyCall(value.function, value.arguments, value.span, value.instance);
|
|
2612
|
+
if (called.result !== value.type) {
|
|
2613
|
+
reject("Expression call requires a matching result type.", value.span);
|
|
2614
|
+
}
|
|
2615
|
+
const index = value.instance && this.instanceIndex(value.instance, value.index, initialized, output, value.span);
|
|
2616
|
+
const arguments_ = this.arguments(called.parameters, value.arguments, initialized, output);
|
|
2617
|
+
const result = this.temporary(value.type, value.span);
|
|
2618
|
+
output.push({
|
|
2619
|
+
kind: "invoke",
|
|
2620
|
+
function: value.function,
|
|
2621
|
+
...value.instance && { instance: value.instance },
|
|
2622
|
+
...index && { index },
|
|
2623
|
+
arguments: arguments_,
|
|
2624
|
+
destination: result.id,
|
|
2625
|
+
span: value.span
|
|
2626
|
+
});
|
|
2627
|
+
initialized.add(result.id);
|
|
2628
|
+
return this.load(result, value.span);
|
|
2629
|
+
}
|
|
2630
|
+
const issue = expressionIssue(value, this.declarations.types, this.scope, this.ranges);
|
|
2631
|
+
if (issue) {
|
|
2632
|
+
reject(issue, value.span);
|
|
2633
|
+
}
|
|
2634
|
+
switch (value.kind) {
|
|
2635
|
+
case "copy":
|
|
2636
|
+
return this.expression(value.operand, initialized, output, {
|
|
2637
|
+
allowAggregateLoad: true
|
|
2638
|
+
});
|
|
2639
|
+
case "record":
|
|
2640
|
+
case "array": {
|
|
2641
|
+
const result = this.temporary(value.type, value.span);
|
|
2642
|
+
if (value.kind === "record") {
|
|
2643
|
+
for (const [name, operand] of Object.entries(value.fields)) {
|
|
2644
|
+
output.push({
|
|
2645
|
+
kind: "assign",
|
|
2646
|
+
root: result.id,
|
|
2647
|
+
path: [{ kind: "field", name }],
|
|
2648
|
+
value: this.expression(operand, initialized, output),
|
|
2649
|
+
span: operand.span
|
|
2650
|
+
});
|
|
2651
|
+
}
|
|
2652
|
+
} else {
|
|
2653
|
+
if (type.kind !== "array") {
|
|
2654
|
+
reject("Invalid array construction.", value.span);
|
|
2655
|
+
}
|
|
2656
|
+
value.items.forEach((operand, index) => {
|
|
2657
|
+
output.push({
|
|
2658
|
+
kind: "assign",
|
|
2659
|
+
root: result.id,
|
|
2660
|
+
path: [
|
|
2661
|
+
{
|
|
2662
|
+
kind: "index",
|
|
2663
|
+
value: {
|
|
2664
|
+
kind: "constant",
|
|
2665
|
+
type: "DINT",
|
|
2666
|
+
value: {
|
|
2667
|
+
kind: "integer",
|
|
2668
|
+
value: String(type.lowerBound + index)
|
|
2669
|
+
},
|
|
2670
|
+
span: operand.span
|
|
2671
|
+
}
|
|
2672
|
+
}
|
|
2673
|
+
],
|
|
2674
|
+
value: this.expression(operand, initialized, output),
|
|
2675
|
+
span: operand.span
|
|
2676
|
+
});
|
|
2677
|
+
});
|
|
2678
|
+
}
|
|
2679
|
+
initialized.add(result.id);
|
|
2680
|
+
return this.load(result, value.span);
|
|
2681
|
+
}
|
|
2682
|
+
case "constant": {
|
|
2683
|
+
if (!aggregate(type)) {
|
|
2684
|
+
return { ...common, kind: "constant", value: value.value };
|
|
2685
|
+
}
|
|
2686
|
+
const result = this.temporary(value.type, value.span);
|
|
2687
|
+
output.push({
|
|
2688
|
+
kind: "assign",
|
|
2689
|
+
root: result.id,
|
|
2690
|
+
value: { ...common, kind: "constant", value: value.value },
|
|
2691
|
+
span: value.span
|
|
2692
|
+
});
|
|
2693
|
+
initialized.add(result.id);
|
|
2694
|
+
return this.load(result, value.span);
|
|
2695
|
+
}
|
|
2696
|
+
case "load": {
|
|
2697
|
+
const source = this.scope.get(value.place.root);
|
|
2698
|
+
const checked = placeType(value.place, this.declarations.types, this.scope, this.ranges);
|
|
2699
|
+
if (!source || checked.issue || checked.type !== value.type) {
|
|
2700
|
+
reject(checked.issue ?? "Invalid PLC load.", value.span);
|
|
2701
|
+
}
|
|
2702
|
+
if (aggregate(type) && !allowAggregateLoad) {
|
|
2703
|
+
reject("Aggregate loads require explicit copy or a readonly value argument.", value.span);
|
|
2704
|
+
}
|
|
2705
|
+
if (source.storage === "local" && !initialized.has(source.id)) {
|
|
2706
|
+
reject("Local read before initialization.", value.span);
|
|
2707
|
+
}
|
|
2708
|
+
const first = value.place.path[0];
|
|
2709
|
+
if (source.storage === "instance" && value.place.path.length === 1 && first?.kind === "field" && first.name === "out" && type.kind === "record") {
|
|
2710
|
+
const result = this.temporary(value.type, value.span);
|
|
2711
|
+
for (const field of type.fields) {
|
|
2712
|
+
const selected = {
|
|
2713
|
+
kind: "load",
|
|
2714
|
+
type: field.type,
|
|
2715
|
+
place: {
|
|
2716
|
+
root: source.id,
|
|
2717
|
+
path: [
|
|
2718
|
+
...value.place.path,
|
|
2719
|
+
{ kind: "field", name: field.name }
|
|
2720
|
+
]
|
|
2721
|
+
},
|
|
2722
|
+
span: value.span
|
|
2723
|
+
};
|
|
2724
|
+
const captured = this.expression(selected, initialized, output, {
|
|
2725
|
+
allowAggregateLoad: true
|
|
2726
|
+
});
|
|
2727
|
+
output.push({
|
|
2728
|
+
kind: "assign",
|
|
2729
|
+
root: result.id,
|
|
2730
|
+
path: [{ kind: "field", name: field.name }],
|
|
2731
|
+
value: captured,
|
|
2732
|
+
span: value.span
|
|
2733
|
+
});
|
|
2734
|
+
}
|
|
2735
|
+
initialized.add(result.id);
|
|
2736
|
+
return this.load(result, value.span);
|
|
2737
|
+
}
|
|
2738
|
+
const path = this.normalizePath(value.place, initialized, output);
|
|
2739
|
+
if (source.storage === "constant" && source.initial && !path.length) {
|
|
2740
|
+
return { ...common, kind: "constant", value: source.initial };
|
|
2741
|
+
}
|
|
2742
|
+
const result = this.temporary(value.type, value.span);
|
|
2743
|
+
output.push({
|
|
2744
|
+
kind: "assign",
|
|
2745
|
+
root: result.id,
|
|
2746
|
+
value: {
|
|
2747
|
+
...common,
|
|
2748
|
+
kind: "load",
|
|
2749
|
+
root: source.id,
|
|
2750
|
+
...path.length && { path }
|
|
2751
|
+
},
|
|
2752
|
+
span: value.span
|
|
2753
|
+
});
|
|
2754
|
+
const bound = interval(value, this.declarations.types, this.scope, this.ranges);
|
|
2755
|
+
if (bound) {
|
|
2756
|
+
this.ranges.set(result.id, bound);
|
|
2757
|
+
}
|
|
2758
|
+
initialized.add(result.id);
|
|
2759
|
+
return this.load(result, value.span);
|
|
2760
|
+
}
|
|
2761
|
+
case "unary": {
|
|
2762
|
+
const operand = this.expression(value.operand, initialized, output);
|
|
2763
|
+
const constant = fold(value, this.scope, this.declarations.types);
|
|
2764
|
+
return constant ? { ...common, kind: "constant", value: constant } : { ...common, kind: "unary", operator: value.operator, operand };
|
|
2765
|
+
}
|
|
2766
|
+
case "convert": {
|
|
2767
|
+
const operand = this.expression(value.operand, initialized, output);
|
|
2768
|
+
if (value.type === value.operand.type) {
|
|
2769
|
+
return operand;
|
|
2770
|
+
}
|
|
2771
|
+
const constant = fold(value, this.scope, this.declarations.types);
|
|
2772
|
+
return constant ? { ...common, kind: "constant", value: constant } : { ...common, kind: "convert", operand, policy: value.policy };
|
|
2773
|
+
}
|
|
2774
|
+
case "binary": {
|
|
2775
|
+
const left = this.expression(value.left, initialized, output);
|
|
2776
|
+
if (value.operator === "and" || value.operator === "or") {
|
|
2777
|
+
const result = this.temporary("BOOL", value.span);
|
|
2778
|
+
const right = this.branchOperand(value.right, initialized);
|
|
2779
|
+
output.push(...lowerLogical({
|
|
2780
|
+
operator: value.operator,
|
|
2781
|
+
result: { root: result.id, type: result.type },
|
|
2782
|
+
left,
|
|
2783
|
+
right,
|
|
2784
|
+
span: value.span
|
|
2785
|
+
}));
|
|
2786
|
+
initialized.add(result.id);
|
|
2787
|
+
return this.load(result, value.span);
|
|
2788
|
+
}
|
|
2789
|
+
const right = this.expression(value.right, initialized, output);
|
|
2790
|
+
const constant = fold(value, this.scope, this.declarations.types);
|
|
2791
|
+
if (constant) {
|
|
2792
|
+
return { ...common, kind: "constant", value: constant };
|
|
2793
|
+
}
|
|
2794
|
+
return {
|
|
2795
|
+
...common,
|
|
2796
|
+
kind: "binary",
|
|
2797
|
+
operator: value.operator,
|
|
2798
|
+
left,
|
|
2799
|
+
right,
|
|
2800
|
+
...value.policy && { policy: value.policy }
|
|
2801
|
+
};
|
|
2802
|
+
}
|
|
2803
|
+
}
|
|
2804
|
+
}
|
|
2805
|
+
branchOperand(operand, initialized) {
|
|
2806
|
+
const statements = [];
|
|
2807
|
+
const value = this.expression(operand, new Set(initialized), statements);
|
|
2808
|
+
return { statements, value };
|
|
2809
|
+
}
|
|
2810
|
+
normalizePath(place, initialized, output) {
|
|
2811
|
+
return place.path.map((segment) => segment.kind === "field" ? segment : {
|
|
2812
|
+
kind: "index",
|
|
2813
|
+
value: this.expression(segment.value, initialized, output)
|
|
2814
|
+
});
|
|
2815
|
+
}
|
|
2816
|
+
destination(place, type, initialized, span) {
|
|
2817
|
+
const target = this.scope.get(place.root);
|
|
2818
|
+
const initializing = target?.storage === "local" && !initialized.has(place.root) && !place.path.length;
|
|
2819
|
+
const checked = placeType(place, this.declarations.types, this.scope, this.ranges, !initializing);
|
|
2820
|
+
if (!target || checked.issue || checked.type !== type || this.counters.has(place.root)) {
|
|
2821
|
+
reject(checked.issue ?? "Invalid assignment destination.", span);
|
|
2822
|
+
}
|
|
2823
|
+
if (place.path.length && target.storage === "local" && !initialized.has(target.id)) {
|
|
2824
|
+
reject("Initialize the whole aggregate before assigning fields.", span);
|
|
2825
|
+
}
|
|
2826
|
+
return target;
|
|
2827
|
+
}
|
|
2828
|
+
instanceIndex(instance, index, initialized, output, span) {
|
|
2829
|
+
if (!index) {
|
|
2830
|
+
return;
|
|
2831
|
+
}
|
|
2832
|
+
const checked = placeType({ root: instance, path: [{ kind: "index", value: index }] }, this.declarations.types, this.scope, this.ranges);
|
|
2833
|
+
if (checked.issue) {
|
|
2834
|
+
reject(checked.issue, span);
|
|
2835
|
+
}
|
|
2836
|
+
return this.expression(index, initialized, output);
|
|
2837
|
+
}
|
|
2838
|
+
blockUpdate(item, initialized, output) {
|
|
2839
|
+
const block = this.receiverBlock(item.instance);
|
|
2840
|
+
const called = block && this.declarations.blocks.get(block);
|
|
2841
|
+
if (!called) {
|
|
2842
|
+
reject("Updates require a statically allocated block instance.", item.span);
|
|
2843
|
+
}
|
|
2844
|
+
const index = this.instanceIndex(item.instance, item.index, initialized, output, item.span);
|
|
2845
|
+
const supplied = Object.entries(item.inputs).flatMap(([name, value]) => {
|
|
2846
|
+
const input = called.inputs.find((port) => port.name === name);
|
|
2847
|
+
return input ? [{ input, value }] : [];
|
|
2848
|
+
});
|
|
2849
|
+
if (Object.keys(item.inputs).length !== called.inputs.length || supplied.length !== called.inputs.length) {
|
|
2850
|
+
reject("Block update must supply every named input exactly once.", item.span);
|
|
2851
|
+
}
|
|
2852
|
+
this.callees.add(called.id);
|
|
2853
|
+
const inputs = Object.fromEntries(supplied.map(({ input, value }) => [
|
|
2854
|
+
input.name,
|
|
2855
|
+
this.argument(input, value, initialized, output)
|
|
2856
|
+
]));
|
|
2857
|
+
output.push({
|
|
2858
|
+
kind: "blockUpdate",
|
|
2859
|
+
instance: item.instance,
|
|
2860
|
+
...index && { index },
|
|
2861
|
+
inputs,
|
|
2862
|
+
span: item.span
|
|
2863
|
+
});
|
|
2864
|
+
}
|
|
2865
|
+
arguments(parameters, values, initialized, output) {
|
|
2866
|
+
return values.map((value, index) => {
|
|
2867
|
+
const parameter = parameters[index];
|
|
2868
|
+
if (!parameter) {
|
|
2869
|
+
throw new Error("A call passes more arguments than its callee declares.");
|
|
2870
|
+
}
|
|
2871
|
+
return this.argument(parameter, value, initialized, output);
|
|
2872
|
+
});
|
|
2873
|
+
}
|
|
2874
|
+
argument(input, value, initialized, output) {
|
|
2875
|
+
if (value.type !== input.type) {
|
|
2876
|
+
reject("Block input differs from its concrete PLC type.", value.span);
|
|
2877
|
+
}
|
|
2878
|
+
if (input.mode === "inOut" && value.kind === "borrow") {
|
|
2879
|
+
return this.borrow(value, initialized, output);
|
|
2880
|
+
}
|
|
2881
|
+
if (input.mode === "inOut") {
|
|
2882
|
+
if (this.declarations.types.get(value.type)?.kind === "block") {
|
|
2883
|
+
reject("Pass a block instance by name.", value.span);
|
|
2884
|
+
}
|
|
2885
|
+
const temporary = this.temporary(value.type, value.span);
|
|
2886
|
+
output.push({
|
|
2887
|
+
kind: "assign",
|
|
2888
|
+
root: temporary.id,
|
|
2889
|
+
value: this.expression(value, initialized, output),
|
|
2890
|
+
span: value.span
|
|
2891
|
+
});
|
|
2892
|
+
initialized.add(temporary.id);
|
|
2893
|
+
return {
|
|
2894
|
+
kind: "borrow",
|
|
2895
|
+
type: value.type,
|
|
2896
|
+
place: { root: temporary.id, path: [] },
|
|
2897
|
+
span: value.span
|
|
2898
|
+
};
|
|
2899
|
+
}
|
|
2900
|
+
if (value.kind === "borrow") {
|
|
2901
|
+
reject("Readonly value inputs cannot receive borrowed references.", value.span);
|
|
2902
|
+
}
|
|
2903
|
+
return this.expression(value, initialized, output, {
|
|
2904
|
+
allowAggregateLoad: true
|
|
2905
|
+
});
|
|
2906
|
+
}
|
|
2907
|
+
borrow(value, initialized, output) {
|
|
2908
|
+
const block = this.declarations.types.get(value.type)?.kind === "block";
|
|
2909
|
+
const root = this.scope.get(value.place.root);
|
|
2910
|
+
const checked = placeType(value.place, this.declarations.types, this.scope, this.ranges, !block);
|
|
2911
|
+
if (!root || checked.issue || checked.type !== value.type || !block && !isValueType(value.type, this.declarations.types) || this.counters.has(root.id) || root.storage === "local" && !initialized.has(root.id)) {
|
|
2912
|
+
reject(checked.issue ?? "Borrow requires initialized mutable value storage of the exact type.", value.span);
|
|
2913
|
+
}
|
|
2914
|
+
return {
|
|
2915
|
+
kind: "borrow",
|
|
2916
|
+
type: value.type,
|
|
2917
|
+
place: {
|
|
2918
|
+
root: value.place.root,
|
|
2919
|
+
path: this.normalizePath(value.place, initialized, output)
|
|
2920
|
+
},
|
|
2921
|
+
span: value.span
|
|
2922
|
+
};
|
|
2923
|
+
}
|
|
2924
|
+
body(statements, initialized) {
|
|
2925
|
+
const output = [];
|
|
2926
|
+
const state = statements.reduce((reached, item) => reached.flow === "fallthrough" ? this.statement(item, reached.initialized, output) : reached, { flow: "fallthrough", initialized });
|
|
2927
|
+
return { body: output, ...state };
|
|
2928
|
+
}
|
|
2929
|
+
statement(item, initialized, output) {
|
|
2930
|
+
switch (item.kind) {
|
|
2931
|
+
case "assign":
|
|
2932
|
+
this.assign(item, initialized, output);
|
|
2933
|
+
return { flow: "fallthrough", initialized };
|
|
2934
|
+
case "blockUpdate":
|
|
2935
|
+
this.blockUpdate(item, initialized, output);
|
|
2936
|
+
return { flow: "fallthrough", initialized };
|
|
2937
|
+
case "invoke":
|
|
2938
|
+
this.invoke(item, initialized, output);
|
|
2939
|
+
return { flow: "fallthrough", initialized };
|
|
2940
|
+
case "if":
|
|
2941
|
+
return this.ifStatement(item, initialized, output);
|
|
2942
|
+
case "switch":
|
|
2943
|
+
return this.switchStatement(item, initialized, output);
|
|
2944
|
+
case "for":
|
|
2945
|
+
this.forStatement(item, initialized, output);
|
|
2946
|
+
return { flow: "fallthrough", initialized };
|
|
2947
|
+
case "return": {
|
|
2948
|
+
if (item.value?.type !== this.routine.result) {
|
|
2949
|
+
reject("Return differs from the function signature.", item.span);
|
|
2950
|
+
}
|
|
2951
|
+
const value = item.value && this.expression(item.value, initialized, output);
|
|
2952
|
+
output.push({
|
|
2953
|
+
kind: "return",
|
|
2954
|
+
span: item.span,
|
|
2955
|
+
...value && { value }
|
|
2956
|
+
});
|
|
2957
|
+
return { flow: "return", initialized };
|
|
2958
|
+
}
|
|
2959
|
+
case "telemetry":
|
|
2960
|
+
this.telemetry(item, initialized, output);
|
|
2961
|
+
return { flow: "fallthrough", initialized };
|
|
2962
|
+
case "break":
|
|
2963
|
+
case "continue":
|
|
2964
|
+
if (!this.counters.size) {
|
|
2965
|
+
reject("Loop control appears outside a bounded loop.", item.span);
|
|
2966
|
+
}
|
|
2967
|
+
output.push({ kind: item.kind, span: item.span });
|
|
2968
|
+
return { flow: "loop", initialized };
|
|
2969
|
+
}
|
|
2970
|
+
}
|
|
2971
|
+
assign(item, initialized, output) {
|
|
2972
|
+
this.destination(item.destination, item.value.type, initialized, item.span);
|
|
2973
|
+
const path = this.normalizePath(item.destination, initialized, output);
|
|
2974
|
+
const bound = !path.length && this.scope.get(item.destination.root)?.mutable === false && interval(item.value, this.declarations.types, this.scope, this.ranges);
|
|
2975
|
+
const value = this.expression(item.value, initialized, output);
|
|
2976
|
+
if (bound) {
|
|
2977
|
+
this.ranges.set(item.destination.root, bound);
|
|
2978
|
+
}
|
|
2979
|
+
if (!path.length) {
|
|
2980
|
+
initialized.add(item.destination.root);
|
|
2981
|
+
}
|
|
2982
|
+
output.push({
|
|
2983
|
+
kind: "assign",
|
|
2984
|
+
root: item.destination.root,
|
|
2985
|
+
...path.length && { path },
|
|
2986
|
+
value,
|
|
2987
|
+
span: item.span
|
|
2988
|
+
});
|
|
2989
|
+
}
|
|
2990
|
+
invoke(item, initialized, output) {
|
|
2991
|
+
const called = this.verifyCall(item.function, item.arguments, item.span, item.instance);
|
|
2992
|
+
if (item.destination) {
|
|
2993
|
+
if (item.destination.path.length || !called.result) {
|
|
2994
|
+
reject("Invalid helper destination.", item.span);
|
|
2995
|
+
}
|
|
2996
|
+
this.destination(item.destination, called.result, initialized, item.span);
|
|
2997
|
+
}
|
|
2998
|
+
const index = item.instance && this.instanceIndex(item.instance, item.index, initialized, output, item.span);
|
|
2999
|
+
const arguments_ = this.arguments(called.parameters, item.arguments, initialized, output);
|
|
3000
|
+
output.push({
|
|
3001
|
+
kind: "invoke",
|
|
3002
|
+
function: item.function,
|
|
3003
|
+
...item.instance && { instance: item.instance },
|
|
3004
|
+
...index && { index },
|
|
3005
|
+
arguments: arguments_,
|
|
3006
|
+
span: item.span,
|
|
3007
|
+
...item.destination && { destination: item.destination.root }
|
|
3008
|
+
});
|
|
3009
|
+
if (item.destination) {
|
|
3010
|
+
initialized.add(item.destination.root);
|
|
3011
|
+
}
|
|
3012
|
+
}
|
|
3013
|
+
ifStatement(item, initialized, output) {
|
|
3014
|
+
if (item.condition.type !== "BOOL") {
|
|
3015
|
+
reject("Conditions require BOOL.", item.span);
|
|
3016
|
+
}
|
|
3017
|
+
const condition = this.expression(item.condition, initialized, output);
|
|
3018
|
+
const originalRanges = new Map(this.ranges);
|
|
3019
|
+
const branch = (statements, truth) => {
|
|
3020
|
+
this.ranges.clear();
|
|
3021
|
+
for (const [root, range] of narrowRanges(item.condition, truth, this.declarations.types, this.scope, originalRanges)) {
|
|
3022
|
+
this.ranges.set(root, range);
|
|
3023
|
+
}
|
|
3024
|
+
try {
|
|
3025
|
+
return this.body(statements, new Set(initialized));
|
|
3026
|
+
} finally {
|
|
3027
|
+
this.ranges.clear();
|
|
3028
|
+
for (const [root, range] of originalRanges) {
|
|
3029
|
+
this.ranges.set(root, range);
|
|
3030
|
+
}
|
|
3031
|
+
}
|
|
3032
|
+
};
|
|
3033
|
+
const yes = branch(item.then, true);
|
|
3034
|
+
const no = branch(item.else, false);
|
|
3035
|
+
output.push({
|
|
3036
|
+
kind: "if",
|
|
3037
|
+
condition,
|
|
3038
|
+
then: yes.body,
|
|
3039
|
+
else: no.body,
|
|
3040
|
+
span: item.span
|
|
3041
|
+
});
|
|
3042
|
+
return join([yes, no], initialized);
|
|
3043
|
+
}
|
|
3044
|
+
switchStatement(item, initialized, output) {
|
|
3045
|
+
const value = this.expression(item.value, initialized, output);
|
|
3046
|
+
const type = lookup(this.declarations.types, item.value.type, "type");
|
|
3047
|
+
const seen = new Set;
|
|
3048
|
+
const cases = item.cases.map((branch) => {
|
|
3049
|
+
for (const constant of branch.values) {
|
|
3050
|
+
if (!valueFits(constant, type, this.declarations.types)) {
|
|
3051
|
+
reject("Invalid case constant.", item.span);
|
|
3052
|
+
}
|
|
3053
|
+
const key = JSON.stringify(constant);
|
|
3054
|
+
if (seen.has(key)) {
|
|
3055
|
+
reject("Duplicate case constant.", item.span);
|
|
3056
|
+
}
|
|
3057
|
+
seen.add(key);
|
|
3058
|
+
}
|
|
3059
|
+
return {
|
|
3060
|
+
values: branch.values,
|
|
3061
|
+
result: this.body(branch.body, new Set(initialized))
|
|
3062
|
+
};
|
|
3063
|
+
});
|
|
3064
|
+
const fallback = this.body(item.fallback, new Set(initialized));
|
|
3065
|
+
output.push({
|
|
3066
|
+
kind: "switch",
|
|
3067
|
+
value,
|
|
3068
|
+
cases: cases.map((branch) => ({
|
|
3069
|
+
values: branch.values,
|
|
3070
|
+
body: branch.result.body
|
|
3071
|
+
})),
|
|
3072
|
+
fallback: fallback.body,
|
|
3073
|
+
span: item.span
|
|
3074
|
+
});
|
|
3075
|
+
return join([fallback, ...cases.map((branch) => branch.result)], initialized);
|
|
3076
|
+
}
|
|
3077
|
+
forStatement(item, initialized, output) {
|
|
3078
|
+
const counter = this.scope.get(item.counter);
|
|
3079
|
+
const counterType = counter && this.declarations.types.get(counter.type);
|
|
3080
|
+
const storage = item.counterScope === "existing" ? ["local", "module", "field"] : ["local"];
|
|
3081
|
+
if (!counter || !storage.includes(counter.storage) || !counter.mutable || counterType?.kind !== "integer" || this.counters.has(counter.id) || item.start.type !== counter.type || item.limit.type !== counter.type || !canonicalInteger.test(item.step) || item.step === "0") {
|
|
3082
|
+
reject("Invalid bounded loop.", item.span);
|
|
3083
|
+
}
|
|
3084
|
+
const start = fold(item.start, this.scope, this.declarations.types);
|
|
3085
|
+
const limit = fold(item.limit, this.scope, this.declarations.types);
|
|
3086
|
+
const startRange = interval(item.start, this.declarations.types, this.scope, this.ranges);
|
|
3087
|
+
const limitRange = interval(item.limit, this.declarations.types, this.scope, this.ranges);
|
|
3088
|
+
if (!startRange || !limitRange) {
|
|
3089
|
+
reject("Loop bounds require finite integer ranges.", item.span);
|
|
3090
|
+
}
|
|
3091
|
+
const step = BigInt(item.step);
|
|
3092
|
+
const { first, last, count, range, terminal } = loopBounds(startRange, limitRange, step, item.exclusive);
|
|
3093
|
+
const dynamic = start?.kind !== "integer" || limit?.kind !== "integer";
|
|
3094
|
+
if (count > maxLoopIterations || Number(count) !== item.maxIterations) {
|
|
3095
|
+
reject("Loop iteration proof differs from its bounds.", item.span);
|
|
3096
|
+
}
|
|
3097
|
+
if (item.counterScope === "existing") {
|
|
3098
|
+
if (count > 0n && !admits(integerRange(counterType), terminal)) {
|
|
3099
|
+
reject("The existing loop counter overflows on termination.", item.span);
|
|
3100
|
+
}
|
|
3101
|
+
}
|
|
3102
|
+
const evaluatedStart = this.expression(item.start, initialized, output);
|
|
3103
|
+
const evaluatedLimit = this.expression(item.limit, initialized, output);
|
|
3104
|
+
initialized.add(counter.id);
|
|
3105
|
+
this.counters.add(counter.id);
|
|
3106
|
+
this.ranges.set(counter.id, range);
|
|
3107
|
+
const nested = this.body(item.body, new Set(initialized));
|
|
3108
|
+
this.counters.delete(counter.id);
|
|
3109
|
+
this.ranges.delete(counter.id);
|
|
3110
|
+
if (item.counterScope !== "existing") {
|
|
3111
|
+
initialized.delete(counter.id);
|
|
3112
|
+
}
|
|
3113
|
+
output.push({
|
|
3114
|
+
kind: "for",
|
|
3115
|
+
counter: counter.id,
|
|
3116
|
+
...item.counterScope && { counterScope: item.counterScope },
|
|
3117
|
+
start: { kind: "integer", value: String(first) },
|
|
3118
|
+
limit: { kind: "integer", value: String(last) },
|
|
3119
|
+
...dynamic && {
|
|
3120
|
+
dynamic: {
|
|
3121
|
+
start: evaluatedStart,
|
|
3122
|
+
limit: evaluatedLimit,
|
|
3123
|
+
...item.exclusive && { exclusive: item.exclusive }
|
|
3124
|
+
}
|
|
3125
|
+
},
|
|
3126
|
+
step: item.step,
|
|
3127
|
+
maxIterations: item.maxIterations,
|
|
3128
|
+
body: nested.body,
|
|
3129
|
+
span: item.span
|
|
3130
|
+
});
|
|
3131
|
+
}
|
|
3132
|
+
telemetry(item, initialized, output) {
|
|
3133
|
+
const evaluate = (value) => this.expression(value, initialized, output);
|
|
3134
|
+
const { record } = item;
|
|
3135
|
+
output.push({
|
|
3136
|
+
kind: "telemetry",
|
|
3137
|
+
record: record.kind === "exception" ? { kind: "exception", code: evaluate(record.code) } : record,
|
|
3138
|
+
properties: item.properties.map(({ name, value, length }) => {
|
|
3139
|
+
if (!length) {
|
|
3140
|
+
return { name, value: evaluate(value) };
|
|
3141
|
+
}
|
|
3142
|
+
if (value.kind !== "borrow") {
|
|
3143
|
+
reject("Telemetry text reads a byte array in place.", value.span);
|
|
3144
|
+
}
|
|
3145
|
+
return {
|
|
3146
|
+
name,
|
|
3147
|
+
value: this.borrow(value, initialized, output),
|
|
3148
|
+
length: evaluate(length)
|
|
3149
|
+
};
|
|
3150
|
+
}),
|
|
3151
|
+
span: item.span
|
|
3152
|
+
});
|
|
3153
|
+
}
|
|
3154
|
+
}
|
|
3155
|
+
|
|
3156
|
+
// packages/compiler/src/ir/normalize.ts
|
|
3157
|
+
function normalizeModule(module) {
|
|
3158
|
+
try {
|
|
3159
|
+
const declarations = new ModuleDeclarations(module);
|
|
3160
|
+
checkStaticAllocation(module, declarations);
|
|
3161
|
+
const functions = [];
|
|
3162
|
+
const blocks = [];
|
|
3163
|
+
const edges = new Map;
|
|
3164
|
+
for (const source of [...module.functions, ...module.blocks]) {
|
|
3165
|
+
const normalized = new RoutineNormalizer(source, declarations).normalize();
|
|
3166
|
+
edges.set(source.id, normalized.callees);
|
|
3167
|
+
if (isBlockRoutine(normalized.routine)) {
|
|
3168
|
+
blocks.push(normalized.routine);
|
|
3169
|
+
} else {
|
|
3170
|
+
functions.push(normalized.routine);
|
|
3171
|
+
}
|
|
3172
|
+
}
|
|
3173
|
+
const linked = linkModule(module, declarations, functions, blocks, edges);
|
|
3174
|
+
return {
|
|
3175
|
+
core: admitCore({ ...structuredClone(linked), [verified]: true }),
|
|
3176
|
+
diagnostics: []
|
|
3177
|
+
};
|
|
3178
|
+
} catch (cause) {
|
|
3179
|
+
if (cause instanceof InvalidCore) {
|
|
3180
|
+
return { diagnostics: [cause.diagnostic] };
|
|
3181
|
+
}
|
|
3182
|
+
throw cause;
|
|
3183
|
+
}
|
|
3184
|
+
}
|
|
3185
|
+
// packages/compiler/src/ir/operands.ts
|
|
3186
|
+
var pathIndexes = (path = []) => path.flatMap((segment) => segment.kind === "index" ? [segment.value] : []);
|
|
3187
|
+
var mapPath = (path, map) => path.map((segment) => segment.kind === "field" ? segment : { kind: "index", value: map(segment.value) });
|
|
3188
|
+
var subexpressions = (value) => {
|
|
3189
|
+
switch (value.kind) {
|
|
3190
|
+
case "constant":
|
|
3191
|
+
return [];
|
|
3192
|
+
case "load":
|
|
3193
|
+
return pathIndexes(value.path);
|
|
3194
|
+
case "borrow":
|
|
3195
|
+
return pathIndexes(value.place.path);
|
|
3196
|
+
case "unary":
|
|
3197
|
+
case "convert":
|
|
3198
|
+
return [value.operand];
|
|
3199
|
+
case "binary":
|
|
3200
|
+
return [value.left, value.right];
|
|
3201
|
+
}
|
|
3202
|
+
};
|
|
3203
|
+
var mapExpression = (value, map) => {
|
|
3204
|
+
switch (value.kind) {
|
|
3205
|
+
case "constant":
|
|
3206
|
+
return value;
|
|
3207
|
+
case "load":
|
|
3208
|
+
return value.path ? { ...value, path: mapPath(value.path, map) } : value;
|
|
3209
|
+
case "borrow":
|
|
3210
|
+
return {
|
|
3211
|
+
...value,
|
|
3212
|
+
place: { ...value.place, path: mapPath(value.place.path, map) }
|
|
3213
|
+
};
|
|
3214
|
+
case "unary":
|
|
3215
|
+
case "convert":
|
|
3216
|
+
return { ...value, operand: map(value.operand) };
|
|
3217
|
+
case "binary":
|
|
3218
|
+
return { ...value, left: map(value.left), right: map(value.right) };
|
|
3219
|
+
}
|
|
3220
|
+
};
|
|
3221
|
+
var statementExpressions = (item) => {
|
|
3222
|
+
switch (item.kind) {
|
|
3223
|
+
case "assign":
|
|
3224
|
+
return [...pathIndexes(item.path), item.value];
|
|
3225
|
+
case "if":
|
|
3226
|
+
return [item.condition];
|
|
3227
|
+
case "switch":
|
|
3228
|
+
return [item.value];
|
|
3229
|
+
case "for":
|
|
3230
|
+
return item.dynamic ? [item.dynamic.start, item.dynamic.limit] : [];
|
|
3231
|
+
case "invoke":
|
|
3232
|
+
return [...item.index ? [item.index] : [], ...item.arguments];
|
|
3233
|
+
case "blockUpdate":
|
|
3234
|
+
return [
|
|
3235
|
+
...item.index ? [item.index] : [],
|
|
3236
|
+
...Object.values(item.inputs)
|
|
3237
|
+
];
|
|
3238
|
+
case "return":
|
|
3239
|
+
return item.value ? [item.value] : [];
|
|
3240
|
+
case "telemetry":
|
|
3241
|
+
return telemetryOperands(item);
|
|
3242
|
+
case "break":
|
|
3243
|
+
case "continue":
|
|
3244
|
+
return [];
|
|
3245
|
+
}
|
|
3246
|
+
};
|
|
3247
|
+
var mapStatementExpressions = (item, map) => {
|
|
3248
|
+
switch (item.kind) {
|
|
3249
|
+
case "assign":
|
|
3250
|
+
return {
|
|
3251
|
+
...item,
|
|
3252
|
+
...item.path && { path: mapPath(item.path, map) },
|
|
3253
|
+
value: map(item.value)
|
|
3254
|
+
};
|
|
3255
|
+
case "if":
|
|
3256
|
+
return { ...item, condition: map(item.condition) };
|
|
3257
|
+
case "switch":
|
|
3258
|
+
return { ...item, value: map(item.value) };
|
|
3259
|
+
case "for":
|
|
3260
|
+
return item.dynamic ? {
|
|
3261
|
+
...item,
|
|
3262
|
+
dynamic: {
|
|
3263
|
+
...item.dynamic,
|
|
3264
|
+
start: map(item.dynamic.start),
|
|
3265
|
+
limit: map(item.dynamic.limit)
|
|
3266
|
+
}
|
|
3267
|
+
} : item;
|
|
3268
|
+
case "invoke":
|
|
3269
|
+
return {
|
|
3270
|
+
...item,
|
|
3271
|
+
...item.index && { index: map(item.index) },
|
|
3272
|
+
arguments: item.arguments.map(map)
|
|
3273
|
+
};
|
|
3274
|
+
case "blockUpdate":
|
|
3275
|
+
return {
|
|
3276
|
+
...item,
|
|
3277
|
+
...item.index && { index: map(item.index) },
|
|
3278
|
+
inputs: Object.fromEntries(Object.entries(item.inputs).map(([name, input]) => [
|
|
3279
|
+
name,
|
|
3280
|
+
map(input)
|
|
3281
|
+
]))
|
|
3282
|
+
};
|
|
3283
|
+
case "return":
|
|
3284
|
+
return item.value ? { ...item, value: map(item.value) } : item;
|
|
3285
|
+
case "telemetry":
|
|
3286
|
+
return {
|
|
3287
|
+
...item,
|
|
3288
|
+
properties: item.properties.map((property) => ({
|
|
3289
|
+
...property,
|
|
3290
|
+
value: map(property.value),
|
|
3291
|
+
...property.length && { length: map(property.length) }
|
|
3292
|
+
})),
|
|
3293
|
+
...item.record.kind === "exception" && {
|
|
3294
|
+
record: { ...item.record, code: map(item.record.code) }
|
|
3295
|
+
}
|
|
3296
|
+
};
|
|
3297
|
+
case "break":
|
|
3298
|
+
case "continue":
|
|
3299
|
+
return item;
|
|
3300
|
+
}
|
|
3301
|
+
};
|
|
3302
|
+
// packages/compiler/src/ir/share.ts
|
|
3303
|
+
import { parse } from "node:path";
|
|
3304
|
+
function shareRoutines(core, partition) {
|
|
3305
|
+
const tables = coreTables(core);
|
|
3306
|
+
const globals = new Map(core.variables.map((item) => [item.id, item]));
|
|
3307
|
+
const entries = new Set(core.programs.map((program) => program.entry));
|
|
3308
|
+
const bodies = new Map([...core.functions, ...core.blocks].map((routine) => [
|
|
3309
|
+
routine.id,
|
|
3310
|
+
routine.body
|
|
3311
|
+
]));
|
|
3312
|
+
const merged = new Map;
|
|
3313
|
+
const shared = new Map;
|
|
3314
|
+
const body = (id) => lookup(bodies, id, "routine");
|
|
3315
|
+
const roots = {
|
|
3316
|
+
anchorable: (root) => {
|
|
3317
|
+
const variable = globals.get(root);
|
|
3318
|
+
return variable !== undefined && variable.storage !== "constant";
|
|
3319
|
+
},
|
|
3320
|
+
variable: (root) => lookup(globals, root, "variable"),
|
|
3321
|
+
plainData: (type) => isValueType(type, tables.types)
|
|
3322
|
+
};
|
|
3323
|
+
const candidates = core.functions.filter((fn) => !fn.owner && !entries.has(fn.id));
|
|
3324
|
+
for (const level of callLevels(candidates, body)) {
|
|
3325
|
+
const groups = new Map;
|
|
3326
|
+
for (const fn of level) {
|
|
3327
|
+
const group = partition(fn);
|
|
3328
|
+
if (group === undefined) {
|
|
3329
|
+
continue;
|
|
3330
|
+
}
|
|
3331
|
+
const anchored = anchor({ ...fn, body: body(fn.id) }, tables, roots);
|
|
3332
|
+
if (!anchored) {
|
|
3333
|
+
continue;
|
|
3334
|
+
}
|
|
3335
|
+
const key = `${group}
|
|
3336
|
+
${anchored.key}`;
|
|
3337
|
+
groups.set(key, [...groups.get(key) ?? [], anchored]);
|
|
3338
|
+
}
|
|
3339
|
+
const calls = new Map;
|
|
3340
|
+
for (const members of groups.values()) {
|
|
3341
|
+
const [first] = members;
|
|
3342
|
+
if (!first || members.length < 2) {
|
|
3343
|
+
continue;
|
|
3344
|
+
}
|
|
3345
|
+
const varying = {
|
|
3346
|
+
anchors: first.anchors.map((slot, index) => members.some((member) => member.anchors[index]?.key !== slot.key)),
|
|
3347
|
+
constants: constantParameters(members)
|
|
3348
|
+
};
|
|
3349
|
+
shared.set(first.fn.id, mergedRoutine(members, varying, roots, core.folded ?? []));
|
|
3350
|
+
for (const [index, member] of members.entries()) {
|
|
3351
|
+
if (index) {
|
|
3352
|
+
merged.set(member.fn.id, first.fn.id);
|
|
3353
|
+
}
|
|
3354
|
+
calls.set(member.fn.id, {
|
|
3355
|
+
target: first.fn.id,
|
|
3356
|
+
borrows: member.anchors.filter((_, slot) => varying.anchors[slot]),
|
|
3357
|
+
values: member.constants.filter((_, slot) => varying.constants[slot] === slot)
|
|
3358
|
+
});
|
|
3359
|
+
}
|
|
3360
|
+
}
|
|
3361
|
+
if (!calls.size) {
|
|
3362
|
+
continue;
|
|
3363
|
+
}
|
|
3364
|
+
for (const [id, items] of bodies) {
|
|
3365
|
+
bodies.set(id, rewriteCalls(items, calls));
|
|
3366
|
+
}
|
|
3367
|
+
}
|
|
3368
|
+
if (!merged.size) {
|
|
3369
|
+
return { core, routines: merged };
|
|
3370
|
+
}
|
|
3371
|
+
const functions = core.functions.flatMap((fn) => {
|
|
3372
|
+
if (merged.has(fn.id)) {
|
|
3373
|
+
return [];
|
|
3374
|
+
}
|
|
3375
|
+
return [shared.get(fn.id) ?? { ...fn, body: body(fn.id) }];
|
|
3376
|
+
});
|
|
3377
|
+
const blocks = core.blocks.map((block) => ({ ...block, body: body(block.id) }));
|
|
3378
|
+
return {
|
|
3379
|
+
core: admitCore({ ...core, functions, blocks }),
|
|
3380
|
+
routines: merged
|
|
3381
|
+
};
|
|
3382
|
+
}
|
|
3383
|
+
function callLevels(candidates, body) {
|
|
3384
|
+
const levels = new Map;
|
|
3385
|
+
const callees = (items, found) => {
|
|
3386
|
+
for (const item of items) {
|
|
3387
|
+
if (item.kind === "invoke") {
|
|
3388
|
+
found.add(item.function);
|
|
3389
|
+
}
|
|
3390
|
+
for (const nested of nestedBodies(item)) {
|
|
3391
|
+
callees(nested, found);
|
|
3392
|
+
}
|
|
3393
|
+
}
|
|
3394
|
+
return found;
|
|
3395
|
+
};
|
|
3396
|
+
const level = (id) => {
|
|
3397
|
+
const known = levels.get(id);
|
|
3398
|
+
if (known !== undefined) {
|
|
3399
|
+
return known;
|
|
3400
|
+
}
|
|
3401
|
+
const deepest = [...callees(body(id), new Set)].reduce((depth, callee) => Math.max(depth, level(callee) + 1), 0);
|
|
3402
|
+
levels.set(id, deepest);
|
|
3403
|
+
return deepest;
|
|
3404
|
+
};
|
|
3405
|
+
const ordered = [];
|
|
3406
|
+
for (const fn of candidates) {
|
|
3407
|
+
const depth = level(fn.id);
|
|
3408
|
+
ordered[depth] = [...ordered[depth] ?? [], fn];
|
|
3409
|
+
}
|
|
3410
|
+
return ordered.filter((items) => items !== undefined);
|
|
3411
|
+
}
|
|
3412
|
+
function anchorLength(path) {
|
|
3413
|
+
const dynamic = path.findIndex((segment) => segment.kind === "index" && constantIndex(segment.value) === undefined);
|
|
3414
|
+
if (dynamic >= 0) {
|
|
3415
|
+
return dynamic;
|
|
3416
|
+
}
|
|
3417
|
+
return path.at(-1)?.kind === "field" ? path.length - 1 : path.length;
|
|
3418
|
+
}
|
|
3419
|
+
var constantText = (segment) => segment.kind === "field" ? `.${segment.name}` : `[${segment.value.kind === "constant" ? JSON.stringify(segment.value.value) : "?"}]`;
|
|
3420
|
+
function anchor(fn, tables, roots) {
|
|
3421
|
+
const own = new Map([...fn.parameters, ...fn.locals].map((variable, index) => [
|
|
3422
|
+
variable.id,
|
|
3423
|
+
`#${index}`
|
|
3424
|
+
]));
|
|
3425
|
+
const anchors = [];
|
|
3426
|
+
const slots = new Map;
|
|
3427
|
+
const numbers = new Map;
|
|
3428
|
+
const rewrite = {
|
|
3429
|
+
constant: (value) => {
|
|
3430
|
+
if (!scalarConstant(value, tables.types)) {
|
|
3431
|
+
return value;
|
|
3432
|
+
}
|
|
3433
|
+
const slot = slots.get(value) ?? slots.size;
|
|
3434
|
+
slots.set(value, slot);
|
|
3435
|
+
return {
|
|
3436
|
+
kind: "load",
|
|
3437
|
+
type: value.type,
|
|
3438
|
+
span: value.span,
|
|
3439
|
+
root: `$${slot}`
|
|
3440
|
+
};
|
|
3441
|
+
},
|
|
3442
|
+
place: (root, path, index) => {
|
|
3443
|
+
if (!roots.anchorable(root)) {
|
|
3444
|
+
return { root: own.get(root) ?? root, path: mapPath(path, index) };
|
|
3445
|
+
}
|
|
3446
|
+
const { fixed, key } = anchorOf(root, path);
|
|
3447
|
+
const rest = mapPath(path.slice(fixed.length), index);
|
|
3448
|
+
const known = numbers.get(key);
|
|
3449
|
+
if (known !== undefined) {
|
|
3450
|
+
return { root: `@${known}`, path: rest };
|
|
3451
|
+
}
|
|
3452
|
+
const type = tables.placeType(roots.variable(root).type, fixed)?.id;
|
|
3453
|
+
if (type === undefined) {
|
|
3454
|
+
throw new Unanchored;
|
|
3455
|
+
}
|
|
3456
|
+
if (!roots.plainData(type)) {
|
|
3457
|
+
return { root, path: [...fixed, ...rest] };
|
|
3458
|
+
}
|
|
3459
|
+
numbers.set(key, anchors.length);
|
|
3460
|
+
anchors.push({ root, path: fixed, type, key });
|
|
3461
|
+
return { root: `@${anchors.length - 1}`, path: rest };
|
|
3462
|
+
},
|
|
3463
|
+
identity: (root) => {
|
|
3464
|
+
if (roots.anchorable(root)) {
|
|
3465
|
+
throw new Unanchored;
|
|
3466
|
+
}
|
|
3467
|
+
return own.get(root) ?? root;
|
|
3468
|
+
}
|
|
3469
|
+
};
|
|
3470
|
+
try {
|
|
3471
|
+
const body = rewriteStatements(fn.body, rewrite);
|
|
3472
|
+
const signature = {
|
|
3473
|
+
span: fn.span,
|
|
3474
|
+
result: fn.result,
|
|
3475
|
+
parameters: fn.parameters.map(({ id, ...rest }) => rest),
|
|
3476
|
+
locals: fn.locals.map(({ id, ...rest }) => rest),
|
|
3477
|
+
anchors: anchors.map((item) => item.type)
|
|
3478
|
+
};
|
|
3479
|
+
return {
|
|
3480
|
+
fn,
|
|
3481
|
+
key: JSON.stringify([signature, body]),
|
|
3482
|
+
anchors,
|
|
3483
|
+
constants: [...slots.keys()],
|
|
3484
|
+
slots
|
|
3485
|
+
};
|
|
3486
|
+
} catch (cause) {
|
|
3487
|
+
if (cause instanceof Unanchored) {
|
|
3488
|
+
return;
|
|
3489
|
+
}
|
|
3490
|
+
throw cause;
|
|
3491
|
+
}
|
|
3492
|
+
}
|
|
3493
|
+
var anchorOf = (root, path) => {
|
|
3494
|
+
const fixed = path.slice(0, anchorLength(path));
|
|
3495
|
+
return { fixed, key: `${root}${fixed.map(constantText).join("")}` };
|
|
3496
|
+
};
|
|
3497
|
+
function constantParameters(members) {
|
|
3498
|
+
const [first] = members;
|
|
3499
|
+
const firstSlots = new Map;
|
|
3500
|
+
return (first?.constants ?? []).map((constant, index) => {
|
|
3501
|
+
const values = members.map((member) => member.constants[index]?.value);
|
|
3502
|
+
if (values.every((value) => JSON.stringify(value) === JSON.stringify(constant.value))) {
|
|
3503
|
+
return;
|
|
3504
|
+
}
|
|
3505
|
+
const key = JSON.stringify([constant.type, values]);
|
|
3506
|
+
const slot = firstSlots.get(key) ?? index;
|
|
3507
|
+
firstSlots.set(key, slot);
|
|
3508
|
+
return slot;
|
|
3509
|
+
});
|
|
3510
|
+
}
|
|
3511
|
+
function mergedRoutine(members, varying, roots, folded) {
|
|
3512
|
+
const [{ fn, anchors, constants, slots }] = required(members);
|
|
3513
|
+
const anchorNames = borrowNames(members, varying, roots);
|
|
3514
|
+
const borrowed = new Map;
|
|
3515
|
+
for (const [index, slot] of anchors.entries()) {
|
|
3516
|
+
const name = anchorNames.get(index);
|
|
3517
|
+
if (name === undefined) {
|
|
3518
|
+
continue;
|
|
3519
|
+
}
|
|
3520
|
+
borrowed.set(index, {
|
|
3521
|
+
id: `${fn.id}:anchor${index}`,
|
|
3522
|
+
name,
|
|
3523
|
+
type: slot.type,
|
|
3524
|
+
storage: "parameter",
|
|
3525
|
+
mutable: true,
|
|
3526
|
+
retention: "none",
|
|
3527
|
+
mode: "inOut",
|
|
3528
|
+
span: fn.span
|
|
3529
|
+
});
|
|
3530
|
+
}
|
|
3531
|
+
const values = new Map;
|
|
3532
|
+
for (const [index, constant] of constants.entries()) {
|
|
3533
|
+
if (varying.constants[index] === index) {
|
|
3534
|
+
values.set(index, {
|
|
3535
|
+
id: `${fn.id}:value${index}`,
|
|
3536
|
+
name: foldedName(members, index, folded) ?? "value",
|
|
3537
|
+
type: constant.type,
|
|
3538
|
+
storage: "parameter",
|
|
3539
|
+
mutable: false,
|
|
3540
|
+
retention: "none",
|
|
3541
|
+
span: fn.span
|
|
3542
|
+
});
|
|
3543
|
+
}
|
|
3544
|
+
}
|
|
3545
|
+
const anchorSlots = new Map(anchors.map((slot, index) => [slot.key, index]));
|
|
3546
|
+
const parameter = (parameters, slot) => slot === undefined ? undefined : parameters.get(slot);
|
|
3547
|
+
const rewrite = {
|
|
3548
|
+
constant: (value) => {
|
|
3549
|
+
const slot = slots.get(value);
|
|
3550
|
+
const replacement = parameter(values, slot === undefined ? undefined : varying.constants[slot]);
|
|
3551
|
+
return replacement ? {
|
|
3552
|
+
kind: "load",
|
|
3553
|
+
type: value.type,
|
|
3554
|
+
span: value.span,
|
|
3555
|
+
root: replacement.id
|
|
3556
|
+
} : value;
|
|
3557
|
+
},
|
|
3558
|
+
place: (root, path, index) => {
|
|
3559
|
+
if (!roots.anchorable(root)) {
|
|
3560
|
+
return { root, path: mapPath(path, index) };
|
|
3561
|
+
}
|
|
3562
|
+
const { fixed, key } = anchorOf(root, path);
|
|
3563
|
+
const rest = mapPath(path.slice(fixed.length), index);
|
|
3564
|
+
const borrow = parameter(borrowed, anchorSlots.get(key));
|
|
3565
|
+
return borrow ? { root: borrow.id, path: rest } : { root, path: [...fixed, ...rest] };
|
|
3566
|
+
},
|
|
3567
|
+
identity: (root) => root
|
|
3568
|
+
};
|
|
3569
|
+
return {
|
|
3570
|
+
...fn,
|
|
3571
|
+
parameters: [...fn.parameters, ...borrowed.values(), ...values.values()],
|
|
3572
|
+
body: rewriteStatements(fn.body, rewrite)
|
|
3573
|
+
};
|
|
3574
|
+
}
|
|
3575
|
+
var required = (items) => {
|
|
3576
|
+
const [first, ...rest] = items;
|
|
3577
|
+
if (first === undefined) {
|
|
3578
|
+
throw new Error("A merged group has routines.");
|
|
3579
|
+
}
|
|
3580
|
+
return [first, ...rest];
|
|
3581
|
+
};
|
|
3582
|
+
function foldedName(members, slot, folded) {
|
|
3583
|
+
const fields = members.map((member) => {
|
|
3584
|
+
const instance = member.fn.origin?.instance;
|
|
3585
|
+
const constant = member.constants[slot];
|
|
3586
|
+
if (instance === undefined || constant === undefined) {
|
|
3587
|
+
return new Set;
|
|
3588
|
+
}
|
|
3589
|
+
return new Set(folded.flatMap((item) => item.path.startsWith(`${instance}.`) && JSON.stringify(item.value) === JSON.stringify(constant.value) ? [item.path.slice(instance.length + 1)] : []));
|
|
3590
|
+
});
|
|
3591
|
+
const [first, ...rest] = fields;
|
|
3592
|
+
const shared = [...first ?? []].filter((field) => rest.every((other) => other.has(field)));
|
|
3593
|
+
const [only, ...others] = shared;
|
|
3594
|
+
return only !== undefined && !others.length ? only.replace(/[.[\]]+/g, "_").replace(/_$/, "") : undefined;
|
|
3595
|
+
}
|
|
3596
|
+
function borrowNames(members, varying, roots) {
|
|
3597
|
+
const words = (borrow) => [
|
|
3598
|
+
roots.variable(borrow.root).name,
|
|
3599
|
+
...borrow.path.map((segment) => segment.kind === "field" ? segment.name : String(constantIndex(segment.value) ?? "item"))
|
|
3600
|
+
];
|
|
3601
|
+
const [first] = required(members);
|
|
3602
|
+
const names = new Map;
|
|
3603
|
+
for (const [index, slot] of first.anchors.entries()) {
|
|
3604
|
+
if (!varying.anchors[index]) {
|
|
3605
|
+
continue;
|
|
3606
|
+
}
|
|
3607
|
+
const each = members.map((member) => {
|
|
3608
|
+
const borrow = member.anchors[index];
|
|
3609
|
+
return borrow ? words(borrow) : [];
|
|
3610
|
+
});
|
|
3611
|
+
const own = words(slot);
|
|
3612
|
+
const name = own.flatMap((word, position) => {
|
|
3613
|
+
if (each.every((other) => other[position] === word)) {
|
|
3614
|
+
return [word];
|
|
3615
|
+
}
|
|
3616
|
+
const segment = slot.path[position - 1];
|
|
3617
|
+
return segment?.kind === "index" ? ["item"] : [];
|
|
3618
|
+
});
|
|
3619
|
+
names.set(index, name.join("_") || "item");
|
|
3620
|
+
}
|
|
3621
|
+
const module = (index) => {
|
|
3622
|
+
const slot = first.anchors[index];
|
|
3623
|
+
return slot ? parse(roots.variable(slot.root).span.file).name : "";
|
|
3624
|
+
};
|
|
3625
|
+
const modules = new Map;
|
|
3626
|
+
for (const [index, name] of names) {
|
|
3627
|
+
modules.set(name, (modules.get(name) ?? new Set).add(module(index)));
|
|
3628
|
+
}
|
|
3629
|
+
return new Map([...names].map(([index, name]) => [
|
|
3630
|
+
index,
|
|
3631
|
+
(modules.get(name)?.size ?? 0) > 1 ? `${module(index)}_${name}` : name
|
|
3632
|
+
]));
|
|
3633
|
+
}
|
|
3634
|
+
function rewriteCalls(items, calls) {
|
|
3635
|
+
return items.map((item) => {
|
|
3636
|
+
if (item.kind !== "invoke") {
|
|
3637
|
+
return mapBodies(item, (body) => rewriteCalls(body, calls));
|
|
3638
|
+
}
|
|
3639
|
+
const call = calls.get(item.function);
|
|
3640
|
+
if (!call) {
|
|
3641
|
+
return item;
|
|
3642
|
+
}
|
|
3643
|
+
return {
|
|
3644
|
+
...item,
|
|
3645
|
+
function: call.target,
|
|
3646
|
+
arguments: [
|
|
3647
|
+
...item.arguments,
|
|
3648
|
+
...call.borrows.map((borrow) => ({
|
|
3649
|
+
kind: "borrow",
|
|
3650
|
+
type: borrow.type,
|
|
3651
|
+
span: item.span,
|
|
3652
|
+
place: { root: borrow.root, path: borrow.path }
|
|
3653
|
+
})),
|
|
3654
|
+
...call.values.map((value) => ({ ...value }))
|
|
3655
|
+
]
|
|
3656
|
+
};
|
|
3657
|
+
});
|
|
3658
|
+
}
|
|
3659
|
+
|
|
3660
|
+
class Unanchored extends Error {
|
|
3661
|
+
}
|
|
3662
|
+
var scalarConstant = (value, types) => ["bool", "integer", "float", "duration", "calendar"].includes(value.value.kind) && types.get(value.type)?.kind !== "string";
|
|
3663
|
+
function rewriteExpression(value, rewrite) {
|
|
3664
|
+
const index = (operand) => rewriteExpression(operand, rewrite);
|
|
3665
|
+
if (value.kind === "constant") {
|
|
3666
|
+
return rewrite.constant(value);
|
|
3667
|
+
}
|
|
3668
|
+
if (value.kind === "load") {
|
|
3669
|
+
const place = rewrite.place(value.root, value.path ?? [], index);
|
|
3670
|
+
return {
|
|
3671
|
+
...value,
|
|
3672
|
+
root: place.root,
|
|
3673
|
+
...value.path || place.path.length ? { path: place.path } : {}
|
|
3674
|
+
};
|
|
3675
|
+
}
|
|
3676
|
+
if (value.kind === "borrow") {
|
|
3677
|
+
return {
|
|
3678
|
+
...value,
|
|
3679
|
+
place: rewrite.place(value.place.root, value.place.path, index)
|
|
3680
|
+
};
|
|
3681
|
+
}
|
|
3682
|
+
return mapExpression(value, index);
|
|
3683
|
+
}
|
|
3684
|
+
function rewriteStatements(items, rewrite) {
|
|
3685
|
+
return items.map((item) => rewriteStatement(item, rewrite));
|
|
3686
|
+
}
|
|
3687
|
+
function rewriteStatement(item, rewrite) {
|
|
3688
|
+
const expression = (value) => rewriteExpression(value, rewrite);
|
|
3689
|
+
const statements = (body) => rewriteStatements(body, rewrite);
|
|
3690
|
+
switch (item.kind) {
|
|
3691
|
+
case "assign": {
|
|
3692
|
+
const place = rewrite.place(item.root, item.path ?? [], expression);
|
|
3693
|
+
return {
|
|
3694
|
+
...item,
|
|
3695
|
+
root: place.root,
|
|
3696
|
+
...item.path || place.path.length ? { path: place.path } : {},
|
|
3697
|
+
value: expression(item.value)
|
|
3698
|
+
};
|
|
3699
|
+
}
|
|
3700
|
+
case "for":
|
|
3701
|
+
return mapBodies(mapStatementExpressions({ ...item, counter: rewrite.identity(item.counter) }, expression), statements);
|
|
3702
|
+
case "invoke":
|
|
3703
|
+
return mapStatementExpressions({
|
|
3704
|
+
...item,
|
|
3705
|
+
...item.instance !== undefined && {
|
|
3706
|
+
instance: rewrite.identity(item.instance)
|
|
3707
|
+
},
|
|
3708
|
+
...item.destination !== undefined && {
|
|
3709
|
+
destination: rewrite.identity(item.destination)
|
|
3710
|
+
}
|
|
3711
|
+
}, expression);
|
|
3712
|
+
case "blockUpdate":
|
|
3713
|
+
return mapStatementExpressions({ ...item, instance: rewrite.identity(item.instance) }, expression);
|
|
3714
|
+
case "if":
|
|
3715
|
+
case "switch":
|
|
3716
|
+
case "return":
|
|
3717
|
+
case "telemetry":
|
|
3718
|
+
case "break":
|
|
3719
|
+
case "continue":
|
|
3720
|
+
return mapBodies(mapStatementExpressions(item, expression), statements);
|
|
3721
|
+
}
|
|
3722
|
+
}
|
|
3723
|
+
function constantResult(fn) {
|
|
3724
|
+
const [only, ...rest] = fn.body;
|
|
3725
|
+
if (rest.length || fn.owner) {
|
|
3726
|
+
return;
|
|
3727
|
+
}
|
|
3728
|
+
if (!only) {
|
|
3729
|
+
return fn.result ? undefined : {};
|
|
3730
|
+
}
|
|
3731
|
+
if (only.kind !== "return") {
|
|
3732
|
+
return;
|
|
3733
|
+
}
|
|
3734
|
+
if (!only.value) {
|
|
3735
|
+
return fn.result ? undefined : {};
|
|
3736
|
+
}
|
|
3737
|
+
return only.value.kind === "constant" ? { value: only.value } : undefined;
|
|
3738
|
+
}
|
|
3739
|
+
var placePath = (value) => {
|
|
3740
|
+
if (value.kind === "load") {
|
|
3741
|
+
return value.path ?? [];
|
|
3742
|
+
}
|
|
3743
|
+
return value.kind === "borrow" ? value.place.path : undefined;
|
|
3744
|
+
};
|
|
3745
|
+
var plainArgument = (value) => {
|
|
3746
|
+
if (value.kind === "constant") {
|
|
3747
|
+
return true;
|
|
3748
|
+
}
|
|
3749
|
+
return placePath(value)?.every((segment) => segment.kind === "field" || plainArgument(segment.value)) ?? false;
|
|
3750
|
+
};
|
|
3751
|
+
function foldConstantRoutines(core) {
|
|
3752
|
+
const entries = new Set(core.programs.map((program) => program.entry));
|
|
3753
|
+
const constants = new Map(core.functions.flatMap((fn) => {
|
|
3754
|
+
const result = entries.has(fn.id) ? undefined : constantResult(fn);
|
|
3755
|
+
return result ? [[fn.id, result]] : [];
|
|
3756
|
+
}));
|
|
3757
|
+
if (!constants.size) {
|
|
3758
|
+
return { core, routines: new Set };
|
|
3759
|
+
}
|
|
3760
|
+
const called = new Set;
|
|
3761
|
+
const fold = (items) => items.flatMap((item) => {
|
|
3762
|
+
if (item.kind !== "invoke") {
|
|
3763
|
+
return [mapBodies(item, fold)];
|
|
3764
|
+
}
|
|
3765
|
+
const result = constants.get(item.function);
|
|
3766
|
+
if (!result || !item.arguments.every(plainArgument)) {
|
|
3767
|
+
called.add(item.function);
|
|
3768
|
+
return [item];
|
|
3769
|
+
}
|
|
3770
|
+
if (item.destination === undefined || !result.value) {
|
|
3771
|
+
return [];
|
|
3772
|
+
}
|
|
3773
|
+
return [
|
|
3774
|
+
{
|
|
3775
|
+
kind: "assign",
|
|
3776
|
+
span: item.span,
|
|
3777
|
+
root: item.destination,
|
|
3778
|
+
value: { ...result.value, span: item.span }
|
|
3779
|
+
}
|
|
3780
|
+
];
|
|
3781
|
+
});
|
|
3782
|
+
const functions = core.functions.map((fn) => ({
|
|
3783
|
+
...fn,
|
|
3784
|
+
body: fold(fn.body)
|
|
3785
|
+
}));
|
|
3786
|
+
const blocks = core.blocks.map((block) => ({ ...block, body: fold(block.body) }));
|
|
3787
|
+
const routines = new Set([...constants.keys()].filter((id) => !called.has(id)));
|
|
3788
|
+
return {
|
|
3789
|
+
core: admitCore({
|
|
3790
|
+
...core,
|
|
3791
|
+
functions: functions.filter((fn) => !routines.has(fn.id)),
|
|
3792
|
+
blocks
|
|
3793
|
+
}),
|
|
3794
|
+
routines
|
|
3795
|
+
};
|
|
3796
|
+
}
|
|
3797
|
+
// packages/compiler/src/ir/temporaries.ts
|
|
3798
|
+
function forwardTemporaries(core) {
|
|
3799
|
+
const functions = core.functions.map((fn) => forward(fn));
|
|
3800
|
+
const blocks = core.blocks.map((block) => forward(block));
|
|
3801
|
+
return admitCore({ ...core, functions, blocks });
|
|
3802
|
+
}
|
|
3803
|
+
function forward(routine) {
|
|
3804
|
+
const temporaries = new Set(routine.locals.filter((local) => isTemporary(routine.id, local)).map((local) => local.id));
|
|
3805
|
+
if (!temporaries.size) {
|
|
3806
|
+
return routine;
|
|
3807
|
+
}
|
|
3808
|
+
const writes = new Map;
|
|
3809
|
+
const reads = new Map;
|
|
3810
|
+
const count = (counts, root) => counts.set(root, (counts.get(root) ?? 0) + 1);
|
|
3811
|
+
const expression = (value) => {
|
|
3812
|
+
if (value.kind === "load") {
|
|
3813
|
+
count(reads, value.root);
|
|
3814
|
+
}
|
|
3815
|
+
if (value.kind === "borrow") {
|
|
3816
|
+
count(writes, value.place.root);
|
|
3817
|
+
count(reads, value.place.root);
|
|
3818
|
+
}
|
|
3819
|
+
subexpressions(value).forEach(expression);
|
|
3820
|
+
};
|
|
3821
|
+
const statements = (items) => {
|
|
3822
|
+
for (const item of items) {
|
|
3823
|
+
if (item.kind === "assign") {
|
|
3824
|
+
count(writes, item.root);
|
|
3825
|
+
}
|
|
3826
|
+
if (item.kind === "for") {
|
|
3827
|
+
count(writes, item.counter);
|
|
3828
|
+
}
|
|
3829
|
+
if (item.kind === "invoke" && item.destination !== undefined) {
|
|
3830
|
+
count(writes, item.destination);
|
|
3831
|
+
}
|
|
3832
|
+
statementExpressions(item).forEach(expression);
|
|
3833
|
+
nestedBodies(item).forEach(statements);
|
|
3834
|
+
}
|
|
3835
|
+
};
|
|
3836
|
+
statements(routine.body);
|
|
3837
|
+
const movable = (item) => item.kind === "assign" && !item.path?.length && temporaries.has(item.root) && writes.get(item.root) === 1 && reads.get(item.root) === 1 && (item.value.kind === "load" || item.value.kind === "constant" || item.value.type === "BOOL");
|
|
3838
|
+
const forwarded = new Set;
|
|
3839
|
+
const rewrite = (items) => {
|
|
3840
|
+
const result = items.map((item) => mapBodies(item, rewrite));
|
|
3841
|
+
for (let index = result.length - 2;index >= 0; index--) {
|
|
3842
|
+
const item = result[index];
|
|
3843
|
+
const next = result[index + 1];
|
|
3844
|
+
if (!item || !next || !movable(item) || !readsOwn(next, item.root)) {
|
|
3845
|
+
continue;
|
|
3846
|
+
}
|
|
3847
|
+
result.splice(index, 2, substitute(next, item.root, item.value));
|
|
3848
|
+
forwarded.add(item.root);
|
|
3849
|
+
}
|
|
3850
|
+
return result;
|
|
3851
|
+
};
|
|
3852
|
+
const body = rewrite(routine.body);
|
|
3853
|
+
if (!forwarded.size) {
|
|
3854
|
+
return routine;
|
|
3855
|
+
}
|
|
3856
|
+
return {
|
|
3857
|
+
...routine,
|
|
3858
|
+
locals: routine.locals.filter((local) => !forwarded.has(local.id)),
|
|
3859
|
+
body
|
|
3860
|
+
};
|
|
3861
|
+
}
|
|
3862
|
+
function readsOwn(item, root) {
|
|
3863
|
+
if (item.kind === "for" || item.kind === "switch") {
|
|
3864
|
+
return false;
|
|
3865
|
+
}
|
|
3866
|
+
const reads = (value) => value.kind === "load" && value.root === root || subexpressions(value).some(reads);
|
|
3867
|
+
return statementExpressions(item).some(reads);
|
|
3868
|
+
}
|
|
3869
|
+
function substitute(item, root, value) {
|
|
3870
|
+
const replace = (expression) => expression.kind === "load" && expression.root === root ? value : mapExpression(expression, replace);
|
|
3871
|
+
return mapStatementExpressions(item, replace);
|
|
3872
|
+
}
|
|
3873
|
+
export {
|
|
3874
|
+
aggregate,
|
|
3875
|
+
aggregateIssue,
|
|
3876
|
+
calendarLiteral,
|
|
3877
|
+
canAssign,
|
|
3878
|
+
comparisonOperators,
|
|
3879
|
+
constantFits,
|
|
3880
|
+
constantIndex,
|
|
3881
|
+
coreTables,
|
|
3882
|
+
defaultValue,
|
|
3883
|
+
directWrites,
|
|
3884
|
+
domainConstantFits,
|
|
3885
|
+
domainIssue,
|
|
3886
|
+
durationLiteral,
|
|
3887
|
+
error,
|
|
3888
|
+
errorName,
|
|
3889
|
+
exactIntegerLimit,
|
|
3890
|
+
expressionIssue,
|
|
3891
|
+
failureCode,
|
|
3892
|
+
failureName,
|
|
3893
|
+
fold,
|
|
3894
|
+
foldConstantRoutines,
|
|
3895
|
+
formatDiagnostic,
|
|
3896
|
+
forwardTemporaries,
|
|
3897
|
+
freeze,
|
|
3898
|
+
hasErrors,
|
|
3899
|
+
httpErrors,
|
|
3900
|
+
httpMethods,
|
|
3901
|
+
identityDigest,
|
|
3902
|
+
instanceFields,
|
|
3903
|
+
instancedBlock,
|
|
3904
|
+
integerRange,
|
|
3905
|
+
integerType,
|
|
3906
|
+
interval,
|
|
3907
|
+
isBlockRoutine,
|
|
3908
|
+
isLogicalIo,
|
|
3909
|
+
isRadixLiteral,
|
|
3910
|
+
isTemporary,
|
|
3911
|
+
isVerifiedCore,
|
|
3912
|
+
jobError,
|
|
3913
|
+
jobErrors,
|
|
3914
|
+
layoutIssue,
|
|
3915
|
+
literalOutsideType,
|
|
3916
|
+
loopBounds,
|
|
3917
|
+
maxLoopIterations,
|
|
3918
|
+
maxNestingDepth,
|
|
3919
|
+
maxScalarElements,
|
|
3920
|
+
maxScalarElementsText,
|
|
3921
|
+
maxStringCapacity,
|
|
3922
|
+
nanosecondsPerMillisecond2 as nanosecondsPerMillisecond,
|
|
3923
|
+
narrowRanges,
|
|
3924
|
+
nestedBodies,
|
|
3925
|
+
normalizeModule,
|
|
3926
|
+
optionalRecord,
|
|
3927
|
+
parseFloatLiteral,
|
|
3928
|
+
parseInteger,
|
|
3929
|
+
pascalCase,
|
|
3930
|
+
pathConditions,
|
|
3931
|
+
pathIndexes,
|
|
3932
|
+
placeType,
|
|
3933
|
+
primitiveTypes,
|
|
3934
|
+
projectReconstruction,
|
|
3935
|
+
reservedErrors,
|
|
3936
|
+
scalarIssue,
|
|
3937
|
+
shareRoutines,
|
|
3938
|
+
standardBlocks,
|
|
3939
|
+
statementExpressions,
|
|
3940
|
+
staticNames,
|
|
3941
|
+
subexpressions,
|
|
3942
|
+
telemetryOperands,
|
|
3943
|
+
valueFits,
|
|
3944
|
+
wrapsNatively
|
|
3945
|
+
};
|
|
3946
|
+
|
|
3947
|
+
//# debugId=E53B56328BF447F564756E2164756E21
|
|
3948
|
+
//# sourceMappingURL=ir.js.map
|