@nova-energy/openamx 0.11.0 → 0.14.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.
@@ -1,8 +1,9 @@
1
1
  import { inputError, staticError, throwInputErrors, throwInvalidLoopIterable, throwInvalidRangeBounds, throwInvalidReturnContext, throwListOperationError, throwMeasurementDomainError } from '../diagnostics/errors';
2
2
  import { Environment } from './environment';
3
- import { evaluateStandardLibraryCall } from './standardLibrary';
3
+ import { evaluateStandardLibraryCall, isMathematicalFunction } from './standardLibrary';
4
4
  import { fieldRegistry } from '../typechecker/declarationRegistry';
5
5
  import { canonicalUnit, composeUnits, isMeasurement, measurement, powerUnit, sqrtMeasurement, unitFromMetadata } from './measurement';
6
+ import { createDiagramModel } from './diagramModel';
6
7
  function validateRuntimeValue(value, expected, env, source, file, valuePath) {
7
8
  const diagnostics = [];
8
9
  const report = (message, target, actual, dataPath, fieldSource) => {
@@ -79,13 +80,13 @@ function validateRuntimeValue(value, expected, env, source, file, valuePath) {
79
80
  }
80
81
  const record = actual;
81
82
  const fieldNames = new Set(declaration.fields.map(field => field.name));
82
- const recordRegistry = fieldRegistry(declaration, env.dimensionRegistry);
83
83
  for (const field of declaration.fields) {
84
+ const fieldScope = fieldRegistry(field, env.dimensionRegistry);
84
85
  if (!Object.prototype.hasOwnProperty.call(record, field.name)) {
85
- report(`Missing computed field '${field.name}'`, checkedType(field.annotation, recordRegistry), 'missing', `${dataPath}.${field.name}`, field.source);
86
+ report(`Missing computed field '${field.name}'`, checkedType(field.annotation, fieldScope), 'missing', `${dataPath}.${field.name}`, field.source);
86
87
  }
87
88
  else {
88
- visit(record[field.name], checkedType(field.annotation, recordRegistry), `${dataPath}.${field.name}`, field.source);
89
+ visit(record[field.name], checkedType(field.annotation, fieldScope), `${dataPath}.${field.name}`, field.source);
89
90
  }
90
91
  }
91
92
  for (const name of Object.keys(record).filter(name => !fieldNames.has(name)).sort()) {
@@ -96,6 +97,18 @@ function validateRuntimeValue(value, expected, env, source, file, valuePath) {
96
97
  if (diagnostics.length)
97
98
  throwInputErrors(diagnostics);
98
99
  }
100
+ function evaluateFieldDefault(field, env, file) {
101
+ if (!field.defaultExpression)
102
+ return null;
103
+ const currentRegistry = env.dimensionRegistry;
104
+ env.dimensionRegistry = fieldRegistry(field, currentRegistry);
105
+ try {
106
+ return evaluateExpression(field.defaultExpression, env, file);
107
+ }
108
+ finally {
109
+ env.dimensionRegistry = currentRegistry;
110
+ }
111
+ }
99
112
  function checkedType(reference, scope) {
100
113
  const registry = scope instanceof Environment ? scope.dimensionRegistry : scope;
101
114
  if (reference.type === 'namedType') {
@@ -141,6 +154,46 @@ function validDateTime(value) {
141
154
  && +hour <= 23 && +minute <= 59 && +second <= 59
142
155
  && (offset === 'Z' || (+offset.slice(1, 3) <= 23 && +offset.slice(4) <= 59));
143
156
  }
157
+ function matchesRuntimeType(value, target, env, file, registry = env.dimensionRegistry) {
158
+ if (target.type === 'nullableType') {
159
+ return value === null || matchesRuntimeType(value, target.element, env, file, registry);
160
+ }
161
+ if (target.type === 'listType') {
162
+ return Array.isArray(value) && value.every(item => matchesRuntimeType(item, target.element, env, file, registry));
163
+ }
164
+ const name = target.name;
165
+ const dimension = registry?.dimensions.get(name);
166
+ if (dimension)
167
+ return isMeasurement(value) && sameMeasurementVector(value, dimension.vector);
168
+ if (name === 'Number')
169
+ return typeof value === 'number';
170
+ if (name === 'String')
171
+ return typeof value === 'string';
172
+ if (name === 'Boolean')
173
+ return typeof value === 'boolean';
174
+ if (name === 'DateTime')
175
+ return typeof value === 'string' && validDateTime(value);
176
+ const enumeration = env.enumDeclarations.get(name);
177
+ if (enumeration) {
178
+ if (typeof value !== 'number' && typeof value !== 'string')
179
+ return false;
180
+ if (!enumeration.resolvedValues)
181
+ throw new Error(`Enum '${name}' has not been resolved`);
182
+ return enumeration.resolvedValues.includes(value);
183
+ }
184
+ const declaration = env.recordTypes.get(name);
185
+ if (declaration) {
186
+ if (typeof value !== 'object' || value === null || Array.isArray(value) || isMeasurement(value))
187
+ return false;
188
+ const record = value;
189
+ return declaration.fields.every(field => {
190
+ if (!Object.prototype.hasOwnProperty.call(record, field.name))
191
+ return field.optional;
192
+ return matchesRuntimeType(record[field.name], field.annotation, env, file, fieldRegistry(field, registry));
193
+ });
194
+ }
195
+ return staticError('AMX3001', `Unknown type '${name}'`, target.source, file);
196
+ }
144
197
  /** Evaluate V0.2 expressions, including ranges and expression-form loops. */
145
198
  export function evaluateExpression(node, env, file) {
146
199
  switch (node.type) {
@@ -154,13 +207,19 @@ export function evaluateExpression(node, env, file) {
154
207
  const record = {};
155
208
  for (const field of declaration.fields) {
156
209
  record[field.name] = supplied.has(field.name) ? supplied.get(field.name)
157
- : field.defaultExpression ? evaluateExpression(field.defaultExpression, env, file) : null;
210
+ : field.defaultExpression ? evaluateFieldDefault(field, env, file) : null;
158
211
  }
159
212
  validateRuntimeValue(record, { kind: 'named', name: node.name }, env, node.source, file, `record ${node.name}`);
160
213
  return record;
161
214
  }
162
- case 'fieldAccess':
215
+ case 'fieldAccess': {
216
+ if (node.receiver.type === 'identifier') {
217
+ const enumeration = env.enumValues.get(node.receiver.name);
218
+ if (enumeration)
219
+ return enumeration[node.field];
220
+ }
163
221
  return evaluateExpression(node.receiver, env, file)[node.field];
222
+ }
164
223
  case 'listAccess':
165
224
  return evalListAccess(node, env, file);
166
225
  case 'numberLiteral':
@@ -185,6 +244,10 @@ export function evaluateExpression(node, env, file) {
185
244
  case 'booleanLiteral':
186
245
  return node.value;
187
246
  case 'identifier':
247
+ if (node.name === 'PI')
248
+ return Math.PI;
249
+ if (node.name === 'E')
250
+ return Math.E;
188
251
  // Pass source location for better diagnostics
189
252
  return env.get(node.name, node.source, file);
190
253
  case 'measurementAttachment': {
@@ -215,10 +278,14 @@ export function evaluateExpression(node, env, file) {
215
278
  }
216
279
  case 'binaryExpression':
217
280
  return evalBinary(node, env, file);
281
+ case 'typeTestExpression':
282
+ return matchesRuntimeType(evaluateExpression(node.value, env, file), node.target, env, file);
218
283
  case 'unaryExpression':
219
284
  return evalUnary(node, env, file);
220
285
  case 'conditionalExpression':
221
286
  return evalConditional(node, env, file);
287
+ case 'bracedIfExpression':
288
+ return evalBracedIfExpression(node, env, file);
222
289
  case 'listLiteral':
223
290
  return evalListLiteral(node, env, file);
224
291
  case 'functionCall':
@@ -385,6 +452,58 @@ function evalConditional(node, env, file) {
385
452
  ? evaluateExpression(node.consequent, env, file)
386
453
  : evaluateExpression(node.alternate, env, file);
387
454
  }
455
+ class ConditionalValueReturn {
456
+ value;
457
+ constructor(value) {
458
+ this.value = value;
459
+ }
460
+ }
461
+ class ForExpressionReturn {
462
+ value;
463
+ constructor(value) {
464
+ this.value = value;
465
+ }
466
+ }
467
+ const conditionalReturnDepth = new WeakMap();
468
+ const forExpressionDepth = new WeakMap();
469
+ function withDepth(depths, env, run) {
470
+ depths.set(env, (depths.get(env) ?? 0) + 1);
471
+ try {
472
+ return run();
473
+ }
474
+ finally {
475
+ const depth = depths.get(env) - 1;
476
+ if (depth)
477
+ depths.set(env, depth);
478
+ else
479
+ depths.delete(env);
480
+ }
481
+ }
482
+ function evaluateScopedStatements(statements, env, file) {
483
+ const existing = new Set(Object.keys(env.toObject()));
484
+ try {
485
+ evaluateStatements(statements, env, file);
486
+ }
487
+ finally {
488
+ for (const name of Object.keys(env.toObject())) {
489
+ if (!existing.has(name))
490
+ env.delete(name);
491
+ }
492
+ }
493
+ }
494
+ function evalBracedIfExpression(node, env, file) {
495
+ const branch = toBoolean(evaluateExpression(node.test, env, file)) ? node.consequent : node.alternate;
496
+ const closingSource = branch === node.consequent ? node.consequentSource : node.alternateSource;
497
+ try {
498
+ withDepth(conditionalReturnDepth, env, () => evaluateScopedStatements(branch, env, file));
499
+ }
500
+ catch (error) {
501
+ if (error instanceof ConditionalValueReturn)
502
+ return error.value;
503
+ throw error;
504
+ }
505
+ return staticError('AMX3021', 'Every possible path in an if expression must return a value', closingSource ?? node.source, file);
506
+ }
388
507
  function evalListLiteral(node, env, file) {
389
508
  return node.elements.map(el => evaluateExpression(el, env, file));
390
509
  }
@@ -402,6 +521,24 @@ function evalListAccess(node, env, file) {
402
521
  }
403
522
  return receiver[index - 1];
404
523
  }
524
+ function functionArgumentSource(expression, fallback) {
525
+ if (expression.type === 'binaryExpression') {
526
+ return functionArgumentSource(expression.left, fallback) ?? expression.operatorSource ?? expression.source ?? fallback;
527
+ }
528
+ if (expression.type === 'unaryExpression') {
529
+ const operandSource = functionArgumentSource(expression.argument, fallback);
530
+ if (operandSource) {
531
+ return {
532
+ line: operandSource.line,
533
+ column: Math.max(1, operandSource.column - (expression.operator === 'not' ? 3 : 1))
534
+ };
535
+ }
536
+ }
537
+ if (expression.type === 'measurementAttachment' || expression.type === 'measurementConversion') {
538
+ return functionArgumentSource(expression.value, fallback) ?? expression.source ?? fallback;
539
+ }
540
+ return expression.source ?? fallback;
541
+ }
405
542
  function evalFunctionCall(node, env, file) {
406
543
  const args = node.arguments.map(a => evaluateExpression(a, env, file));
407
544
  const userFunction = env.functions.get(node.callee);
@@ -460,6 +597,12 @@ function evalFunctionCall(node, env, file) {
460
597
  }
461
598
  if (isMeasurement(args[0])) {
462
599
  const value = args[0];
600
+ if (isMathematicalFunction(node.callee)) {
601
+ if (Object.keys(value.unit.vector).length !== 0) {
602
+ return staticError('AMX3007', `'${node.callee}' requires a Number or dimensionless Measurement`, node.arguments[0]?.source ?? node.source, file);
603
+ }
604
+ return evaluateStandardLibraryCall(node.callee, [value.value * value.unit.scale], node.source, file);
605
+ }
463
606
  switch (node.callee) {
464
607
  case 'abs':
465
608
  return measurement(Math.abs(value.value), value.unit);
@@ -509,7 +652,7 @@ function evalFunctionCall(node, env, file) {
509
652
  }
510
653
  }
511
654
  }
512
- return evaluateStandardLibraryCall(node.callee, args, node.source, file);
655
+ return evaluateStandardLibraryCall(node.callee, args, node.source, file, node.arguments.map(argument => functionArgumentSource(argument, node.source)));
513
656
  }
514
657
  function toNumber(v, nodeForError) {
515
658
  if (typeof v === 'number')
@@ -726,12 +869,31 @@ function evaluateStatement(statement, env, file) {
726
869
  case 'chartDeclaration':
727
870
  env.viewDefinitions.set(statement.name, statement);
728
871
  return;
872
+ case 'diagramDeclaration':
873
+ env.diagramEmissions.push({
874
+ model: createDiagramModel(statement, env, file, env.currentDocumentNodeIndex, env.currentStatementIndex)
875
+ });
876
+ return;
729
877
  case 'showStatement':
730
878
  env.viewEmissions.push(snapshotView(statement.name, env, file, statement.source));
731
879
  return;
732
880
  case 'typeDeclaration':
733
881
  env.recordTypes.set(statement.name, statement);
734
882
  return;
883
+ case 'enumDeclaration': {
884
+ const values = statement.resolvedValues ?? statement.members.map((member, index) => {
885
+ if (!member.value)
886
+ return index + 1;
887
+ if (member.value.type === 'numberLiteral' || member.value.type === 'stringLiteral')
888
+ return member.value.value;
889
+ return staticError('AMX3020', 'Only constant values can be assigned to enum members', member.valueSource ?? member.value.source, file);
890
+ });
891
+ const enumeration = {};
892
+ statement.members.forEach((member, index) => { enumeration[member.name] = values[index]; });
893
+ env.enumDeclarations.set(statement.name, statement);
894
+ env.enumValues.set(statement.name, enumeration);
895
+ return;
896
+ }
735
897
  case 'functionDeclaration':
736
898
  env.functions.set(statement.name, statement);
737
899
  return;
@@ -775,10 +937,24 @@ function evaluateStatement(statement, env, file) {
775
937
  case 'forStatement':
776
938
  evalForStatement(statement, env, file);
777
939
  return;
940
+ case 'bracedIfStatement':
941
+ evalBracedIfStatement(statement, env, file);
942
+ return;
778
943
  case 'returnStatement':
944
+ if (conditionalReturnDepth.has(env)) {
945
+ throw new ConditionalValueReturn(evaluateExpression(statement.expression, env, file));
946
+ }
947
+ if (forExpressionDepth.has(env)) {
948
+ throw new ForExpressionReturn(evaluateExpression(statement.expression, env, file));
949
+ }
779
950
  throwInvalidReturnContext(statement.source, file);
780
951
  }
781
952
  }
953
+ function evalBracedIfStatement(node, env, file) {
954
+ const branch = toBoolean(evaluateExpression(node.test, env, file)) ? node.consequent : node.alternate;
955
+ if (branch)
956
+ evaluateScopedStatements(branch, env, file);
957
+ }
782
958
  function mutationTarget(name, env, source, file) {
783
959
  const target = env.get(name, source, file);
784
960
  if (!Array.isArray(target))
@@ -852,16 +1028,24 @@ function evalForStatement(node, env, file) {
852
1028
  function evalForExpression(node, env, file) {
853
1029
  const values = evaluateLoopIterable(node.iterable, env, file);
854
1030
  const results = [];
855
- withLoopBinding(node.variable, values, env, () => {
1031
+ withDepth(forExpressionDepth, env, () => withLoopBinding(node.variable, values, env, () => {
856
1032
  for (const statement of node.body) {
857
1033
  if (statement.type === 'returnStatement') {
858
1034
  results.push(evaluateExpression(statement.expression, env, file));
859
1035
  }
860
1036
  else {
861
- evaluateStatement(statement, env, file);
1037
+ try {
1038
+ evaluateStatement(statement, env, file);
1039
+ }
1040
+ catch (error) {
1041
+ if (error instanceof ForExpressionReturn)
1042
+ results.push(error.value);
1043
+ else
1044
+ throw error;
1045
+ }
862
1046
  }
863
1047
  }
864
- });
1048
+ }));
865
1049
  return results;
866
1050
  }
867
1051
  function evaluateLoopIterable(node, env, file) {
@@ -20,20 +20,22 @@ export function describeInputSchema(declaration, types, registry) {
20
20
  && declaration.annotation.element?.type === 'namedType'
21
21
  ? types.get(declaration.annotation.element.name)
22
22
  : undefined;
23
- const recordRegistry = recordType ? fieldRegistry(recordType, registry) : undefined;
24
- const csvCompatible = !!recordType && recordType.fields.every(field => isCsvScalar(field.annotation, recordRegistry));
23
+ const csvCompatible = !!recordType && recordType.fields.every(field => isCsvScalar(field.annotation, fieldRegistry(field, registry)));
25
24
  return {
26
25
  name: declaration.name,
27
26
  type: typeName(declaration.annotation),
28
27
  acceptedFormats: csvCompatible ? ['json', 'csv'] : ['json'],
29
28
  ...(registry ? measurementSchema(declaration.annotation, registry) : {}),
30
- ...(recordType ? { fields: recordType.fields.map(field => ({
31
- name: field.name,
32
- type: typeName(field.annotation),
33
- optional: field.optional,
34
- hasDefault: field.defaultExpression !== undefined,
35
- ...(recordRegistry ? measurementSchema(field.annotation, recordRegistry) : {})
36
- })) } : {})
29
+ ...(recordType ? { fields: recordType.fields.map(field => {
30
+ const fieldScope = fieldRegistry(field, registry);
31
+ return {
32
+ name: field.name,
33
+ type: typeName(field.annotation),
34
+ optional: field.optional,
35
+ hasDefault: field.defaultExpression !== undefined,
36
+ ...(fieldScope ? measurementSchema(field.annotation, fieldScope) : {})
37
+ };
38
+ }) } : {})
37
39
  };
38
40
  }
39
41
  export function validateInputText(text, format, declaration, types, mode = 'aggregate', context = {}, registry) {
@@ -215,15 +217,15 @@ function convertJson(value, annotation, pointer, declarationSource, types, envir
215
217
  report(shapeDiagnostic(`Unknown field '${key}'`, 'declared record field', describe(object[key]), propertyPointer, context, declarationSource, fieldSource));
216
218
  }
217
219
  const materialized = {};
218
- const recordRegistry = fieldRegistry(declaration, registry);
219
220
  for (const field of declaration.fields) {
221
+ const fieldScope = fieldRegistry(field, registry);
220
222
  const propertyPointer = `${pointer}/${escapePointer(field.name)}`;
221
223
  if (Object.prototype.hasOwnProperty.call(object, field.name)) {
222
- materialized[field.name] = convertJson(object[field.name], field.annotation, propertyPointer, declarationSource, types, environment, report, context, field.source, recordRegistry, internalDefault);
224
+ materialized[field.name] = convertJson(object[field.name], field.annotation, propertyPointer, declarationSource, types, environment, report, context, field.source, fieldScope, internalDefault);
223
225
  }
224
226
  else if (field.defaultExpression) {
225
- const value = evaluateExpression(field.defaultExpression, defaultsEnvironment(environment, recordRegistry), context.file);
226
- materialized[field.name] = convertJson(value, field.annotation, propertyPointer, declarationSource, types, environment, report, context, field.source, recordRegistry, true);
227
+ const value = evaluateExpression(field.defaultExpression, defaultsEnvironment(environment, fieldScope), context.file);
228
+ materialized[field.name] = convertJson(value, field.annotation, propertyPointer, declarationSource, types, environment, report, context, field.source, fieldScope, true);
227
229
  }
228
230
  else if (field.optional) {
229
231
  materialized[field.name] = null;
@@ -240,8 +242,7 @@ function convertCsv(text, annotation, declarationSource, types, environment, rep
240
242
  return [];
241
243
  }
242
244
  const recordType = types.get(annotation.element.name);
243
- const recordRegistry = fieldRegistry(recordType, registry);
244
- const scalarFields = recordType.fields.every(field => isCsvScalar(field.annotation, recordRegistry));
245
+ const scalarFields = recordType.fields.every(field => isCsvScalar(field.annotation, fieldRegistry(field, registry)));
245
246
  if (!scalarFields) {
246
247
  report(shapeDiagnostic('CSV records may contain only scalar fields', 'scalar-field RecordType[]', recordType.name, '', context, declarationSource));
247
248
  return [];
@@ -291,8 +292,9 @@ function convertCsv(text, annotation, declarationSource, types, environment, rep
291
292
  const propertyPath = `record[${recordNumber}].${field.name}`;
292
293
  if (column < 0) {
293
294
  if (field.defaultExpression) {
294
- const value = evaluateExpression(field.defaultExpression, defaultsEnvironment(environment, recordRegistry), context.file);
295
- materialized[field.name] = convertJson(value, field.annotation, propertyPath, context.declarationSource, types, environment, report, context, field.source, recordRegistry, true);
295
+ const fieldScope = fieldRegistry(field, registry);
296
+ const value = evaluateExpression(field.defaultExpression, defaultsEnvironment(environment, fieldScope), context.file);
297
+ materialized[field.name] = convertJson(value, field.annotation, propertyPath, context.declarationSource, types, environment, report, context, field.source, fieldScope, true);
296
298
  }
297
299
  else if (field.optional)
298
300
  materialized[field.name] = null;
@@ -301,7 +303,7 @@ function convertCsv(text, annotation, declarationSource, types, environment, rep
301
303
  const cell = row[column];
302
304
  if (!cell)
303
305
  continue;
304
- materialized[field.name] = convertCsvCell(cell, field.annotation, propertyPath, recordNumber, column + 1, field.source, report, context, recordRegistry);
306
+ materialized[field.name] = convertCsvCell(cell, field.annotation, propertyPath, recordNumber, column + 1, field.source, report, context, fieldRegistry(field, registry));
305
307
  }
306
308
  result.push(materialized);
307
309
  }
@@ -15,6 +15,45 @@ function flattenStatements(doc) {
15
15
  }
16
16
  return statements;
17
17
  }
18
+ function collectDiagramDeclarations(statements, output) {
19
+ for (const statement of statements) {
20
+ if (statement.type === 'diagramDeclaration')
21
+ output.push(statement);
22
+ else if (statement.type === 'forStatement')
23
+ collectDiagramDeclarations(statement.body, output);
24
+ else if (statement.type === 'bracedIfStatement') {
25
+ collectDiagramDeclarations(statement.consequent, output);
26
+ if (statement.alternate)
27
+ collectDiagramDeclarations(statement.alternate, output);
28
+ }
29
+ }
30
+ }
31
+ function reportDiagramDeclarations(doc) {
32
+ const declarations = [];
33
+ for (const node of doc.nodes) {
34
+ if (node.type === 'executableCodeBlock')
35
+ collectDiagramDeclarations(node.statements, declarations);
36
+ }
37
+ return declarations;
38
+ }
39
+ function validateReportDiagramCaps(records) {
40
+ let diagramCount = 0;
41
+ let elementCount = 0;
42
+ for (const record of records) {
43
+ for (const declaration of reportDiagramDeclarations(record.doc)) {
44
+ diagramCount++;
45
+ if (diagramCount > 16) {
46
+ staticError('AMXD012', 'A single report can have up to 16 diagrams maximum.', declaration.source, record.canonicalPath);
47
+ }
48
+ for (const element of declaration.elements) {
49
+ elementCount++;
50
+ if (elementCount > 512) {
51
+ staticError('AMXD013', 'A single report can have up to 512 elements maximum.', element.source, record.canonicalPath);
52
+ }
53
+ }
54
+ }
55
+ }
56
+ }
18
57
  function validateImportPathSyntax(importNode, file) {
19
58
  const importPath = importNode.path;
20
59
  if (!(importPath.startsWith('./') || importPath.startsWith('../'))) {
@@ -96,7 +135,7 @@ export async function loadEntryModule(entryPath, options = {}) {
96
135
  const statements = flattenStatements(doc);
97
136
  const localNames = new Set();
98
137
  for (const statement of statements) {
99
- if (statement.type === 'typeDeclaration' || statement.type === 'functionDeclaration' || statement.type === 'variableDeclaration' || statement.type === 'inputDeclaration'
138
+ if (statement.type === 'typeDeclaration' || statement.type === 'enumDeclaration' || statement.type === 'functionDeclaration' || statement.type === 'variableDeclaration' || statement.type === 'inputDeclaration'
100
139
  || statement.type === 'tableDeclaration' || statement.type === 'chartDeclaration'
101
140
  || statement.type === 'dimensionDeclaration' || statement.type === 'unitDeclaration') {
102
141
  localNames.add(statement.name);
@@ -121,6 +160,8 @@ export async function loadEntryModule(entryPath, options = {}) {
121
160
  const imports = statements.filter((s) => s.type === 'importDeclaration');
122
161
  const localDimensionUnitNames = new Set(statements.flatMap(statement => statement.type === 'dimensionDeclaration' || statement.type === 'unitDeclaration' ? [statement.name] : []));
123
162
  const importedTypes = new Map();
163
+ const importedEnums = new Map();
164
+ const importedEnumSources = new Map();
124
165
  const importedFunctions = new Map();
125
166
  const importedBindings = new Map();
126
167
  const importedBindingSources = new Map();
@@ -157,6 +198,10 @@ export async function loadEntryModule(entryPath, options = {}) {
157
198
  if (dependency.checkResult.exportedTypes.has(importedName.name)) {
158
199
  importedTypes.set(importedName.name, dependency.checkResult.exportedTypes.get(importedName.name));
159
200
  }
201
+ else if (dependency.checkResult.exportedEnums.has(importedName.name)) {
202
+ importedEnums.set(importedName.name, dependency.checkResult.exportedEnums.get(importedName.name));
203
+ importedEnumSources.set(importedName.name, dependency.canonicalPath);
204
+ }
160
205
  else if (dependency.checkResult.exportedFunctions.has(importedName.name)) {
161
206
  importedFunctions.set(importedName.name, dependency.checkResult.exportedFunctions.get(importedName.name));
162
207
  }
@@ -179,6 +224,7 @@ export async function loadEntryModule(entryPath, options = {}) {
179
224
  }
180
225
  const checkResult = checkDocument(doc, canonicalPath, {
181
226
  types: importedTypes,
227
+ enums: importedEnums,
182
228
  functions: importedFunctions,
183
229
  bindings: importedBindings,
184
230
  dimensions: importedDimensions,
@@ -188,12 +234,13 @@ export async function loadEntryModule(entryPath, options = {}) {
188
234
  isEntryModule: canonicalPath === realEntry
189
235
  });
190
236
  visiting.pop();
191
- const record = { canonicalPath, doc, checkResult, importedTypes, importedFunctions, importedBindings, importedBindingSources, importedDimensions, importedUnits };
237
+ const record = { canonicalPath, doc, checkResult, importedTypes, importedEnums, importedEnumSources, importedFunctions, importedBindings, importedBindingSources, importedDimensions, importedUnits };
192
238
  resolved.set(canonicalPath, record);
193
239
  evaluationOrder.push(canonicalPath);
194
240
  return record;
195
241
  }
196
242
  await visit(realEntry, undefined);
243
+ validateReportDiagramCaps(evaluationOrder.map(canonicalPath => resolved.get(canonicalPath)));
197
244
  const entryRecord = resolved.get(realEntry);
198
245
  const registry = {
199
246
  dimensions: entryRecord.checkResult.dimensions,
@@ -227,6 +274,7 @@ export async function loadEntryModule(entryPath, options = {}) {
227
274
  env: new Environment(entryTypes, new Map(), registry),
228
275
  outputs,
229
276
  viewEmissions: [],
277
+ diagramEmissions: [],
230
278
  registry,
231
279
  inputInspection: {
232
280
  schema: describeInputSchema(declaration, entryTypes, registry),
@@ -237,7 +285,15 @@ export async function loadEntryModule(entryPath, options = {}) {
237
285
  };
238
286
  }
239
287
  if (options.outputInspection) {
240
- return { doc: entryRecord.doc, env: new Environment(entryTypes, new Map(), registry), outputs, viewEmissions: [], outputSchemas: outputSchemas ?? [], registry };
288
+ return {
289
+ doc: entryRecord.doc,
290
+ env: new Environment(entryTypes, new Map(), registry),
291
+ outputs,
292
+ viewEmissions: [],
293
+ diagramEmissions: [],
294
+ outputSchemas: outputSchemas ?? [],
295
+ registry
296
+ };
241
297
  }
242
298
  const inputValues = await loadInputValues(inputDeclarations, entryTypes, options.inputMappings, options.validation, entryPath, registry);
243
299
  const evaluatedEnvironments = new Map();
@@ -251,6 +307,13 @@ export async function loadEntryModule(entryPath, options = {}) {
251
307
  env.validationMode = options.validation ?? 'aggregate';
252
308
  for (const [name, typeDeclaration] of record.importedTypes)
253
309
  env.recordTypes.set(name, typeDeclaration);
310
+ for (const [name, enumDeclaration] of record.importedEnums) {
311
+ const dependency = evaluatedEnvironments.get(record.importedEnumSources.get(name));
312
+ if (!dependency)
313
+ moduleError('AMX5002', `Imported enum '${name}' was not materialized`, enumDeclaration.source, canonicalPath);
314
+ env.enumDeclarations.set(name, enumDeclaration);
315
+ env.enumValues.set(name, dependency.enumValues.get(name));
316
+ }
254
317
  for (const [name, functionDeclaration] of record.importedFunctions)
255
318
  env.functions.set(name, functionDeclaration);
256
319
  for (const [name, bindingType] of record.checkResult.bindingTypes)
@@ -275,5 +338,14 @@ export async function loadEntryModule(entryPath, options = {}) {
275
338
  evaluatedEnvironments.set(canonicalPath, env);
276
339
  }
277
340
  const entryEnv = evaluatedEnvironments.get(realEntry);
278
- return { doc: resolved.get(realEntry).doc, env: entryEnv, outputs, viewEmissions: entryEnv.viewEmissions, registry };
341
+ const diagramEmissions = Object.freeze(evaluationOrder.flatMap(canonicalPath => evaluatedEnvironments.get(canonicalPath).diagramEmissions));
342
+ entryEnv.diagramEmissions.splice(0, entryEnv.diagramEmissions.length, ...diagramEmissions);
343
+ return {
344
+ doc: resolved.get(realEntry).doc,
345
+ env: entryEnv,
346
+ outputs,
347
+ viewEmissions: entryEnv.viewEmissions,
348
+ diagramEmissions,
349
+ registry
350
+ };
279
351
  }
@@ -30,13 +30,16 @@ function supportsJson(type, recordTypes, registry, visiting = new Set()) {
30
30
  if (!declaration || visiting.has(type.name))
31
31
  return false;
32
32
  const next = new Set(visiting).add(type.name);
33
- return declaration.fields.every(field => supportsJson(checkedType(field.annotation, fieldRegistry(declaration, registry)), recordTypes, fieldRegistry(declaration, registry), next));
33
+ return declaration.fields.every(field => {
34
+ const fieldScope = fieldRegistry(field, registry);
35
+ return supportsJson(checkedType(field.annotation, fieldScope), recordTypes, fieldScope, next);
36
+ });
34
37
  }
35
38
  function supportsCsv(type, recordTypes, registry) {
36
39
  if (type.kind !== 'list' || type.element.kind !== 'named')
37
40
  return false;
38
41
  const declaration = recordTypes.get(type.element.name);
39
- return !!declaration && declaration.fields.every(field => isCsvScalar(checkedType(field.annotation, fieldRegistry(declaration, registry))));
42
+ return !!declaration && declaration.fields.every(field => isCsvScalar(checkedType(field.annotation, fieldRegistry(field, registry))));
40
43
  }
41
44
  export function describeOutputSchemas(exportedBindings, recordTypes, registry) {
42
45
  return [...exportedBindings].flatMap(([name, type]) => {
@@ -63,9 +66,10 @@ function assertJsonShape(type, recordTypes, outputName, registry) {
63
66
  const declaration = recordTypes.get(type.name);
64
67
  if (!declaration)
65
68
  outputError('AMX6001', `Output '${outputName}' uses unknown record type '${type.name}'`);
66
- const recordRegistry = fieldRegistry(declaration, registry);
67
- for (const field of declaration.fields)
68
- assertJsonShape(checkedType(field.annotation, recordRegistry), recordTypes, outputName, recordRegistry);
69
+ for (const field of declaration.fields) {
70
+ const fieldScope = fieldRegistry(field, registry);
71
+ assertJsonShape(checkedType(field.annotation, fieldScope), recordTypes, outputName, fieldScope);
72
+ }
69
73
  }
70
74
  function checkedType(reference, registry) {
71
75
  if (reference.type === 'namedType') {
@@ -82,10 +86,9 @@ function assertCsvShape(type, recordTypes, outputName, registry) {
82
86
  const declaration = recordTypes.get(type.element.name);
83
87
  if (!declaration)
84
88
  outputError('AMX6001', `CSV output '${outputName}' uses unknown record type '${type.element.name}'`);
85
- const recordRegistry = fieldRegistry(declaration, registry);
86
- const unsupported = declaration.fields.find(field => !isCsvScalar(checkedType(field.annotation, recordRegistry)));
89
+ const unsupported = declaration.fields.find(field => !isCsvScalar(checkedType(field.annotation, fieldRegistry(field, registry))));
87
90
  if (unsupported) {
88
- outputError('AMX6001', `CSV output '${outputName}' field '${unsupported.name}' must be a scalar or nullable scalar, not ${typeName(checkedType(unsupported.annotation, recordRegistry))}`);
91
+ outputError('AMX6001', `CSV output '${outputName}' field '${unsupported.name}' must be a scalar or nullable scalar, not ${typeName(checkedType(unsupported.annotation, fieldRegistry(unsupported, registry)))}`);
89
92
  }
90
93
  }
91
94
  export function prepareOutputs(mappings, exportedBindings, recordTypes, reservedDestination, registry) {
@@ -182,7 +185,8 @@ function jsonValue(value, type, output, recordTypes, registry) {
182
185
  for (const field of declaration.fields) {
183
186
  if (!Object.prototype.hasOwnProperty.call(record, field.name))
184
187
  return invalidValue(output, `record ${type.name} is missing field '${field.name}'`);
185
- ordered[field.name] = jsonValue(record[field.name], checkedType(field.annotation, fieldRegistry(declaration, registry)), output, recordTypes, fieldRegistry(declaration, registry));
188
+ const fieldScope = fieldRegistry(field, registry);
189
+ ordered[field.name] = jsonValue(record[field.name], checkedType(field.annotation, fieldScope), output, recordTypes, fieldScope);
186
190
  }
187
191
  return ordered;
188
192
  }
@@ -244,7 +248,7 @@ function csvContents(value, type, output, recordTypes, registry) {
244
248
  rows.push(fields.map(field => {
245
249
  if (!Object.prototype.hasOwnProperty.call(record, field.name))
246
250
  return invalidValue(output, `record ${index} is missing field '${field.name}'`);
247
- return csvCell(record[field.name], checkedType(field.annotation, fieldRegistry(declaration, registry)), output, registry);
251
+ return csvCell(record[field.name], checkedType(field.annotation, fieldRegistry(field, registry)), output, registry);
248
252
  }).join(','));
249
253
  }
250
254
  return `${rows.join('\n')}\n`;
@@ -274,8 +278,10 @@ function measurementExpectations(type, recordTypes, registry, path = '$', seen =
274
278
  if (!declaration)
275
279
  return [];
276
280
  const next = new Set(seen).add(type.name);
277
- const recordRegistry = fieldRegistry(declaration, registry) ?? registry;
278
- return declaration.fields.flatMap(field => measurementExpectations(checkedType(field.annotation, recordRegistry), recordTypes, recordRegistry, `${path}.${field.name}`, next) ?? []);
281
+ return declaration.fields.flatMap(field => {
282
+ const fieldScope = fieldRegistry(field, registry) ?? registry;
283
+ return measurementExpectations(checkedType(field.annotation, fieldScope), recordTypes, fieldScope, `${path}.${field.name}`, next) ?? [];
284
+ });
279
285
  }
280
286
  function formatDimensionVector(vector, registry) {
281
287
  return [...vector].sort(([left], [right]) => left.localeCompare(right)).map(([identity, exponent]) => {