@nova-energy/openamx 0.21.0 → 0.23.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.
@@ -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
+ }
@@ -1,9 +1,12 @@
1
1
  import { isMeasurement } from './measurement';
2
+ import { formatComplex, isComplex } from './complex';
2
3
  export function formatAmxValue(value, nullText = '') {
3
4
  if (value === null || value === undefined)
4
5
  return nullText;
5
6
  if (Array.isArray(value))
6
7
  return value.map(item => formatAmxValue(item, nullText)).join(', ');
8
+ if (isComplex(value))
9
+ return formatComplex(value);
7
10
  if (isMeasurement(value))
8
11
  return `${String(value.value)} ${value.unit.text}`;
9
12
  if (typeof value === 'object')
@@ -1,5 +1,6 @@
1
1
  import { fieldRegistry } from '../typechecker/declarationRegistry';
2
2
  import { rawFrontMatterComments, safeNarrativeComments } from './source';
3
+ import { dateTimeUnitValues } from '../runtime/dateTime';
3
4
  export class LoweringFailure extends Error {
4
5
  line;
5
6
  column;
@@ -11,7 +12,8 @@ export class LoweringFailure extends Error {
11
12
  }
12
13
  }
13
14
  const builtinNames = new Set([
14
- 'sum', 'min', 'max', 'mean', 'round', 'abs', 'sqrt', 'pow', 'len', 'trim',
15
+ 'sum', 'min', 'max', 'mean', 'round', 'abs', 'sqrt', 'pow', 'len', 'trim', 'conjugate', 'arg',
16
+ 'now', 'createDateTime', 'dateDiff', 'addToDateTime', 'subtractFromDateTime',
15
17
  'left', 'right', 'format', 'sin', 'cos', 'tan', 'asin', 'acos', 'atan',
16
18
  'sinh', 'cosh', 'tanh', 'asinh', 'acosh', 'atanh', 'ln', 'log', 'exp'
17
19
  ]);
@@ -53,6 +55,7 @@ class ModuleEmitter {
53
55
  inputs;
54
56
  sourceFile;
55
57
  expressionLoopReturns = [];
58
+ readonlyTypeName;
56
59
  constructor(module, isEntry, measurementDimensionIds) {
57
60
  this.module = module;
58
61
  this.isEntry = isEntry;
@@ -94,6 +97,13 @@ class ModuleEmitter {
94
97
  }
95
98
  for (const statement of module.statements)
96
99
  this.collectMutationTargets(statement);
100
+ for (const plan of module.typescriptBlocks.values()) {
101
+ for (const binding of plan.visibleBindings) {
102
+ if (binding.mutable)
103
+ this.mutationTargets.add(binding.name);
104
+ }
105
+ }
106
+ this.readonlyTypeName = this.uniqueInternalName('tsReadonly');
97
107
  }
98
108
  name(value) {
99
109
  return `${this.prefix}${value}`;
@@ -101,6 +111,9 @@ class ModuleEmitter {
101
111
  sourceContext(source) {
102
112
  return `{ file: ${quote(this.sourceFile)}${source ? `, line: ${source.line}, column: ${source.column}` : ''} }`;
103
113
  }
114
+ validationContext(source, inputPath) {
115
+ return `{ ...${this.sourceContext(source)}, inputPath: ${quote(inputPath)} }`;
116
+ }
104
117
  checkedTypeForReference(reference, owner) {
105
118
  if (reference.type === 'listType')
106
119
  return { kind: 'list', element: this.checkedTypeForReference(reference.element, owner) };
@@ -128,6 +141,8 @@ class ModuleEmitter {
128
141
  return 'string';
129
142
  if (type.name === 'Boolean')
130
143
  return 'boolean';
144
+ if (type.name === 'Complex')
145
+ return 'Readonly<{ real: number; imaginary: number }>';
131
146
  if (external && this.recordTypes.has(type.name))
132
147
  return `__AMXExternal_${this.name(type.name)}`;
133
148
  return this.name(type.name);
@@ -164,16 +179,23 @@ class ModuleEmitter {
164
179
  return expected;
165
180
  switch (expression.type) {
166
181
  case 'numberLiteral': return { kind: 'named', name: 'Number' };
182
+ case 'imaginaryLiteral': return { kind: 'named', name: 'Complex' };
167
183
  case 'stringLiteral':
168
184
  case 'stringInterpolation': return { kind: 'named', name: 'String' };
169
185
  case 'booleanLiteral':
170
186
  case 'typeTestExpression': return { kind: 'named', name: 'Boolean' };
171
187
  case 'nullLiteral': return { kind: 'null' };
172
188
  case 'identifier': return this.localTypes.get(expression.name) ?? { kind: 'named', name: 'Number' };
173
- case 'binaryExpression':
189
+ case 'binaryExpression': {
174
190
  if (isComparison(expression.operator))
175
191
  return { kind: 'named', name: 'Boolean' };
176
- return this.expressionType(expression.left);
192
+ const left = this.expressionType(expression.left);
193
+ const right = this.expressionType(expression.right);
194
+ return left.kind === 'named' && left.name === 'Complex'
195
+ || right.kind === 'named' && right.name === 'Complex'
196
+ ? { kind: 'named', name: 'Complex' }
197
+ : left;
198
+ }
177
199
  case 'unaryExpression': return expression.operator === 'not'
178
200
  ? { kind: 'named', name: 'Boolean' }
179
201
  : this.expressionType(expression.argument);
@@ -245,11 +267,137 @@ class ModuleEmitter {
245
267
  castExpression(code, type) {
246
268
  return `(${code} as unknown as ${this.typeScriptType(type)})`;
247
269
  }
270
+ uniqueInternalName(base) {
271
+ const sourceNames = new Set([
272
+ ...this.localTypes.keys(),
273
+ ...this.recordTypes.keys(),
274
+ ...this.enumTypes.keys(),
275
+ ...this.functions.keys(),
276
+ ...this.viewDefinitions.keys()
277
+ ]);
278
+ let candidate = base;
279
+ while (sourceNames.has(candidate)
280
+ || [...this.module.typescriptBlocks.values()].some(plan => plan.node.content.includes(`${this.prefix}${candidate}`))) {
281
+ candidate += '_';
282
+ }
283
+ return `${this.prefix}${candidate}`;
284
+ }
285
+ bridgeTypeScriptType(type, plan, nodeIndex, readonlyArrays = false, seenRecords = new Set()) {
286
+ if (type.kind === 'list' || type.kind === 'nullable') {
287
+ const element = this.bridgeTypeScriptType(type.element, plan, nodeIndex, readonlyArrays, seenRecords);
288
+ if (!element)
289
+ return undefined;
290
+ if (type.kind === 'nullable')
291
+ return `${element} | null`;
292
+ return readonlyArrays ? `ReadonlyArray<${element}>` : `(${element})[]`;
293
+ }
294
+ if (type.kind !== 'named')
295
+ return undefined;
296
+ if (type.name === 'Number')
297
+ return 'number';
298
+ if (type.name === 'String')
299
+ return 'string';
300
+ if (type.name === 'Boolean')
301
+ return 'boolean';
302
+ if (type.name === 'DateTime')
303
+ return 'DateTime';
304
+ if (plan.visibleEnums.has(type.name))
305
+ return type.name;
306
+ if (plan.visibleTypes.has(type.name)
307
+ && this.bridgeRecordTypeSupported(type.name, plan, nodeIndex, seenRecords))
308
+ return type.name;
309
+ return undefined;
310
+ }
311
+ bridgeRecordTypeSupported(name, plan, nodeIndex, seen = new Set()) {
312
+ const declaration = plan.visibleTypes.get(name);
313
+ if (!declaration || declaration.fields.some(field => field.optional) || seen.has(name))
314
+ return false;
315
+ const nextSeen = new Set(seen).add(name);
316
+ return declaration.fields.every(field => this.bridgeTypeScriptType(this.checkedTypeForReference(field.annotation, field), plan, nodeIndex, true, nextSeen) !== undefined);
317
+ }
318
+ checkedTypeDescriptor(type, source) {
319
+ if (type.kind === 'list') {
320
+ return `{ kind: 'list', element: ${this.checkedTypeDescriptor(type.element, source)} }`;
321
+ }
322
+ if (type.kind === 'nullable') {
323
+ return `{ kind: 'nullable', value: ${this.checkedTypeDescriptor(type.element, source)} }`;
324
+ }
325
+ if (type.kind === 'named') {
326
+ return this.inputDescriptor({ type: 'namedType', name: type.name }, new Set(), this.module.check, false);
327
+ }
328
+ throw new LoweringFailure('TypeScript bridge value has no AMX runtime descriptor', source?.line, source?.column);
329
+ }
330
+ bridgeTypeAliases(plan, nodeIndex, depth) {
331
+ const indent = ' '.repeat(depth);
332
+ const lines = [
333
+ `${indent}type DateTime = string & { readonly ${quote(`${this.prefix}dateTime_${nodeIndex}`)}: true };`
334
+ ];
335
+ for (const [name, declaration] of plan.visibleTypes) {
336
+ if (!this.bridgeRecordTypeSupported(name, plan, nodeIndex))
337
+ continue;
338
+ const fields = declaration.fields.map(field => {
339
+ const type = this.bridgeTypeScriptType(this.checkedTypeForReference(field.annotation, field), plan, nodeIndex, true, new Set([name]));
340
+ if (!type)
341
+ throw new LoweringFailure(`Missing TypeScript bridge type for field '${name}.${field.name}'`, field.source?.line, field.source?.column);
342
+ return `readonly ${quote(field.name)}: ${type};`;
343
+ });
344
+ fields.push(`readonly ${quote(`${this.prefix}record_${nodeIndex}_${hash(name)}`)}: true;`);
345
+ lines.push(`${indent}type ${name} = { ${fields.join(' ')} };`);
346
+ }
347
+ for (const [name, declaration] of plan.visibleEnums) {
348
+ const values = declaration.resolvedValues ?? [];
349
+ if (values.length !== declaration.members.length)
350
+ continue;
351
+ const valueName = this.name(name);
352
+ const brand = quote(`${this.prefix}enum_${nodeIndex}_${hash(name)}`);
353
+ lines.push(`${indent}type ${name} = (typeof ${valueName}[keyof typeof ${valueName}]) & { readonly ${brand}: true };`);
354
+ const members = declaration.members.map(member => `readonly ${quote(member.name)}: ${name};`).join(' ');
355
+ lines.push(`${indent}const ${name} = ${valueName} as unknown as { ${members} };`);
356
+ }
357
+ return lines;
358
+ }
359
+ emitTypeScriptBlock(plan, depth) {
360
+ const nodeIndex = plan.nodeIndex;
361
+ const indent = ' '.repeat(depth);
362
+ const innerIndent = ' '.repeat(depth + 1);
363
+ const resultName = this.uniqueInternalName(`ts_${nodeIndex}_result`);
364
+ const mutableBindings = plan.visibleBindings.filter(binding => binding.mutable
365
+ && this.bridgeTypeScriptType(binding.type, plan, nodeIndex) !== undefined);
366
+ const outputBindings = plan.outputs.filter(output => this.bridgeTypeScriptType(output.type, plan, nodeIndex, !output.mutable) !== undefined);
367
+ const declarations = plan.visibleBindings.flatMap(binding => {
368
+ const type = this.bridgeTypeScriptType(binding.type, plan, nodeIndex, !binding.mutable);
369
+ if (!type)
370
+ return [];
371
+ const keyword = binding.mutable ? 'let' : 'const';
372
+ return [`${innerIndent}${keyword} ${binding.name}: ${type} = ${this.name(binding.name)} as unknown as ${type};`];
373
+ });
374
+ const returnedBindings = mutableBindings.map(binding => `${quote(binding.name)}: ${binding.name}`);
375
+ const returnedOutputs = outputBindings.map(output => `${quote(output.name)}: ${output.name}`);
376
+ const body = [
377
+ `${indent}const ${resultName} = (() => {`,
378
+ ...this.bridgeTypeAliases(plan, nodeIndex, depth + 1),
379
+ ...declarations,
380
+ plan.node.content,
381
+ `${innerIndent}return { ${[...returnedBindings, ...returnedOutputs].join(', ')} };`,
382
+ `${indent}})();`
383
+ ].join('\n');
384
+ 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)});`);
385
+ 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)});`);
386
+ const writebacks = mutableBindings.map(binding => `${indent}${this.name(binding.name)} = ${resultName}[${quote(binding.name)}] as unknown as ${this.typeScriptType(binding.type)};`);
387
+ const outputDeclarations = outputBindings.map(output => {
388
+ const type = this.typeScriptType(output.type);
389
+ const outerType = output.mutable ? type : `${this.readonlyTypeName}<${type}>`;
390
+ return `${indent}${output.mutable ? 'let' : 'const'} ${this.name(output.name)}: ${outerType} = ${resultName}[${quote(output.name)}] as unknown as ${outerType};`;
391
+ });
392
+ return [body, ...outputValidation, ...mutableValidation, ...writebacks, ...outputDeclarations];
393
+ }
248
394
  expression(expression, expected) {
249
395
  const resultType = this.expressionType(expression, expected);
250
396
  const context = this.sourceContext(expression.source);
251
397
  switch (expression.type) {
252
398
  case 'numberLiteral': return String(expression.value);
399
+ case 'imaginaryLiteral':
400
+ return `__amxComplex(0, ${String(expression.coefficient)}, ${context})`;
253
401
  case 'stringLiteral': return quote(expression.value);
254
402
  case 'booleanLiteral': return String(expression.value);
255
403
  case 'nullLiteral': return 'null';
@@ -290,11 +438,16 @@ class ModuleEmitter {
290
438
  case 'listAccess':
291
439
  return this.castExpression(`__amxGet1Based(${this.expression(expression.receiver)} as unknown as __AMXValue[], ${this.expression(expression.index, { kind: 'named', name: 'Number' })}, ${context})`, resultType);
292
440
  case 'fieldAccess':
441
+ if (expression.receiver.type === 'identifier' && expression.receiver.name === 'DateTimeUnit'
442
+ && dateTimeUnitValues.includes(expression.field))
443
+ return quote(expression.field);
293
444
  return `${this.expression(expression.receiver)}[${quote(expression.field)}]`;
294
445
  case 'functionCall': {
295
446
  const args = expression.arguments.map(argument => this.expression(argument));
296
447
  if (builtinNames.has(expression.callee)) {
297
- return this.castExpression(`__amxBuiltin(${quote(expression.callee)} as __AMXBuiltinName, [${args.map(argument => `${argument} as unknown as __AMXValue`).join(', ')}], __amxRuntime)`, resultType);
448
+ const argumentContexts = expression.arguments.map(argument => this.sourceContext(argument.source)).join(', ');
449
+ const runtimeContext = `Object.assign({ ...__amxRuntime, ...${this.sourceContext(expression.source)} }, { argumentContexts: [${argumentContexts}] })`;
450
+ return this.castExpression(`__amxBuiltin(${quote(expression.callee)} as __AMXBuiltinName, [${args.map(argument => `${argument} as unknown as __AMXValue`).join(', ')}], ${runtimeContext})`, resultType);
298
451
  }
299
452
  const fn = this.functions.get(expression.callee);
300
453
  if (!fn)
@@ -558,11 +711,11 @@ class ModuleEmitter {
558
711
  `${indent}})();`
559
712
  ];
560
713
  }
561
- inputDescriptor(reference, seen = new Set(), registry = this.module.check) {
714
+ inputDescriptor(reference, seen = new Set(), registry = this.module.check, includeDefaults = true) {
562
715
  if (reference.type === 'listType')
563
- return `{ kind: 'list', element: ${this.inputDescriptor(reference.element, seen, registry)} }`;
716
+ return `{ kind: 'list', element: ${this.inputDescriptor(reference.element, seen, registry, includeDefaults)} }`;
564
717
  if (reference.type === 'nullableType')
565
- return `{ kind: 'nullable', value: ${this.inputDescriptor(reference.element, seen, registry)} }`;
718
+ return `{ kind: 'nullable', value: ${this.inputDescriptor(reference.element, seen, registry, includeDefaults)} }`;
566
719
  const name = reference.name;
567
720
  if (name === 'Number')
568
721
  return `{ kind: 'number' }`;
@@ -572,6 +725,8 @@ class ModuleEmitter {
572
725
  return `{ kind: 'boolean' }`;
573
726
  if (name === 'DateTime')
574
727
  return `{ kind: 'dateTime' }`;
728
+ if (name === 'Complex')
729
+ return `{ kind: 'complex' }`;
575
730
  const dimension = registry.dimensions.get(name);
576
731
  if (dimension) {
577
732
  const units = [...registry.units.values()].filter(unit => sameVector(unit.vector, dimension.vector));
@@ -589,10 +744,10 @@ class ModuleEmitter {
589
744
  const nested = new Set(seen).add(name);
590
745
  const fields = declaration.fields.map(field => {
591
746
  const fieldScope = fieldRegistry(field, registry) ?? registry;
592
- const defaultValue = field.defaultExpression
747
+ const defaultValue = includeDefaults && field.defaultExpression
593
748
  ? `, defaultValue: () => ${this.expression(field.defaultExpression, this.checkedTypeForReference(field.annotation, field))}`
594
749
  : '';
595
- return `{ name: ${quote(field.name)}, descriptor: ${this.inputDescriptor(field.annotation, nested, fieldScope)}${field.optional ? ', optional: true' : ''}${defaultValue} }`;
750
+ return `{ name: ${quote(field.name)}, descriptor: ${this.inputDescriptor(field.annotation, nested, fieldScope, includeDefaults)}${field.optional ? ', optional: true' : ''}${defaultValue} }`;
596
751
  });
597
752
  return `{ kind: 'record', recordName: ${quote(name)}, fields: [${fields.join(', ')}] }`;
598
753
  }
@@ -709,7 +864,8 @@ class ModuleEmitter {
709
864
  const code = [];
710
865
  code.push(...rawFrontMatterComments(this.module.input.sourceText));
711
866
  const runtimeStatements = [];
712
- for (const node of this.module.document.nodes) {
867
+ for (let nodeIndex = 0; nodeIndex < this.module.document.nodes.length; nodeIndex++) {
868
+ const node = this.module.document.nodes[nodeIndex];
713
869
  if (node.type === 'narrative')
714
870
  runtimeStatements.push(...safeNarrativeComments(node.content).map(line => ` ${line}`));
715
871
  else if (node.type === 'variableDeclaration')
@@ -718,6 +874,12 @@ class ModuleEmitter {
718
874
  for (const statement of node.statements)
719
875
  runtimeStatements.push(...this.emitStatement(statement, 1));
720
876
  }
877
+ else if (node.type === 'typescriptCodeBlock') {
878
+ const plan = this.module.typescriptBlocks.get(nodeIndex);
879
+ if (!plan)
880
+ throw new LoweringFailure('Missing checked TypeScript runtime plan', node.source?.line, node.source?.column);
881
+ runtimeStatements.push(...this.emitTypeScriptBlock(plan, 1));
882
+ }
721
883
  }
722
884
  const localDeclarations = statements.filter((statement) => statement.type === 'typeDeclaration' || statement.type === 'enumDeclaration');
723
885
  const declarationCode = localDeclarations.map(statement => statement.type === 'typeDeclaration'
@@ -780,15 +942,30 @@ class ModuleEmitter {
780
942
  const exportValues = [...this.module.check.exportedBindings.keys()].map(name => `${quote(name)}: ${this.name(name)}`).join(', ');
781
943
  const inputDescriptor = `{ kind: 'record', recordName: 'AMXRunInputs', fields: [${this.inputs.map(input => `{ name: ${quote(input.name)}, descriptor: ${this.inputDescriptor(input.annotation)} }`).join(', ')}] }`;
782
944
  const unitDescriptors = [...this.module.check.units.keys()].map(name => this.unitDescriptor(name));
945
+ const containsComplex = (type) => type.kind === 'named'
946
+ ? type.name === 'Complex'
947
+ : (type.kind === 'list' || type.kind === 'nullable') && containsComplex(type.element);
948
+ const hasComplexLiteral = [...runtimeStatements, ...functionCode, ...declarationCode]
949
+ .some(line => line.includes('__amxComplex('));
950
+ const needsComplexSupport = hasComplexLiteral || [...this.module.check.bindingTypes.values(), ...this.module.check.exportedBindings.values(),
951
+ ...this.inputs.map(input => this.checkedTypeForReference(input.annotation))]
952
+ .some(containsComplex)
953
+ || [...this.recordTypes.values()].some(declaration => declaration.fields.some(field => containsComplex(this.checkedTypeForReference(field.annotation, field))));
954
+ const complexHelperImport = needsComplexSupport
955
+ ? 'amxComplex as __amxComplex, amxIsComplex as __amxIsComplex, '
956
+ : '';
783
957
  const generated = [
784
958
  ...code,
785
959
  ...staticImports,
786
- `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';`,
960
+ `import { amxAdd1Based as __amxAdd1Based, amxAttach as __amxAttach, amxBinary as __amxBinary, amxBuiltin as __amxBuiltin, amxChartView as __amxChartView, ${complexHelperImport}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
961
  ...declarationCode,
962
+ ...(this.module.typescriptBlocks.size ? [
963
+ `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;`
964
+ ] : []),
788
965
  ...functionCode,
789
966
  `const __amxUnits: readonly __AMXUnitDescriptor[] = [${unitDescriptors.join(', ')}];`,
790
967
  `const __amxRuntime: __AMXRuntimeContext = { file: ${quote(this.sourceFile)}, unitDescriptors: __amxUnits };`,
791
- ...viewHelperSource(),
968
+ ...viewHelperSource(needsComplexSupport),
792
969
  `interface __AMXRunContext { readonly modules: Map<string, unknown>; readonly views: __AMXShownView[] }`,
793
970
  `export function __amxInitialize(__context: __AMXRunContext, __inputs: __AMXValidatedInputs = {} as __AMXValidatedInputs): Readonly<Record<string, unknown>> {`,
794
971
  ` if (__context.modules.has(${quote(this.module.input.outputPath)})) return __context.modules.get(${quote(this.module.input.outputPath)}) as Readonly<Record<string, unknown>>;`,
@@ -822,11 +999,12 @@ function moduleStatements(module) {
822
999
  function quoteIdentifier(name) {
823
1000
  return reservedWords.has(name) ? `[${quote(name)}]` : name;
824
1001
  }
825
- function viewHelperSource() {
1002
+ function viewHelperSource(complexSupport = false) {
1003
+ const complexGuard = complexSupport ? ' if (__amxIsComplex(value)) return value;' : '';
826
1004
  return [
827
1005
  `function __amxDiagramNumber(value: number, context: __AMXRuntimeContext, code: string, message: string, source: Readonly<{ file?: string; line?: number; column?: number }>, positive = false): number { if (!Number.isFinite(value) || positive && value <= 0) throw new __AMXRuntimeError({ code, message, file: source.file ?? context.file, line: source.line ?? context.line, column: source.column ?? context.column }); return value; }`,
828
1006
  `function __amxIsMeasurement(value: unknown): value is __AMXMeasurement { return typeof value === 'object' && value !== null && !Array.isArray(value) && '__amxMeasurement' in value && (value as { __amxMeasurement?: unknown }).__amxMeasurement === true; }`,
829
- `function __amxSnapshotViewValue(value: unknown): __AMXViewData { if (value === null || typeof value === 'string' || typeof value === 'boolean') return value; if (typeof value === 'number') return value; if (Array.isArray(value)) return value.map(__amxSnapshotViewValue); if (__amxIsMeasurement(value)) return String(value.value) + ' ' + value.unit.text; if (typeof value === 'object') { const copy: Record<string, __AMXViewData> = {}; for (const [field, item] of Object.entries(value)) copy[field] = __amxSnapshotViewValue(item); return copy; } return null; }`,
1007
+ `function __amxSnapshotViewValue(value: unknown): __AMXViewData { if (value === null || typeof value === 'string' || typeof value === 'boolean') return value; if (typeof value === 'number') return value; if (Array.isArray(value)) return value.map(__amxSnapshotViewValue);${complexGuard} if (__amxIsMeasurement(value)) return String(value.value) + ' ' + value.unit.text; if (typeof value === 'object') { const copy: Record<string, __AMXViewData> = {}; for (const [field, item] of Object.entries(value)) copy[field] = __amxSnapshotViewValue(item); return copy; } return null; }`,
830
1008
  `interface __AMXChartColumn { readonly role: 'series' | 'x' | 'y'; readonly field?: string; readonly label: string; readonly source?: Readonly<{ line?: number; column?: number }> }`,
831
1009
  `function __amxSameMeasurementDimension(left: __AMXMeasurement, right: __AMXMeasurement): boolean { const a = Object.entries(left.unit.vector); return a.length === Object.keys(right.unit.vector).length && a.every(([identity, exponent]) => right.unit.vector[identity] === exponent); }`,
832
1010
  `function __amxChartFailure(name: string, message: string, context: __AMXRuntimeContext, source?: __AMXChartColumn['source']): never { throw new __AMXRuntimeError({ code: 'AMX3007', message, file: context.file, line: source?.line ?? context.line, column: source?.column ?? context.column }); }`,
@@ -1,7 +1,7 @@
1
1
  import path from 'node:path';
2
2
  import { AmxError, moduleError } from '../diagnostics/errors';
3
3
  import { parseDocumentText } from '../parser/parseDocument';
4
- import { checkDocument } from '../typechecker/checkDocument';
4
+ import { checkDocumentWithRuntimePlan } from '../typechecker/checkDocument';
5
5
  import { normalizeParserLineSeparators } from './source';
6
6
  function statementsOf(document) {
7
7
  const statements = [];
@@ -147,7 +147,7 @@ export function prepareGraph(entryModuleId, modules) {
147
147
  }
148
148
  }
149
149
  const imported = importedContext(record.input, record.statements, dependencies);
150
- const check = checkDocument(record.document, record.input.sourcePath, {
150
+ const checked = checkDocumentWithRuntimePlan(record.document, record.input.sourcePath, {
151
151
  ...imported,
152
152
  baseUnits: sharedBaseUnits,
153
153
  moduleIdentity: record.input.outputPath,
@@ -159,7 +159,8 @@ export function prepareGraph(entryModuleId, modules) {
159
159
  statements: record.statements,
160
160
  imports: dependencies,
161
161
  importSpecifiers: specifiers,
162
- check
162
+ check: checked.result,
163
+ typescriptBlocks: checked.typescriptBlocks
163
164
  };
164
165
  prepared.set(moduleId, module);
165
166
  states.set(moduleId, 'visited');
@@ -1,6 +1,8 @@
1
1
  import { isMeasurement, measurement, measurementDisplayValue, measurementPhysicalValue } from './runtime/measurement';
2
2
  import { AmxError, staticError } from './diagnostics/errors';
3
3
  import { evaluateBinaryValues, evaluateBuiltinValues, evaluateIterableValue, evaluateListAddition, evaluateListItem, evaluateListRemoval, evaluateRangeValues, evaluateUnaryValue } from './runtime/evaluateExpression';
4
+ import { isValidDateTime } from './runtime/dateTime';
5
+ import { createComplex, isComplex } from './runtime/complex';
4
6
  export class AMXRuntimeError extends Error {
5
7
  diagnostic;
6
8
  code;
@@ -44,6 +46,12 @@ export class AMXInputError extends TypeError {
44
46
  export function amxBinary(operator, left, right, context) {
45
47
  return withRuntimeErrorContext(() => evaluateBinaryValues(operator, left, right, sourceLocation(context), context?.file), context);
46
48
  }
49
+ export function amxComplex(real, imaginary, context) {
50
+ return withRuntimeErrorContext(() => createComplex(real, imaginary, sourceLocation(context), context?.file), context);
51
+ }
52
+ export function amxIsComplex(value) {
53
+ return isComplex(value);
54
+ }
47
55
  export function amxUnary(operator, value, context) {
48
56
  return withRuntimeErrorContext(() => evaluateUnaryValue(operator, value, sourceLocation(context), context?.file), context);
49
57
  }
@@ -61,7 +69,8 @@ export function amxFormatValue(value, context) {
61
69
  return withRuntimeErrorContext(() => staticError('AMX3007', 'Only String, Number, Boolean, measurement, and null values can be interpolated', sourceLocation(context), context?.file), context);
62
70
  }
63
71
  export function amxBuiltin(name, args, context) {
64
- return withRuntimeErrorContext(() => evaluateBuiltinValues(name, args, sourceLocation(context), context?.file, createDimensionRegistry(context?.unitDescriptors)), context);
72
+ const argumentContexts = context?.argumentContexts ?? [];
73
+ return withRuntimeErrorContext(() => evaluateBuiltinValues(name, args, sourceLocation(context), context?.file, createDimensionRegistry(context?.unitDescriptors), argumentContexts.map(sourceLocation)), context);
65
74
  }
66
75
  export function amxIsType(value, descriptor) {
67
76
  return matchesInputDescriptor(value, descriptor);
@@ -292,6 +301,8 @@ function throwViewInputError(path, expected, actual) {
292
301
  function cloneViewData(value, path, ancestors = new Set()) {
293
302
  if (value === null || typeof value === 'string' || typeof value === 'boolean')
294
303
  return value;
304
+ if (isComplex(value))
305
+ return value;
295
306
  if (typeof value === 'number') {
296
307
  if (!Number.isFinite(value))
297
308
  throwViewInputError(path, 'finite JSON-like value', describeInput(value));
@@ -440,7 +451,8 @@ function matchesInputDescriptor(value, descriptor, ancestors = new Set()) {
440
451
  case 'number': return typeof value === 'number';
441
452
  case 'string': return typeof value === 'string';
442
453
  case 'boolean': return typeof value === 'boolean';
443
- case 'dateTime': return typeof value === 'string' && validAMXDateTime(value);
454
+ case 'dateTime': return isValidDateTime(value);
455
+ case 'complex': return isComplex(value);
444
456
  case 'enum':
445
457
  return (typeof value === 'string' || typeof value === 'number')
446
458
  && descriptor.members.some(member => typeof member === typeof value && member === value);
@@ -500,10 +512,14 @@ function validateInputValue(value, descriptor, inputPath, context, ancestors = n
500
512
  case 'string': return withContext(() => requireAMXString(value, inputPath));
501
513
  case 'boolean': return withContext(() => requireAMXBoolean(value, inputPath));
502
514
  case 'dateTime':
503
- if (typeof value !== 'string' || !validAMXDateTime(value)) {
515
+ if (!isValidDateTime(value)) {
504
516
  throw new AMXInputError(inputPath, 'RFC 3339 DateTime', describeInput(value), context);
505
517
  }
506
518
  return value;
519
+ case 'complex':
520
+ if (!isComplex(value))
521
+ throw new AMXInputError(inputPath, 'finite Complex', describeInput(value), context);
522
+ return value;
507
523
  case 'enum':
508
524
  return withContext(() => requireAMXEnum(value, descriptor.enumName, descriptor.members, inputPath));
509
525
  case 'measurement': {
@@ -591,6 +607,7 @@ function descriptorName(descriptor) {
591
607
  case 'string': return 'String';
592
608
  case 'boolean': return 'Boolean';
593
609
  case 'dateTime': return 'RFC 3339 DateTime';
610
+ case 'complex': return 'finite Complex';
594
611
  case 'enum': return `member of enum '${descriptor.enumName}'`;
595
612
  case 'measurement': return `Measurement<${descriptor.dimensionName}>`;
596
613
  case 'nullable': return `${descriptorName(descriptor.value)} or null`;
@@ -601,17 +618,6 @@ function descriptorName(descriptor) {
601
618
  function appendInputPath(inputPath, segment) {
602
619
  return `${inputPath}/${escapePointer(segment)}`;
603
620
  }
604
- function validAMXDateTime(value) {
605
- const parts = value.match(/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.\d{1,9})?(Z|[+-]\d{2}:\d{2})$/);
606
- if (!parts)
607
- return false;
608
- const [, year, month, day, hour, minute, second, offset] = parts;
609
- const date = new Date(0);
610
- date.setUTCFullYear(+year, +month - 1, +day);
611
- return date.getUTCFullYear() === +year && date.getUTCMonth() === +month - 1 && date.getUTCDate() === +day
612
- && +hour <= 23 && +minute <= 59 && +second <= 59
613
- && (offset === 'Z' || (+offset.slice(1, 3) <= 23 && +offset.slice(4) <= 59));
614
- }
615
621
  function copyArrayTree(value) {
616
622
  return Array.isArray(value) ? value.map(copyArrayTree) : value;
617
623
  }