@nova-energy/openamx 0.21.0 → 0.22.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +8 -4
- package/dist/parser/parseDocument.js +26 -13
- package/dist/renderer/diagramBrowserRuntime.js +1 -1
- package/dist/runtime/evaluateDocument.js +9 -14
- package/dist/runtime/evaluateExpression.js +142 -12
- package/dist/runtime/moduleLoader.js +23 -11
- package/dist/runtime/typescriptBridge.js +171 -0
- package/dist/transpiler/emit.js +151 -6
- package/dist/transpiler/graph.js +4 -3
- package/dist/typechecker/checkDocument.js +64 -2
- package/dist/typechecker/typescriptAnalysis.js +372 -0
- package/package.json +3 -2
|
@@ -4,8 +4,9 @@ import { evaluateStandardLibraryCall, isMathematicalFunction } from './standardL
|
|
|
4
4
|
import { fieldRegistry } from '../typechecker/declarationRegistry';
|
|
5
5
|
import { canonicalUnit, composeUnits, isAffineUnit, isMeasurement, measurement, measurementDisplayValue, measurementPhysicalValue, powerUnit, sqrtMeasurement, unitFromMetadata } from './measurement';
|
|
6
6
|
import { createDiagramModel } from './diagramModel';
|
|
7
|
-
function validateRuntimeValue(value, expected, env, source, file, valuePath) {
|
|
7
|
+
export function validateRuntimeValue(value, expected, env, source, file, valuePath) {
|
|
8
8
|
const diagnostics = [];
|
|
9
|
+
const activeValues = new WeakSet();
|
|
9
10
|
const report = (message, target, actual, dataPath, fieldSource) => {
|
|
10
11
|
const diagnostic = inputError('AMX4003', message, {
|
|
11
12
|
file,
|
|
@@ -32,11 +33,72 @@ function validateRuntimeValue(value, expected, env, source, file, valuePath) {
|
|
|
32
33
|
return;
|
|
33
34
|
}
|
|
34
35
|
if (target.kind === 'list') {
|
|
35
|
-
|
|
36
|
+
let isArray;
|
|
37
|
+
try {
|
|
38
|
+
isArray = Array.isArray(actual);
|
|
39
|
+
}
|
|
40
|
+
catch {
|
|
36
41
|
report('Expected a list value', target, actual, dataPath, fieldSource);
|
|
37
42
|
return;
|
|
38
43
|
}
|
|
39
|
-
|
|
44
|
+
if (!isArray) {
|
|
45
|
+
report('Expected a list value', target, actual, dataPath, fieldSource);
|
|
46
|
+
return;
|
|
47
|
+
}
|
|
48
|
+
const array = actual;
|
|
49
|
+
let prototype;
|
|
50
|
+
try {
|
|
51
|
+
prototype = Object.getPrototypeOf(array);
|
|
52
|
+
}
|
|
53
|
+
catch {
|
|
54
|
+
report('Expected a plain list value', target, actual, dataPath, fieldSource);
|
|
55
|
+
return;
|
|
56
|
+
}
|
|
57
|
+
if (prototype !== Array.prototype) {
|
|
58
|
+
report('Expected a plain list value', target, actual, dataPath, fieldSource);
|
|
59
|
+
return;
|
|
60
|
+
}
|
|
61
|
+
if (activeValues.has(array)) {
|
|
62
|
+
report('Cyclic values are not supported', target, actual, dataPath, fieldSource);
|
|
63
|
+
return;
|
|
64
|
+
}
|
|
65
|
+
activeValues.add(array);
|
|
66
|
+
try {
|
|
67
|
+
for (let index = 0; index < array.length; index++) {
|
|
68
|
+
let descriptor;
|
|
69
|
+
try {
|
|
70
|
+
descriptor = Object.getOwnPropertyDescriptor(array, String(index));
|
|
71
|
+
}
|
|
72
|
+
catch {
|
|
73
|
+
report('Expected a plain list value', target, actual, `${dataPath}[${index}]`, fieldSource);
|
|
74
|
+
continue;
|
|
75
|
+
}
|
|
76
|
+
if (!descriptor || !('value' in descriptor) || descriptor.enumerable !== true) {
|
|
77
|
+
report('Expected a dense data list', target.element, descriptor ? 'accessor' : 'missing', `${dataPath}[${index}]`, fieldSource);
|
|
78
|
+
continue;
|
|
79
|
+
}
|
|
80
|
+
visit(descriptor.value, target.element, `${dataPath}[${index}]`, fieldSource);
|
|
81
|
+
}
|
|
82
|
+
let keys;
|
|
83
|
+
try {
|
|
84
|
+
keys = Reflect.ownKeys(array);
|
|
85
|
+
}
|
|
86
|
+
catch {
|
|
87
|
+
report('Expected a plain list value', target, actual, dataPath, fieldSource);
|
|
88
|
+
return;
|
|
89
|
+
}
|
|
90
|
+
for (const key of keys) {
|
|
91
|
+
if (key === 'length')
|
|
92
|
+
continue;
|
|
93
|
+
const index = typeof key === 'string' ? Number(key) : Number.NaN;
|
|
94
|
+
if (!Number.isSafeInteger(index) || index < 0 || index >= array.length || String(index) !== key) {
|
|
95
|
+
report('Unsupported list property', target, actual, `${dataPath}.${String(key)}`, fieldSource);
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
finally {
|
|
100
|
+
activeValues.delete(array);
|
|
101
|
+
}
|
|
40
102
|
return;
|
|
41
103
|
}
|
|
42
104
|
if (target.kind === 'measurement') {
|
|
@@ -73,24 +135,92 @@ function validateRuntimeValue(value, expected, env, source, file, valuePath) {
|
|
|
73
135
|
report('Expected a Boolean value', target, actual, dataPath, fieldSource);
|
|
74
136
|
return;
|
|
75
137
|
}
|
|
138
|
+
const enumeration = env.enumDeclarations.get(target.name);
|
|
139
|
+
if (enumeration) {
|
|
140
|
+
const values = enumeration.resolvedValues ?? [];
|
|
141
|
+
if ((typeof actual !== 'number' && typeof actual !== 'string') || !values.includes(actual)) {
|
|
142
|
+
report(`Expected a member value of enum '${target.name}'`, target, actual, dataPath, fieldSource);
|
|
143
|
+
}
|
|
144
|
+
return;
|
|
145
|
+
}
|
|
76
146
|
const declaration = env.recordTypes.get(target.name);
|
|
77
|
-
|
|
147
|
+
let isArray;
|
|
148
|
+
try {
|
|
149
|
+
isArray = Array.isArray(actual);
|
|
150
|
+
}
|
|
151
|
+
catch {
|
|
152
|
+
report(`Expected a plain ${target.name} record`, target, actual, dataPath, fieldSource);
|
|
153
|
+
return;
|
|
154
|
+
}
|
|
155
|
+
if (!declaration || typeof actual !== 'object' || actual === null || isArray) {
|
|
78
156
|
report(`Expected a ${target.name} record`, target, actual, dataPath, fieldSource);
|
|
79
157
|
return;
|
|
80
158
|
}
|
|
159
|
+
let prototype;
|
|
160
|
+
try {
|
|
161
|
+
prototype = Object.getPrototypeOf(actual);
|
|
162
|
+
}
|
|
163
|
+
catch {
|
|
164
|
+
report(`Expected a plain ${target.name} record`, target, actual, dataPath, fieldSource);
|
|
165
|
+
return;
|
|
166
|
+
}
|
|
167
|
+
if (prototype !== Object.prototype && prototype !== null) {
|
|
168
|
+
report(`Expected a plain ${target.name} record`, target, actual, dataPath, fieldSource);
|
|
169
|
+
return;
|
|
170
|
+
}
|
|
171
|
+
if (activeValues.has(actual)) {
|
|
172
|
+
report('Cyclic values are not supported', target, actual, dataPath, fieldSource);
|
|
173
|
+
return;
|
|
174
|
+
}
|
|
175
|
+
activeValues.add(actual);
|
|
81
176
|
const record = actual;
|
|
82
177
|
const fieldNames = new Set(declaration.fields.map(field => field.name));
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
178
|
+
try {
|
|
179
|
+
let keys;
|
|
180
|
+
try {
|
|
181
|
+
keys = Reflect.ownKeys(record);
|
|
87
182
|
}
|
|
88
|
-
|
|
89
|
-
|
|
183
|
+
catch {
|
|
184
|
+
report(`Expected a plain ${target.name} record`, target, actual, dataPath, fieldSource);
|
|
185
|
+
return;
|
|
186
|
+
}
|
|
187
|
+
for (const field of declaration.fields) {
|
|
188
|
+
const fieldScope = fieldRegistry(field, env.dimensionRegistry);
|
|
189
|
+
let descriptor;
|
|
190
|
+
try {
|
|
191
|
+
descriptor = Object.getOwnPropertyDescriptor(record, field.name);
|
|
192
|
+
}
|
|
193
|
+
catch {
|
|
194
|
+
report(`Expected a plain data field '${field.name}'`, checkedType(field.annotation, fieldScope), 'accessor', `${dataPath}.${field.name}`, field.source);
|
|
195
|
+
continue;
|
|
196
|
+
}
|
|
197
|
+
if (!descriptor) {
|
|
198
|
+
report(`Missing computed field '${field.name}'`, checkedType(field.annotation, fieldScope), 'missing', `${dataPath}.${field.name}`, field.source);
|
|
199
|
+
}
|
|
200
|
+
else if (!('value' in descriptor) || descriptor.enumerable !== true) {
|
|
201
|
+
report(`Expected a plain data field '${field.name}'`, checkedType(field.annotation, fieldScope), 'accessor', `${dataPath}.${field.name}`, field.source);
|
|
202
|
+
}
|
|
203
|
+
else {
|
|
204
|
+
visit(descriptor.value, checkedType(field.annotation, fieldScope), `${dataPath}.${field.name}`, field.source);
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
for (const key of keys) {
|
|
208
|
+
if (typeof key !== 'string' || !fieldNames.has(key)) {
|
|
209
|
+
let actualValue = 'unsupported property';
|
|
210
|
+
try {
|
|
211
|
+
const descriptor = Object.getOwnPropertyDescriptor(record, key);
|
|
212
|
+
if (descriptor && 'value' in descriptor)
|
|
213
|
+
actualValue = descriptor.value;
|
|
214
|
+
}
|
|
215
|
+
catch {
|
|
216
|
+
actualValue = 'unavailable property';
|
|
217
|
+
}
|
|
218
|
+
report(`Unknown computed field '${String(key)}'`, target, actualValue, `${dataPath}.${String(key)}`, fieldSource);
|
|
219
|
+
}
|
|
90
220
|
}
|
|
91
221
|
}
|
|
92
|
-
|
|
93
|
-
|
|
222
|
+
finally {
|
|
223
|
+
activeValues.delete(actual);
|
|
94
224
|
}
|
|
95
225
|
};
|
|
96
226
|
visit(value, expected, valuePath);
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import * as path from 'path';
|
|
2
2
|
import * as fs from 'fs';
|
|
3
3
|
import { parseDocument, parseDocumentText } from '../parser/parseDocument';
|
|
4
|
-
import {
|
|
5
|
-
import {
|
|
4
|
+
import { checkDocumentWithRuntimePlan } from '../typechecker/checkDocument';
|
|
5
|
+
import { evaluateDocumentNodes, prepareTypeScriptBlocks } from './typescriptBridge';
|
|
6
6
|
import { Environment } from './environment';
|
|
7
7
|
import { AmxError, moduleError, staticError, throwInputErrors } from '../diagnostics/errors';
|
|
8
8
|
import { describeInputSchema, loadInputValues, validateInputText } from './inputData';
|
|
@@ -253,7 +253,7 @@ export async function loadEntryModule(entryPath, options = {}) {
|
|
|
253
253
|
}
|
|
254
254
|
}
|
|
255
255
|
}
|
|
256
|
-
const
|
|
256
|
+
const checked = checkDocumentWithRuntimePlan(doc, canonicalPath, {
|
|
257
257
|
types: importedTypes,
|
|
258
258
|
enums: importedEnums,
|
|
259
259
|
functions: importedFunctions,
|
|
@@ -265,7 +265,20 @@ export async function loadEntryModule(entryPath, options = {}) {
|
|
|
265
265
|
isEntryModule: canonicalPath === realEntry
|
|
266
266
|
});
|
|
267
267
|
visiting.pop();
|
|
268
|
-
const record = {
|
|
268
|
+
const record = {
|
|
269
|
+
canonicalPath,
|
|
270
|
+
doc,
|
|
271
|
+
checkResult: checked.result,
|
|
272
|
+
typescriptBlocks: checked.typescriptBlocks,
|
|
273
|
+
importedTypes,
|
|
274
|
+
importedEnums,
|
|
275
|
+
importedEnumSources,
|
|
276
|
+
importedFunctions,
|
|
277
|
+
importedBindings,
|
|
278
|
+
importedBindingSources,
|
|
279
|
+
importedDimensions,
|
|
280
|
+
importedUnits
|
|
281
|
+
};
|
|
269
282
|
resolved.set(canonicalPath, record);
|
|
270
283
|
evaluationOrder.push(canonicalPath);
|
|
271
284
|
return record;
|
|
@@ -330,6 +343,11 @@ export async function loadEntryModule(entryPath, options = {}) {
|
|
|
330
343
|
};
|
|
331
344
|
}
|
|
332
345
|
const inputValues = await loadInputValues(inputDeclarations, entryTypes, options.inputMappings, options.validation, entryPath, registry, entryEnums);
|
|
346
|
+
const preparedTypeScript = new Map();
|
|
347
|
+
for (const canonicalPath of evaluationOrder) {
|
|
348
|
+
const record = resolved.get(canonicalPath);
|
|
349
|
+
preparedTypeScript.set(canonicalPath, prepareTypeScriptBlocks(record.typescriptBlocks, canonicalPath));
|
|
350
|
+
}
|
|
333
351
|
const evaluatedEnvironments = new Map();
|
|
334
352
|
for (const canonicalPath of evaluationOrder) {
|
|
335
353
|
const record = resolved.get(canonicalPath);
|
|
@@ -362,13 +380,7 @@ export async function loadEntryModule(entryPath, options = {}) {
|
|
|
362
380
|
for (const [name, value] of inputValues)
|
|
363
381
|
env.set(name, value);
|
|
364
382
|
}
|
|
365
|
-
|
|
366
|
-
const node = record.doc.nodes[nodeIndex];
|
|
367
|
-
if (node.type === 'executableCodeBlock') {
|
|
368
|
-
env.currentDocumentNodeIndex = nodeIndex;
|
|
369
|
-
evaluateStatements(node.statements, env, canonicalPath);
|
|
370
|
-
}
|
|
371
|
-
}
|
|
383
|
+
evaluateDocumentNodes(record.doc, env, canonicalPath, record.typescriptBlocks, preparedTypeScript.get(canonicalPath));
|
|
372
384
|
evaluatedEnvironments.set(canonicalPath, env);
|
|
373
385
|
}
|
|
374
386
|
const entryEnv = evaluatedEnvironments.get(realEntry);
|
|
@@ -0,0 +1,171 @@
|
|
|
1
|
+
import { AmxError } from '../diagnostics/errors';
|
|
2
|
+
import { evaluateStatements, validateRuntimeValue } from './evaluateExpression';
|
|
3
|
+
function runtimeFailure(plan, file, phase, error) {
|
|
4
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
5
|
+
throw new AmxError({
|
|
6
|
+
code: 'AMX3025',
|
|
7
|
+
message: `TypeScript ${phase} failed: ${message}`,
|
|
8
|
+
file,
|
|
9
|
+
line: plan.node.contentSource.line,
|
|
10
|
+
column: plan.node.contentSource.column
|
|
11
|
+
});
|
|
12
|
+
}
|
|
13
|
+
function supportsReference(reference, plan, seen = new Set()) {
|
|
14
|
+
if (reference.type === 'listType' || reference.type === 'nullableType') {
|
|
15
|
+
return !!reference.element && supportsReference(reference.element, plan, seen);
|
|
16
|
+
}
|
|
17
|
+
const name = reference.name;
|
|
18
|
+
if (!name)
|
|
19
|
+
return false;
|
|
20
|
+
if (name === 'Number' || name === 'String' || name === 'Boolean' || name === 'DateTime')
|
|
21
|
+
return true;
|
|
22
|
+
if (plan.visibleEnums.has(name))
|
|
23
|
+
return true;
|
|
24
|
+
const declaration = plan.visibleTypes.get(name);
|
|
25
|
+
if (!declaration || seen.has(name) || declaration.fields.some(field => field.optional))
|
|
26
|
+
return false;
|
|
27
|
+
const nextSeen = new Set(seen).add(name);
|
|
28
|
+
return declaration.fields.every(field => supportsReference(field.annotation, plan, nextSeen));
|
|
29
|
+
}
|
|
30
|
+
function supportsType(type, plan, seen = new Set()) {
|
|
31
|
+
if (type.kind === 'list' || type.kind === 'nullable')
|
|
32
|
+
return supportsType(type.element, plan, seen);
|
|
33
|
+
if (type.kind !== 'named')
|
|
34
|
+
return false;
|
|
35
|
+
if (type.name === 'Number' || type.name === 'String' || type.name === 'Boolean' || type.name === 'DateTime')
|
|
36
|
+
return true;
|
|
37
|
+
if (plan.visibleEnums.has(type.name))
|
|
38
|
+
return true;
|
|
39
|
+
const declaration = plan.visibleTypes.get(type.name);
|
|
40
|
+
if (!declaration || seen.has(type.name) || declaration.fields.some(field => field.optional))
|
|
41
|
+
return false;
|
|
42
|
+
const nextSeen = new Set(seen).add(type.name);
|
|
43
|
+
return declaration.fields.every(field => supportsReference(field.annotation, plan, nextSeen));
|
|
44
|
+
}
|
|
45
|
+
function enumValueObject(declaration) {
|
|
46
|
+
const values = declaration.resolvedValues;
|
|
47
|
+
if (!values || values.length !== declaration.members.length) {
|
|
48
|
+
throw new Error(`Enum '${declaration.name}' has unresolved runtime values`);
|
|
49
|
+
}
|
|
50
|
+
const valueObject = Object.create(null);
|
|
51
|
+
declaration.members.forEach((member, index) => {
|
|
52
|
+
Object.defineProperty(valueObject, member.name, {
|
|
53
|
+
value: values[index],
|
|
54
|
+
enumerable: true,
|
|
55
|
+
writable: false,
|
|
56
|
+
configurable: false
|
|
57
|
+
});
|
|
58
|
+
});
|
|
59
|
+
return Object.freeze(valueObject);
|
|
60
|
+
}
|
|
61
|
+
function cloneData(value, copies = new WeakMap()) {
|
|
62
|
+
if (value === null || typeof value !== 'object')
|
|
63
|
+
return value;
|
|
64
|
+
const prior = copies.get(value);
|
|
65
|
+
if (prior !== undefined)
|
|
66
|
+
return prior;
|
|
67
|
+
if (Array.isArray(value)) {
|
|
68
|
+
const copy = new Array(value.length);
|
|
69
|
+
copies.set(value, copy);
|
|
70
|
+
for (let index = 0; index < value.length; index++)
|
|
71
|
+
copy[index] = cloneData(value[index], copies);
|
|
72
|
+
return copy;
|
|
73
|
+
}
|
|
74
|
+
const prototype = Object.getPrototypeOf(value);
|
|
75
|
+
if (prototype !== Object.prototype && prototype !== null)
|
|
76
|
+
return value;
|
|
77
|
+
const copy = Object.create(prototype);
|
|
78
|
+
copies.set(value, copy);
|
|
79
|
+
for (const [field, item] of Object.entries(value))
|
|
80
|
+
copy[field] = cloneData(item, copies);
|
|
81
|
+
return copy;
|
|
82
|
+
}
|
|
83
|
+
export function prepareTypeScriptBlocks(plans, file) {
|
|
84
|
+
const prepared = new Map();
|
|
85
|
+
for (const [nodeIndex, plan] of plans) {
|
|
86
|
+
try {
|
|
87
|
+
const transpiler = new Bun.Transpiler({ loader: 'ts' });
|
|
88
|
+
prepared.set(nodeIndex, transpiler.transformSync(plan.node.content));
|
|
89
|
+
}
|
|
90
|
+
catch (error) {
|
|
91
|
+
runtimeFailure(plan, file, 'transpilation', error);
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
return prepared;
|
|
95
|
+
}
|
|
96
|
+
function evaluateTypeScriptBlock(plan, code, env, file) {
|
|
97
|
+
const visibleBindings = plan.visibleBindings.filter(binding => supportsType(binding.type, plan));
|
|
98
|
+
const mutableBindings = visibleBindings.filter(binding => binding.mutable);
|
|
99
|
+
const enumEntries = [...plan.visibleEnums.entries()];
|
|
100
|
+
const outputNames = plan.outputs.map(output => output.name);
|
|
101
|
+
const returnNames = [...outputNames, ...mutableBindings.map(binding => binding.name)];
|
|
102
|
+
const argumentNames = [
|
|
103
|
+
...visibleBindings.map(binding => binding.name),
|
|
104
|
+
...enumEntries.map(([name]) => name)
|
|
105
|
+
];
|
|
106
|
+
let visibleValues;
|
|
107
|
+
let enumValues;
|
|
108
|
+
try {
|
|
109
|
+
visibleValues = visibleBindings.map(binding => env.get(binding.name, binding.source, file));
|
|
110
|
+
enumValues = enumEntries.map(([, declaration]) => enumValueObject(declaration));
|
|
111
|
+
}
|
|
112
|
+
catch (error) {
|
|
113
|
+
runtimeFailure(plan, file, 'bridge preparation', error);
|
|
114
|
+
}
|
|
115
|
+
let returned;
|
|
116
|
+
try {
|
|
117
|
+
const body = `"use strict";\n${code}\nreturn [${returnNames.join(', ')}];\n`;
|
|
118
|
+
returned = new Function(...argumentNames, body)(...visibleValues, ...enumValues);
|
|
119
|
+
}
|
|
120
|
+
catch (error) {
|
|
121
|
+
runtimeFailure(plan, file, 'execution', error);
|
|
122
|
+
}
|
|
123
|
+
if (!Array.isArray(returned) || returned.length !== returnNames.length) {
|
|
124
|
+
runtimeFailure(plan, file, 'bridge writeback', new Error('The TypeScript block returned an invalid bridge result'));
|
|
125
|
+
}
|
|
126
|
+
const outputValues = returned.slice(0, plan.outputs.length);
|
|
127
|
+
const mutableValues = returned.slice(plan.outputs.length);
|
|
128
|
+
for (let index = 0; index < plan.outputs.length; index++) {
|
|
129
|
+
const output = plan.outputs[index];
|
|
130
|
+
validateRuntimeValue(outputValues[index], output.type, env, output.source, file, output.name);
|
|
131
|
+
}
|
|
132
|
+
for (let index = 0; index < mutableBindings.length; index++) {
|
|
133
|
+
const binding = mutableBindings[index];
|
|
134
|
+
validateRuntimeValue(mutableValues[index], binding.type, env, binding.source, file, binding.name);
|
|
135
|
+
}
|
|
136
|
+
for (let index = 0; index < plan.outputs.length; index++) {
|
|
137
|
+
const output = plan.outputs[index];
|
|
138
|
+
const value = output.mutable ? outputValues[index] : cloneData(outputValues[index]);
|
|
139
|
+
env.set(output.name, value);
|
|
140
|
+
if (!output.mutable)
|
|
141
|
+
env.markImmutable(value);
|
|
142
|
+
}
|
|
143
|
+
for (let index = 0; index < mutableBindings.length; index++) {
|
|
144
|
+
const binding = mutableBindings[index];
|
|
145
|
+
env.update(binding.name, mutableValues[index], binding.source, file);
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
export function evaluateDocumentNodes(doc, env, file, plans, prepared) {
|
|
149
|
+
for (let nodeIndex = 0; nodeIndex < doc.nodes.length; nodeIndex++) {
|
|
150
|
+
const node = doc.nodes[nodeIndex];
|
|
151
|
+
env.currentDocumentNodeIndex = nodeIndex;
|
|
152
|
+
if (node.type === 'executableCodeBlock') {
|
|
153
|
+
evaluateStatements(node.statements, env, file);
|
|
154
|
+
continue;
|
|
155
|
+
}
|
|
156
|
+
if (node.type !== 'typescriptCodeBlock')
|
|
157
|
+
continue;
|
|
158
|
+
const plan = plans.get(nodeIndex);
|
|
159
|
+
const code = prepared.get(nodeIndex);
|
|
160
|
+
if (!plan || code === undefined) {
|
|
161
|
+
throw new AmxError({
|
|
162
|
+
code: 'AMX3022',
|
|
163
|
+
message: 'TypeScript runtime bridge was not prepared for this block',
|
|
164
|
+
file,
|
|
165
|
+
line: node.source.line,
|
|
166
|
+
column: node.source.column
|
|
167
|
+
});
|
|
168
|
+
}
|
|
169
|
+
evaluateTypeScriptBlock(plan, code, env, file);
|
|
170
|
+
}
|
|
171
|
+
}
|
package/dist/transpiler/emit.js
CHANGED
|
@@ -53,6 +53,7 @@ class ModuleEmitter {
|
|
|
53
53
|
inputs;
|
|
54
54
|
sourceFile;
|
|
55
55
|
expressionLoopReturns = [];
|
|
56
|
+
readonlyTypeName;
|
|
56
57
|
constructor(module, isEntry, measurementDimensionIds) {
|
|
57
58
|
this.module = module;
|
|
58
59
|
this.isEntry = isEntry;
|
|
@@ -94,6 +95,13 @@ class ModuleEmitter {
|
|
|
94
95
|
}
|
|
95
96
|
for (const statement of module.statements)
|
|
96
97
|
this.collectMutationTargets(statement);
|
|
98
|
+
for (const plan of module.typescriptBlocks.values()) {
|
|
99
|
+
for (const binding of plan.visibleBindings) {
|
|
100
|
+
if (binding.mutable)
|
|
101
|
+
this.mutationTargets.add(binding.name);
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
this.readonlyTypeName = this.uniqueInternalName('tsReadonly');
|
|
97
105
|
}
|
|
98
106
|
name(value) {
|
|
99
107
|
return `${this.prefix}${value}`;
|
|
@@ -101,6 +109,9 @@ class ModuleEmitter {
|
|
|
101
109
|
sourceContext(source) {
|
|
102
110
|
return `{ file: ${quote(this.sourceFile)}${source ? `, line: ${source.line}, column: ${source.column}` : ''} }`;
|
|
103
111
|
}
|
|
112
|
+
validationContext(source, inputPath) {
|
|
113
|
+
return `{ ...${this.sourceContext(source)}, inputPath: ${quote(inputPath)} }`;
|
|
114
|
+
}
|
|
104
115
|
checkedTypeForReference(reference, owner) {
|
|
105
116
|
if (reference.type === 'listType')
|
|
106
117
|
return { kind: 'list', element: this.checkedTypeForReference(reference.element, owner) };
|
|
@@ -245,6 +256,130 @@ class ModuleEmitter {
|
|
|
245
256
|
castExpression(code, type) {
|
|
246
257
|
return `(${code} as unknown as ${this.typeScriptType(type)})`;
|
|
247
258
|
}
|
|
259
|
+
uniqueInternalName(base) {
|
|
260
|
+
const sourceNames = new Set([
|
|
261
|
+
...this.localTypes.keys(),
|
|
262
|
+
...this.recordTypes.keys(),
|
|
263
|
+
...this.enumTypes.keys(),
|
|
264
|
+
...this.functions.keys(),
|
|
265
|
+
...this.viewDefinitions.keys()
|
|
266
|
+
]);
|
|
267
|
+
let candidate = base;
|
|
268
|
+
while (sourceNames.has(candidate)
|
|
269
|
+
|| [...this.module.typescriptBlocks.values()].some(plan => plan.node.content.includes(`${this.prefix}${candidate}`))) {
|
|
270
|
+
candidate += '_';
|
|
271
|
+
}
|
|
272
|
+
return `${this.prefix}${candidate}`;
|
|
273
|
+
}
|
|
274
|
+
bridgeTypeScriptType(type, plan, nodeIndex, readonlyArrays = false, seenRecords = new Set()) {
|
|
275
|
+
if (type.kind === 'list' || type.kind === 'nullable') {
|
|
276
|
+
const element = this.bridgeTypeScriptType(type.element, plan, nodeIndex, readonlyArrays, seenRecords);
|
|
277
|
+
if (!element)
|
|
278
|
+
return undefined;
|
|
279
|
+
if (type.kind === 'nullable')
|
|
280
|
+
return `${element} | null`;
|
|
281
|
+
return readonlyArrays ? `ReadonlyArray<${element}>` : `(${element})[]`;
|
|
282
|
+
}
|
|
283
|
+
if (type.kind !== 'named')
|
|
284
|
+
return undefined;
|
|
285
|
+
if (type.name === 'Number')
|
|
286
|
+
return 'number';
|
|
287
|
+
if (type.name === 'String')
|
|
288
|
+
return 'string';
|
|
289
|
+
if (type.name === 'Boolean')
|
|
290
|
+
return 'boolean';
|
|
291
|
+
if (type.name === 'DateTime')
|
|
292
|
+
return 'DateTime';
|
|
293
|
+
if (plan.visibleEnums.has(type.name))
|
|
294
|
+
return type.name;
|
|
295
|
+
if (plan.visibleTypes.has(type.name)
|
|
296
|
+
&& this.bridgeRecordTypeSupported(type.name, plan, nodeIndex, seenRecords))
|
|
297
|
+
return type.name;
|
|
298
|
+
return undefined;
|
|
299
|
+
}
|
|
300
|
+
bridgeRecordTypeSupported(name, plan, nodeIndex, seen = new Set()) {
|
|
301
|
+
const declaration = plan.visibleTypes.get(name);
|
|
302
|
+
if (!declaration || declaration.fields.some(field => field.optional) || seen.has(name))
|
|
303
|
+
return false;
|
|
304
|
+
const nextSeen = new Set(seen).add(name);
|
|
305
|
+
return declaration.fields.every(field => this.bridgeTypeScriptType(this.checkedTypeForReference(field.annotation, field), plan, nodeIndex, true, nextSeen) !== undefined);
|
|
306
|
+
}
|
|
307
|
+
checkedTypeDescriptor(type, source) {
|
|
308
|
+
if (type.kind === 'list') {
|
|
309
|
+
return `{ kind: 'list', element: ${this.checkedTypeDescriptor(type.element, source)} }`;
|
|
310
|
+
}
|
|
311
|
+
if (type.kind === 'nullable') {
|
|
312
|
+
return `{ kind: 'nullable', value: ${this.checkedTypeDescriptor(type.element, source)} }`;
|
|
313
|
+
}
|
|
314
|
+
if (type.kind === 'named') {
|
|
315
|
+
return this.inputDescriptor({ type: 'namedType', name: type.name }, new Set(), this.module.check, false);
|
|
316
|
+
}
|
|
317
|
+
throw new LoweringFailure('TypeScript bridge value has no AMX runtime descriptor', source?.line, source?.column);
|
|
318
|
+
}
|
|
319
|
+
bridgeTypeAliases(plan, nodeIndex, depth) {
|
|
320
|
+
const indent = ' '.repeat(depth);
|
|
321
|
+
const lines = [
|
|
322
|
+
`${indent}type DateTime = string & { readonly ${quote(`${this.prefix}dateTime_${nodeIndex}`)}: true };`
|
|
323
|
+
];
|
|
324
|
+
for (const [name, declaration] of plan.visibleTypes) {
|
|
325
|
+
if (!this.bridgeRecordTypeSupported(name, plan, nodeIndex))
|
|
326
|
+
continue;
|
|
327
|
+
const fields = declaration.fields.map(field => {
|
|
328
|
+
const type = this.bridgeTypeScriptType(this.checkedTypeForReference(field.annotation, field), plan, nodeIndex, true, new Set([name]));
|
|
329
|
+
if (!type)
|
|
330
|
+
throw new LoweringFailure(`Missing TypeScript bridge type for field '${name}.${field.name}'`, field.source?.line, field.source?.column);
|
|
331
|
+
return `readonly ${quote(field.name)}: ${type};`;
|
|
332
|
+
});
|
|
333
|
+
fields.push(`readonly ${quote(`${this.prefix}record_${nodeIndex}_${hash(name)}`)}: true;`);
|
|
334
|
+
lines.push(`${indent}type ${name} = { ${fields.join(' ')} };`);
|
|
335
|
+
}
|
|
336
|
+
for (const [name, declaration] of plan.visibleEnums) {
|
|
337
|
+
const values = declaration.resolvedValues ?? [];
|
|
338
|
+
if (values.length !== declaration.members.length)
|
|
339
|
+
continue;
|
|
340
|
+
const valueName = this.name(name);
|
|
341
|
+
const brand = quote(`${this.prefix}enum_${nodeIndex}_${hash(name)}`);
|
|
342
|
+
lines.push(`${indent}type ${name} = (typeof ${valueName}[keyof typeof ${valueName}]) & { readonly ${brand}: true };`);
|
|
343
|
+
const members = declaration.members.map(member => `readonly ${quote(member.name)}: ${name};`).join(' ');
|
|
344
|
+
lines.push(`${indent}const ${name} = ${valueName} as unknown as { ${members} };`);
|
|
345
|
+
}
|
|
346
|
+
return lines;
|
|
347
|
+
}
|
|
348
|
+
emitTypeScriptBlock(plan, depth) {
|
|
349
|
+
const nodeIndex = plan.nodeIndex;
|
|
350
|
+
const indent = ' '.repeat(depth);
|
|
351
|
+
const innerIndent = ' '.repeat(depth + 1);
|
|
352
|
+
const resultName = this.uniqueInternalName(`ts_${nodeIndex}_result`);
|
|
353
|
+
const mutableBindings = plan.visibleBindings.filter(binding => binding.mutable
|
|
354
|
+
&& this.bridgeTypeScriptType(binding.type, plan, nodeIndex) !== undefined);
|
|
355
|
+
const outputBindings = plan.outputs.filter(output => this.bridgeTypeScriptType(output.type, plan, nodeIndex, !output.mutable) !== undefined);
|
|
356
|
+
const declarations = plan.visibleBindings.flatMap(binding => {
|
|
357
|
+
const type = this.bridgeTypeScriptType(binding.type, plan, nodeIndex, !binding.mutable);
|
|
358
|
+
if (!type)
|
|
359
|
+
return [];
|
|
360
|
+
const keyword = binding.mutable ? 'let' : 'const';
|
|
361
|
+
return [`${innerIndent}${keyword} ${binding.name}: ${type} = ${this.name(binding.name)} as unknown as ${type};`];
|
|
362
|
+
});
|
|
363
|
+
const returnedBindings = mutableBindings.map(binding => `${quote(binding.name)}: ${binding.name}`);
|
|
364
|
+
const returnedOutputs = outputBindings.map(output => `${quote(output.name)}: ${output.name}`);
|
|
365
|
+
const body = [
|
|
366
|
+
`${indent}const ${resultName} = (() => {`,
|
|
367
|
+
...this.bridgeTypeAliases(plan, nodeIndex, depth + 1),
|
|
368
|
+
...declarations,
|
|
369
|
+
plan.node.content,
|
|
370
|
+
`${innerIndent}return { ${[...returnedBindings, ...returnedOutputs].join(', ')} };`,
|
|
371
|
+
`${indent}})();`
|
|
372
|
+
].join('\n');
|
|
373
|
+
const outputValidation = outputBindings.map(output => `${indent}__amxValidateValue<${this.typeScriptType(output.type)}>(${resultName}[${quote(output.name)}], ${this.checkedTypeDescriptor(output.type, output.source)}, ${this.validationContext(output.source, output.name)});`);
|
|
374
|
+
const mutableValidation = mutableBindings.map(binding => `${indent}__amxValidateValue<${this.typeScriptType(binding.type)}>(${resultName}[${quote(binding.name)}], ${this.checkedTypeDescriptor(binding.type, binding.source)}, ${this.validationContext(binding.source, binding.name)});`);
|
|
375
|
+
const writebacks = mutableBindings.map(binding => `${indent}${this.name(binding.name)} = ${resultName}[${quote(binding.name)}] as unknown as ${this.typeScriptType(binding.type)};`);
|
|
376
|
+
const outputDeclarations = outputBindings.map(output => {
|
|
377
|
+
const type = this.typeScriptType(output.type);
|
|
378
|
+
const outerType = output.mutable ? type : `${this.readonlyTypeName}<${type}>`;
|
|
379
|
+
return `${indent}${output.mutable ? 'let' : 'const'} ${this.name(output.name)}: ${outerType} = ${resultName}[${quote(output.name)}] as unknown as ${outerType};`;
|
|
380
|
+
});
|
|
381
|
+
return [body, ...outputValidation, ...mutableValidation, ...writebacks, ...outputDeclarations];
|
|
382
|
+
}
|
|
248
383
|
expression(expression, expected) {
|
|
249
384
|
const resultType = this.expressionType(expression, expected);
|
|
250
385
|
const context = this.sourceContext(expression.source);
|
|
@@ -558,11 +693,11 @@ class ModuleEmitter {
|
|
|
558
693
|
`${indent}})();`
|
|
559
694
|
];
|
|
560
695
|
}
|
|
561
|
-
inputDescriptor(reference, seen = new Set(), registry = this.module.check) {
|
|
696
|
+
inputDescriptor(reference, seen = new Set(), registry = this.module.check, includeDefaults = true) {
|
|
562
697
|
if (reference.type === 'listType')
|
|
563
|
-
return `{ kind: 'list', element: ${this.inputDescriptor(reference.element, seen, registry)} }`;
|
|
698
|
+
return `{ kind: 'list', element: ${this.inputDescriptor(reference.element, seen, registry, includeDefaults)} }`;
|
|
564
699
|
if (reference.type === 'nullableType')
|
|
565
|
-
return `{ kind: 'nullable', value: ${this.inputDescriptor(reference.element, seen, registry)} }`;
|
|
700
|
+
return `{ kind: 'nullable', value: ${this.inputDescriptor(reference.element, seen, registry, includeDefaults)} }`;
|
|
566
701
|
const name = reference.name;
|
|
567
702
|
if (name === 'Number')
|
|
568
703
|
return `{ kind: 'number' }`;
|
|
@@ -589,10 +724,10 @@ class ModuleEmitter {
|
|
|
589
724
|
const nested = new Set(seen).add(name);
|
|
590
725
|
const fields = declaration.fields.map(field => {
|
|
591
726
|
const fieldScope = fieldRegistry(field, registry) ?? registry;
|
|
592
|
-
const defaultValue = field.defaultExpression
|
|
727
|
+
const defaultValue = includeDefaults && field.defaultExpression
|
|
593
728
|
? `, defaultValue: () => ${this.expression(field.defaultExpression, this.checkedTypeForReference(field.annotation, field))}`
|
|
594
729
|
: '';
|
|
595
|
-
return `{ name: ${quote(field.name)}, descriptor: ${this.inputDescriptor(field.annotation, nested, fieldScope)}${field.optional ? ', optional: true' : ''}${defaultValue} }`;
|
|
730
|
+
return `{ name: ${quote(field.name)}, descriptor: ${this.inputDescriptor(field.annotation, nested, fieldScope, includeDefaults)}${field.optional ? ', optional: true' : ''}${defaultValue} }`;
|
|
596
731
|
});
|
|
597
732
|
return `{ kind: 'record', recordName: ${quote(name)}, fields: [${fields.join(', ')}] }`;
|
|
598
733
|
}
|
|
@@ -709,7 +844,8 @@ class ModuleEmitter {
|
|
|
709
844
|
const code = [];
|
|
710
845
|
code.push(...rawFrontMatterComments(this.module.input.sourceText));
|
|
711
846
|
const runtimeStatements = [];
|
|
712
|
-
for (
|
|
847
|
+
for (let nodeIndex = 0; nodeIndex < this.module.document.nodes.length; nodeIndex++) {
|
|
848
|
+
const node = this.module.document.nodes[nodeIndex];
|
|
713
849
|
if (node.type === 'narrative')
|
|
714
850
|
runtimeStatements.push(...safeNarrativeComments(node.content).map(line => ` ${line}`));
|
|
715
851
|
else if (node.type === 'variableDeclaration')
|
|
@@ -718,6 +854,12 @@ class ModuleEmitter {
|
|
|
718
854
|
for (const statement of node.statements)
|
|
719
855
|
runtimeStatements.push(...this.emitStatement(statement, 1));
|
|
720
856
|
}
|
|
857
|
+
else if (node.type === 'typescriptCodeBlock') {
|
|
858
|
+
const plan = this.module.typescriptBlocks.get(nodeIndex);
|
|
859
|
+
if (!plan)
|
|
860
|
+
throw new LoweringFailure('Missing checked TypeScript runtime plan', node.source?.line, node.source?.column);
|
|
861
|
+
runtimeStatements.push(...this.emitTypeScriptBlock(plan, 1));
|
|
862
|
+
}
|
|
721
863
|
}
|
|
722
864
|
const localDeclarations = statements.filter((statement) => statement.type === 'typeDeclaration' || statement.type === 'enumDeclaration');
|
|
723
865
|
const declarationCode = localDeclarations.map(statement => statement.type === 'typeDeclaration'
|
|
@@ -785,6 +927,9 @@ class ModuleEmitter {
|
|
|
785
927
|
...staticImports,
|
|
786
928
|
`import { amxAdd1Based as __amxAdd1Based, amxAttach as __amxAttach, amxBinary as __amxBinary, amxBuiltin as __amxBuiltin, amxChartView as __amxChartView, amxConvert as __amxConvert, amxCopyListArgument as __amxCopyListArgument, amxDiagramView as __amxDiagramView, amxFormatValue as __amxFormatValue, amxGet1Based as __amxGet1Based, amxIsType as __amxIsType, amxIterate as __amxIterate, amxPhysicalValue as __amxPhysicalValue, amxRange as __amxRange, amxRemove1Based as __amxRemove1Based, amxTableView as __amxTableView, amxUnary as __amxUnary, validateAMXValue as __amxValidateValue, AMXInputError as __AMXInputError, AMXRuntimeError as __AMXRuntimeError, type AMXBuiltinName as __AMXBuiltinName, type AMXDiagramPrimitiveElement as __AMXDiagramPrimitiveElement, type AMXInputDescriptor as __AMXInputDescriptor, type AMXMeasurement as __AMXMeasurement, type AMXMeasurementInput as __AMXMeasurementInput, type AMXRunResult as __AMXRunResult, type AMXRuntimeContext as __AMXRuntimeContext, type AMXShownView as __AMXShownView, type AMXUnitDescriptor as __AMXUnitDescriptor, type AMXValue as __AMXValue, type AMXViewData as __AMXViewData } from 'openamx/transpiler-runtime';`,
|
|
787
929
|
...declarationCode,
|
|
930
|
+
...(this.module.typescriptBlocks.size ? [
|
|
931
|
+
`type ${this.readonlyTypeName}<T> = T extends readonly (infer U)[] ? ReadonlyArray<${this.readonlyTypeName}<U>> : T extends object ? { readonly [K in keyof T]: ${this.readonlyTypeName}<T[K]> } : T;`
|
|
932
|
+
] : []),
|
|
788
933
|
...functionCode,
|
|
789
934
|
`const __amxUnits: readonly __AMXUnitDescriptor[] = [${unitDescriptors.join(', ')}];`,
|
|
790
935
|
`const __amxRuntime: __AMXRuntimeContext = { file: ${quote(this.sourceFile)}, unitDescriptors: __amxUnits };`,
|