@nova-energy/openamx 0.18.0 → 0.21.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.
@@ -370,15 +370,18 @@ function renderChart(emission, identity) {
370
370
  const zoomControls = browserModel.zoomable
371
371
  ? `<div class="openamx-chart-controls" role="group" aria-label="Chart zoom controls"><button type="button" data-zoom="out" aria-label="Zoom out">Zoom out</button><button type="button" data-zoom="in" aria-label="Zoom in">Zoom in</button><button type="button" data-zoom="reset">Reset zoom</button></div>`
372
372
  : '';
373
+ const tableRelation = model.showTable ? ` ${id}-table-caption` : '';
373
374
  const textRows = model.table.rows.map(row => `<tr>${row.values.map(value => `<td>${renderNarrativeText(formatAmxValue(value))}</td>`).join('')}</tr>`).join('');
375
+ const table = model.showTable
376
+ ? ` <table class="openamx-chart-data" id="${id}"><caption id="${id}-table-caption">${escapeHtml(model.table.caption)}</caption><thead><tr>${model.table.headings.map(value => `<th scope="col">${escapeHtml(value)}</th>`).join('')}</tr></thead><tbody>${textRows}</tbody></table>\n`
377
+ : '';
374
378
  const data = safeJson(browserModel);
375
379
  return `<figure class="openamx-view openamx-chart" id="${id}-figure" data-openamx-chart aria-labelledby="${titleId}" aria-describedby="${descriptionId} ${summaryId}">
376
380
  <figcaption><strong id="${titleId}">${escapeHtml(model.title)}</strong><span id="${descriptionId}">${escapeHtml(model.description)}</span></figcaption>
377
- <p id="${summaryId}" class="sr-only">${escapeHtml(model.accessibility.summary)}</p>
381
+ <p id="${summaryId}" class="sr-only">${escapeHtml(browserModel.accessibility.summary)}</p>
378
382
  ${seriesControls}${zoomControls}
379
- <div id="${id}-plot" class="openamx-chart-plot" role="img" aria-label="${escapeHtml(model.title)}" aria-describedby="${descriptionId} ${summaryId} ${id}-table-caption"></div>
380
- <table class="openamx-chart-data" id="${id}"><caption id="${id}-table-caption">${escapeHtml(model.table.caption)}</caption><thead><tr>${model.table.headings.map(value => `<th scope="col">${escapeHtml(value)}</th>`).join('')}</tr></thead><tbody>${textRows}</tbody></table>
381
- <script type="application/json" data-chart-model>${data}</script>
383
+ <div id="${id}-plot" class="openamx-chart-plot" role="img" aria-label="${escapeHtml(model.title)}" aria-describedby="${descriptionId} ${summaryId}${tableRelation}"></div>
384
+ ${table} <script type="application/json" data-chart-model>${data}</script>
382
385
  </figure>`;
383
386
  }
384
387
  function serializeChartModel(model) {
@@ -390,17 +393,31 @@ function serializeChartModel(model) {
390
393
  const zoom = [{ type: 'inside', xAxisIndex: 0, ...(model.kind === 'scatter' ? { yAxisIndex: 0 } : {}), filterMode: 'none', zoomOnMouseWheel: true, moveOnMouseMove: true, moveOnMouseWheel: true }];
391
394
  optionProperty(option, 'dataZoom', zoom);
392
395
  }
396
+ const needsRowLabels = model.kind === 'bar' || model.kind === 'column'
397
+ || model.kind === 'line' && isCategoryAxis(model.option.xAxis);
393
398
  return {
394
399
  kind: model.kind,
395
400
  title: model.title,
396
401
  description: model.description,
402
+ showTable: model.showTable,
397
403
  dimensions: model.dimensions,
398
404
  option,
399
405
  formatterPaths,
400
- table: model.table,
406
+ ...(model.showTable
407
+ ? { table: model.table, accessibility: model.accessibility }
408
+ : {
409
+ ...(needsRowLabels ? {
410
+ rowLabels: Object.fromEntries(model.table.rows.map(row => [row.id, String(row.values[0] ?? '')]))
411
+ } : {}),
412
+ accessibility: {
413
+ role: model.accessibility.role,
414
+ title: model.accessibility.title,
415
+ description: model.accessibility.description,
416
+ summary: `${model.table.rows.length} source rows; ${model.plottedPointCount} plotted points.${model.dateTimePresentation ? ' DateTime values are presented in UTC ISO 8601 format; source order is preserved.' : ''}`
417
+ }
418
+ }),
401
419
  series: model.series,
402
420
  axes: model.axes,
403
- accessibility: model.accessibility,
404
421
  plottedPointCount: model.plottedPointCount,
405
422
  ...(model.emptyState ? { emptyState: model.emptyState } : {}),
406
423
  ...(model.dateTimePresentation ? { dateTimePresentation: model.dateTimePresentation } : {}),
@@ -476,7 +493,7 @@ const charts=new Map();
476
493
  const escapeHtml=value=>String(value??'').replace(/[&<>"']/g,char=>({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[char]));
477
494
  const iso=value=>{const date=new Date(typeof value==='number'?value:Date.parse(value));return Number.isNaN(date.getTime())?'':date.toISOString()};
478
495
  const locate=(object,path)=>path.slice(2).split('.').reduce((current,key)=>current==null?undefined:current[/^\\d+$/.test(key)?Number(key):key],object);
479
- const rowLabel=(value,model)=>{const row=model.table.rows.find(item=>item.id===String(value));return row?String(row.values[0]??''):String(value??'')};
496
+ const rowLabel=(value,model)=>{const id=String(value);if(model.rowLabels&&Object.prototype.hasOwnProperty.call(model.rowLabels,id))return model.rowLabels[id];const row=model.table?.rows.find(item=>item.id===id);return row?String(row.values[0]??''):String(value??'')};
480
497
  const axisLabel=(value,model)=>model.dateTimePresentation?iso(value):rowLabel(value,model);
481
498
  const formatTooltip=(input,model)=>{const entries=(Array.isArray(input)?input:[input]).filter(item=>item&&typeof item==='object');return entries.map(entry=>{const series=model.series.find(item=>item.id===entry.seriesId||item.name===entry.seriesName);const values=Array.isArray(entry.value)?entry.value:[];if(model.kind==='scatter'){const x=values[0]??null,y=values[1]??null;const xUnit=model.axes.find(item=>item.role==='x')?.name,yUnit=model.axes.find(item=>item.role==='y')?.name;return '<div><strong>'+escapeHtml(entry.seriesName||'')+'</strong><br>x: '+escapeHtml(x)+(xUnit?' '+escapeHtml(xUnit):'')+'<br>y: '+escapeHtml(y)+(yUnit?' '+escapeHtml(yUnit):'')+'</div>'}const rawCategory=entry.axisValue??values[0]??entry.name;const category=model.dateTimePresentation?iso(rawCategory):rowLabel(rawCategory,model);const value=model.kind==='line'?values[1]:entry.value;const categoryUnit=model.kind==='line'?model.axes.find(item=>item.role==='x')?.name:undefined;const coordinate=escapeHtml(category)+(categoryUnit?' '+escapeHtml(categoryUnit):'');return '<div><strong>'+escapeHtml(entry.seriesName||'')+'</strong><br>'+coordinate+': '+escapeHtml(value)+(series?.unit?.text?' '+escapeHtml(series.unit.text):'')+'</div>'}).join('')};
482
499
  const setZoom=(chart,zoom)=>{const current=chart.getOption().dataZoom?.[0]??{start:0,end:100};chart.setOption({dataZoom:[{...current,...zoom}]})};
@@ -419,7 +419,9 @@ function addChart(children, emission, identity) {
419
419
  return;
420
420
  }
421
421
  const description = [
422
- ...plotted.omittedSeries.map(name => `Series "${name}" has no plottable coordinates and is listed only in the complete data table.`),
422
+ ...plotted.omittedSeries.map(name => model.showTable
423
+ ? `Series "${name}" has no plottable coordinates and is listed only in the complete data table.`
424
+ : `Series "${name}" has no plottable coordinates and is omitted from the chart.`),
423
425
  ...(plotted.hasGaps ? ['Null gaps break the line; continued segments are hidden from the legend.'] : [])
424
426
  ];
425
427
  const run = new ChartRun({
@@ -438,7 +440,9 @@ function addChart(children, emission, identity) {
438
440
  });
439
441
  children.push(new Paragraph({ children: [run] }));
440
442
  if (plotted.omittedSeries.length > 0) {
441
- children.push(new Paragraph(`Series with no plottable coordinates, shown only in the complete table: ${plotted.omittedSeries.join(', ')}.`));
443
+ children.push(new Paragraph(model.showTable
444
+ ? `Series with no plottable coordinates, shown only in the complete table: ${plotted.omittedSeries.join(', ')}.`
445
+ : `Series with no plottable coordinates, omitted from the chart: ${plotted.omittedSeries.join(', ')}.`));
442
446
  }
443
447
  addChartTable(children, model);
444
448
  return;
@@ -518,6 +522,8 @@ function addNoChartAlternative(children, model, notice) {
518
522
  addChartTable(children, model);
519
523
  }
520
524
  function addChartTable(children, model) {
525
+ if (!model.showTable)
526
+ return;
521
527
  const header = new TableRow({
522
528
  tableHeader: true,
523
529
  cantSplit: true,
@@ -539,10 +545,13 @@ function addChartTable(children, model) {
539
545
  }));
540
546
  }
541
547
  function chartAltText(model, details = []) {
548
+ const summary = model.showTable
549
+ ? model.accessibility.summary
550
+ : `${model.table.rows.length} source rows; ${model.plottedPointCount} plotted points.${model.dateTimePresentation ? ' DateTime values are presented in UTC ISO 8601 format; source order is preserved.' : ''}`;
542
551
  return {
543
- name: model.accessibility.tableId,
552
+ name: model.showTable ? model.accessibility.tableId : model.accessibility.title,
544
553
  title: model.accessibility.title,
545
- description: [model.accessibility.description, model.accessibility.summary, ...details].join(' ')
554
+ description: [model.accessibility.description, summary, ...details].join(' ')
546
555
  };
547
556
  }
548
557
  function chartTitle(model, accent) {
@@ -331,6 +331,8 @@ function addChart(content, emission, identity, renderChart) {
331
331
  ],
332
332
  unbreakable: true
333
333
  });
334
+ if (!model.showTable)
335
+ return;
334
336
  content.push({
335
337
  table: {
336
338
  headerRows: 1,
@@ -2,7 +2,7 @@ import { inputError, staticError, throwInputErrors, throwInvalidLoopIterable, th
2
2
  import { Environment } from './environment';
3
3
  import { evaluateStandardLibraryCall, isMathematicalFunction } from './standardLibrary';
4
4
  import { fieldRegistry } from '../typechecker/declarationRegistry';
5
- import { canonicalUnit, composeUnits, isMeasurement, measurement, powerUnit, sqrtMeasurement, unitFromMetadata } from './measurement';
5
+ import { canonicalUnit, composeUnits, isAffineUnit, isMeasurement, measurement, measurementDisplayValue, measurementPhysicalValue, powerUnit, sqrtMeasurement, unitFromMetadata } from './measurement';
6
6
  import { createDiagramModel } from './diagramModel';
7
7
  function validateRuntimeValue(value, expected, env, source, file, valuePath) {
8
8
  const diagnostics = [];
@@ -49,7 +49,7 @@ function validateRuntimeValue(value, expected, env, source, file, valuePath) {
49
49
  || [...target.vector].some(([identity, exponent]) => vector[identity] !== exponent)) {
50
50
  report('Measurement dimension does not match the declared dimension', target, actual, dataPath, fieldSource);
51
51
  }
52
- if (!Number.isFinite(actual.value) || !Number.isFinite(actual.value * actual.unit.scale)) {
52
+ if (!Number.isFinite(actual.value) || !Number.isFinite(measurementPhysicalValue(actual))) {
53
53
  report('Measurement value must be finite', target, actual, dataPath, fieldSource);
54
54
  }
55
55
  return;
@@ -258,7 +258,7 @@ export function evaluateExpression(node, env, file) {
258
258
  if (typeof value !== 'number')
259
259
  return staticError('AMX3007', 'Unit attachment requires a Number expression', node.source, file);
260
260
  const result = measurement(value, unitFromMetadata(unit));
261
- if (!Number.isFinite(result.value * result.unit.scale)) {
261
+ if (!Number.isFinite(measurementPhysicalValue(result))) {
262
262
  throwMeasurementDomainError('Measurement physical value must be finite', node.source, file);
263
263
  }
264
264
  return result;
@@ -271,10 +271,11 @@ export function evaluateExpression(node, env, file) {
271
271
  if (!isMeasurement(value) || !sameMeasurementVector(value, unit.vector)) {
272
272
  return staticError('AMX3007', `Cannot convert value to unit '${node.unit}'`, node.source, file);
273
273
  }
274
- const converted = value.value * value.unit.scale / unit.scale;
274
+ const target = unitFromMetadata(unit);
275
+ const converted = measurementDisplayValue(measurementPhysicalValue(value), target);
275
276
  if (!Number.isFinite(converted))
276
277
  throwMeasurementDomainError('Converted measurement value must be finite', node.source, file);
277
- return measurement(converted, unitFromMetadata(unit));
278
+ return measurement(converted, target);
278
279
  }
279
280
  case 'binaryExpression':
280
281
  return evalBinary(node, env, file);
@@ -323,10 +324,15 @@ function evalBinary(node, env, file) {
323
324
  if (!isMeasurement(left) || !isMeasurement(right) || !sameMeasurementVector(left, new Map(Object.entries(right.unit.vector)))) {
324
325
  return staticError('AMX3007', 'Addition and subtraction require compatible measurements', operatorSource, file);
325
326
  }
326
- const physicalLeft = left.value * left.unit.scale;
327
- const physicalRight = right.value * right.unit.scale;
327
+ if (node.operator === '+' && (isAffineUnit(left.unit) || isAffineUnit(right.unit))) {
328
+ return staticError('AMX3007', 'Direct addition of affine measurements is not supported', operatorSource, file);
329
+ }
330
+ const physicalLeft = measurementPhysicalValue(left);
331
+ const physicalRight = measurementPhysicalValue(right);
328
332
  const physical = node.operator === '+' ? physicalLeft + physicalRight : physicalLeft - physicalRight;
329
- const value = physical / left.unit.scale;
333
+ const value = node.operator === '+'
334
+ ? measurementDisplayValue(physical, left.unit)
335
+ : physical / left.unit.scale;
330
336
  if (!Number.isFinite(value) || !Number.isFinite(physical)) {
331
337
  throwMeasurementDomainError('Measurement arithmetic result must be finite', operatorSource, file);
332
338
  }
@@ -339,21 +345,25 @@ function evalBinary(node, env, file) {
339
345
  case '*':
340
346
  case '/': {
341
347
  if (isMeasurement(left) || isMeasurement(right)) {
342
- const numberUnit = { scale: 1, vector: {}, factors: [], text: '1' };
348
+ const numberUnit = { scale: 1, offset: 0, vector: {}, factors: [], text: '1' };
343
349
  const leftMeasurement = isMeasurement(left) ? left : undefined;
344
350
  const rightMeasurement = isMeasurement(right) ? right : undefined;
351
+ if (leftMeasurement && isAffineUnit(leftMeasurement.unit) || rightMeasurement && isAffineUnit(rightMeasurement.unit)) {
352
+ return staticError('AMX3007', node.operator === '*' ? 'Affine measurement multiplication is not supported' : 'Affine measurement division is not supported', operatorSource, file);
353
+ }
345
354
  const leftValue = leftMeasurement ? leftMeasurement.value : toNumber(left, node.left);
346
355
  const rightValue = rightMeasurement ? rightMeasurement.value : toNumber(right, node.right);
347
356
  const leftUnit = leftMeasurement?.unit ?? numberUnit;
348
357
  const rightUnit = rightMeasurement?.unit ?? numberUnit;
349
- const rightPhysical = rightValue * rightUnit.scale;
358
+ const leftPhysical = leftMeasurement ? measurementPhysicalValue(leftMeasurement) : leftValue;
359
+ const rightPhysical = rightMeasurement ? measurementPhysicalValue(rightMeasurement) : rightValue;
350
360
  if (node.operator === '/' && rightPhysical === 0) {
351
361
  throwMeasurementDomainError('Measurement division by zero', operatorSource, file);
352
362
  }
353
363
  const unit = composeUnits(leftUnit, rightUnit, node.operator === '/');
354
364
  const physical = node.operator === '/'
355
- ? leftValue * leftUnit.scale / rightPhysical
356
- : leftValue * leftUnit.scale * rightValue * rightUnit.scale;
365
+ ? leftPhysical / rightPhysical
366
+ : leftPhysical * rightPhysical;
357
367
  if (unit.vector && Object.keys(unit.vector).length === 0) {
358
368
  if (!Number.isFinite(physical))
359
369
  throwMeasurementDomainError('Measurement arithmetic result must be finite', operatorSource, file);
@@ -376,6 +386,9 @@ function evalBinary(node, env, file) {
376
386
  }
377
387
  case '^': {
378
388
  if (isMeasurement(left)) {
389
+ if (isAffineUnit(left.unit)) {
390
+ return staticError('AMX3007', 'Affine measurement powers are not supported', operatorSource, file);
391
+ }
379
392
  const exponent = toNumber(right, node.right);
380
393
  if (!Number.isSafeInteger(exponent)) {
381
394
  return staticError('AMX3007', 'A dimensional power exponent must be an integer literal', node.right.source, file);
@@ -388,9 +401,10 @@ function evalBinary(node, env, file) {
388
401
  if (!Number.isFinite(value) || !Number.isFinite(unit.scale)) {
389
402
  throwMeasurementDomainError('Measurement power result must be finite', operatorSource, file);
390
403
  }
404
+ const result = measurement(value, unit);
391
405
  if (Object.keys(unit.vector).length === 0)
392
- return value * unit.scale;
393
- return measurement(value, unit);
406
+ return measurementPhysicalValue(result);
407
+ return result;
394
408
  }
395
409
  const lNum = toNumber(left, node.left);
396
410
  const rNum = toNumber(right, node.right);
@@ -400,30 +414,30 @@ function evalBinary(node, env, file) {
400
414
  case '==':
401
415
  if (isMeasurement(left) && isMeasurement(right)) {
402
416
  return sameMeasurementVector(left, new Map(Object.entries(right.unit.vector)))
403
- && left.value * left.unit.scale === right.value * right.unit.scale;
417
+ && measurementPhysicalValue(left) === measurementPhysicalValue(right);
404
418
  }
405
419
  return left === right;
406
420
  case '!=':
407
421
  if (isMeasurement(left) && isMeasurement(right)) {
408
422
  return !sameMeasurementVector(left, new Map(Object.entries(right.unit.vector)))
409
- || left.value * left.unit.scale !== right.value * right.unit.scale;
423
+ || measurementPhysicalValue(left) !== measurementPhysicalValue(right);
410
424
  }
411
425
  return left !== right;
412
426
  case '>':
413
427
  if (isMeasurement(left) && isMeasurement(right))
414
- return left.value * left.unit.scale > right.value * right.unit.scale;
428
+ return measurementPhysicalValue(left) > measurementPhysicalValue(right);
415
429
  return toNumber(left, node.left) > toNumber(right, node.right);
416
430
  case '>=':
417
431
  if (isMeasurement(left) && isMeasurement(right))
418
- return left.value * left.unit.scale >= right.value * right.unit.scale;
432
+ return measurementPhysicalValue(left) >= measurementPhysicalValue(right);
419
433
  return toNumber(left, node.left) >= toNumber(right, node.right);
420
434
  case '<':
421
435
  if (isMeasurement(left) && isMeasurement(right))
422
- return left.value * left.unit.scale < right.value * right.unit.scale;
436
+ return measurementPhysicalValue(left) < measurementPhysicalValue(right);
423
437
  return toNumber(left, node.left) < toNumber(right, node.right);
424
438
  case '<=':
425
439
  if (isMeasurement(left) && isMeasurement(right))
426
- return left.value * left.unit.scale <= right.value * right.unit.scale;
440
+ return measurementPhysicalValue(left) <= measurementPhysicalValue(right);
427
441
  return toNumber(left, node.left) <= toNumber(right, node.right);
428
442
  // Logical (short-circuit not required for simple impl; evaluate both then apply)
429
443
  case 'and':
@@ -446,6 +460,111 @@ function evalUnary(node, env, file) {
446
460
  }
447
461
  throw new Error(`Unsupported unary operator: ${node.operator}`);
448
462
  }
463
+ export function evaluateBinaryValues(operator, leftValue, rightValue, source, file) {
464
+ const environment = new Environment();
465
+ const leftName = '__amxRuntimeLeftValue';
466
+ const rightName = '__amxRuntimeRightValue';
467
+ environment.set(leftName, leftValue);
468
+ environment.set(rightName, rightValue);
469
+ return evalBinary({
470
+ type: 'binaryExpression',
471
+ operator,
472
+ left: { type: 'identifier', name: leftName, source },
473
+ right: { type: 'identifier', name: rightName, source },
474
+ operatorSource: source,
475
+ source
476
+ }, environment, file);
477
+ }
478
+ export function evaluateUnaryValue(operator, value, source, file) {
479
+ const environment = new Environment();
480
+ const name = '__amxRuntimeUnaryValue';
481
+ environment.set(name, value);
482
+ return evalUnary({
483
+ type: 'unaryExpression',
484
+ operator,
485
+ argument: { type: 'identifier', name, source },
486
+ source
487
+ }, environment, file);
488
+ }
489
+ export function evaluateBuiltinValues(callee, values, source, file, dimensionRegistry) {
490
+ const environment = new Environment();
491
+ environment.dimensionRegistry = dimensionRegistry;
492
+ const argumentsList = values.map((value, index) => {
493
+ const name = `__amxRuntimeArgument${index}`;
494
+ environment.set(name, value);
495
+ return { type: 'identifier', name, source };
496
+ });
497
+ return evalFunctionCall({
498
+ type: 'functionCall',
499
+ callee,
500
+ arguments: argumentsList,
501
+ source
502
+ }, environment, file);
503
+ }
504
+ export function evaluateListItem(listValue, indexValue, source, file) {
505
+ const environment = new Environment();
506
+ const listName = '__amxRuntimeListValue';
507
+ const indexName = '__amxRuntimeIndexValue';
508
+ environment.set(listName, listValue);
509
+ environment.set(indexName, indexValue);
510
+ return evalListAccess({
511
+ type: 'listAccess',
512
+ receiver: { type: 'identifier', name: listName, source },
513
+ index: { type: 'identifier', name: indexName, source },
514
+ source
515
+ }, environment, file);
516
+ }
517
+ export function evaluateRangeValues(startValue, endValue, source, file) {
518
+ const environment = new Environment();
519
+ const startName = '__amxRuntimeRangeStart';
520
+ const endName = '__amxRuntimeRangeEnd';
521
+ environment.set(startName, startValue);
522
+ environment.set(endName, endValue);
523
+ return evalRange({
524
+ type: 'rangeExpression',
525
+ start: { type: 'identifier', name: startName, source },
526
+ end: { type: 'identifier', name: endName, source },
527
+ source
528
+ }, environment, file);
529
+ }
530
+ export function evaluateListAddition(list, value, position, mutable, targetName, source, file) {
531
+ const environment = new Environment();
532
+ environment.set(targetName, list);
533
+ if (!mutable)
534
+ environment.markImmutable(list);
535
+ const valueName = '__amxRuntimeListAddValue';
536
+ const positionName = '__amxRuntimeListAddPosition';
537
+ environment.set(valueName, value);
538
+ environment.set(positionName, position);
539
+ evaluateAddStatement({
540
+ type: 'addStatement', name: targetName,
541
+ value: { type: 'identifier', name: valueName, source },
542
+ ...(position === undefined ? {} : { index: { type: 'identifier', name: positionName, source } }),
543
+ source
544
+ }, environment, file);
545
+ }
546
+ export function evaluateListRemoval(list, count, position, mutable, targetName, source, file) {
547
+ const environment = new Environment();
548
+ environment.set(targetName, list);
549
+ if (!mutable)
550
+ environment.markImmutable(list);
551
+ const countName = '__amxRuntimeListRemoveCount';
552
+ const positionName = '__amxRuntimeListRemovePosition';
553
+ environment.set(countName, count);
554
+ environment.set(positionName, position);
555
+ evaluateRemoveStatement({
556
+ type: 'removeStatement', name: targetName,
557
+ count: { type: 'identifier', name: countName, source },
558
+ ...(position === undefined ? {} : { index: { type: 'identifier', name: positionName, source } }),
559
+ source
560
+ }, environment, file);
561
+ }
562
+ export function evaluateIterableValue(value, source, file) {
563
+ const environment = new Environment();
564
+ const name = '__amxRuntimeIterableValue';
565
+ environment.set(name, value);
566
+ return evaluateLoopIterable({ type: 'identifier', name, source }, environment, file);
567
+ }
449
568
  function evalConditional(node, env, file) {
450
569
  const testVal = evaluateExpression(node.test, env, file);
451
570
  return toBoolean(testVal)
@@ -629,15 +748,17 @@ function evalFunctionCall(node, env, file) {
629
748
  return evaluateStandardLibraryCall(node.callee, args, node.source, file);
630
749
  return measurements.reduce((best, current) => {
631
750
  const better = node.callee === 'min'
632
- ? current.value * current.unit.scale < best.value * best.unit.scale
633
- : current.value * current.unit.scale > best.value * best.unit.scale;
751
+ ? measurementPhysicalValue(current) < measurementPhysicalValue(best)
752
+ : measurementPhysicalValue(current) > measurementPhysicalValue(best);
634
753
  return better ? current : best;
635
754
  });
636
755
  }
637
- const physicalSum = measurements.reduce((sum, current) => sum + current.value * current.unit.scale, 0);
638
- const value = (node.callee === 'mean' ? physicalSum / measurements.length : physicalSum) / first.unit.scale;
639
- if (!Number.isFinite(value))
756
+ const physicalSum = measurements.reduce((sum, current) => sum + measurementPhysicalValue(current), 0);
757
+ const physicalResult = node.callee === 'mean' ? physicalSum / measurements.length : physicalSum;
758
+ const value = measurementDisplayValue(physicalResult, first.unit);
759
+ if (!Number.isFinite(physicalSum) || !Number.isFinite(physicalResult) || !Number.isFinite(value)) {
640
760
  throwMeasurementDomainError(`${node.callee} result must be finite`, node.source, file);
761
+ }
641
762
  return measurement(value, first.unit);
642
763
  }
643
764
  if (node.callee === 'sum' && Array.isArray(values) && values.length === 0
@@ -653,7 +774,7 @@ function evalFunctionCall(node, env, file) {
653
774
  if (Object.keys(value.unit.vector).length !== 0) {
654
775
  return staticError('AMX3007', `'${node.callee}' requires a Number or dimensionless Measurement`, node.arguments[0]?.source ?? node.source, file);
655
776
  }
656
- return evaluateStandardLibraryCall(node.callee, [value.value * value.unit.scale], node.source, file);
777
+ return evaluateStandardLibraryCall(node.callee, [measurementPhysicalValue(value)], node.source, file);
657
778
  }
658
779
  switch (node.callee) {
659
780
  case 'abs':
@@ -667,7 +788,10 @@ function evalFunctionCall(node, env, file) {
667
788
  return measurement(rounded, value.unit);
668
789
  }
669
790
  case 'sqrt': {
670
- const physical = value.value * value.unit.scale;
791
+ if (isAffineUnit(value.unit)) {
792
+ return staticError('AMX3007', 'Affine measurement sqrt is not supported', node.source, file);
793
+ }
794
+ const physical = measurementPhysicalValue(value);
671
795
  if (physical < 0)
672
796
  throwMeasurementDomainError('sqrt of a negative measurement value', node.source, file);
673
797
  if (!env.dimensionRegistry)
@@ -678,7 +802,7 @@ function evalFunctionCall(node, env, file) {
678
802
  throwMeasurementDomainError('sqrt result must be finite', node.source, file);
679
803
  }
680
804
  if (Object.keys(result.unit.vector).length === 0)
681
- return result.value * result.unit.scale;
805
+ return measurementPhysicalValue(result);
682
806
  return result;
683
807
  }
684
808
  catch (error) {
@@ -689,6 +813,9 @@ function evalFunctionCall(node, env, file) {
689
813
  }
690
814
  }
691
815
  case 'pow': {
816
+ if (isAffineUnit(value.unit)) {
817
+ return staticError('AMX3007', 'Affine measurement powers are not supported', node.source, file);
818
+ }
692
819
  const exponent = toNumber(args[1], node.arguments[1]);
693
820
  if (!Number.isSafeInteger(exponent))
694
821
  return staticError('AMX3007', 'A dimensional pow exponent must be an integer literal', node.arguments[1]?.source, file);
@@ -698,9 +825,10 @@ function evalFunctionCall(node, env, file) {
698
825
  const result = Math.pow(value.value, exponent);
699
826
  if (!Number.isFinite(result) || !Number.isFinite(unit.scale))
700
827
  throwMeasurementDomainError('pow result must be finite', node.source, file);
828
+ const powered = measurement(result, unit);
701
829
  if (!Object.keys(unit.vector).length)
702
- return result * unit.scale;
703
- return measurement(result, unit);
830
+ return measurementPhysicalValue(powered);
831
+ return powered;
704
832
  }
705
833
  }
706
834
  }
@@ -774,8 +902,17 @@ function snapshotView(name, env, file, source) {
774
902
  let labels;
775
903
  let headings;
776
904
  let measurementDescriptors;
905
+ let showTable = false;
777
906
  let viewData;
778
907
  if (declaration.type === 'chartDeclaration') {
908
+ const showTableOption = declaration.options.find(option => option.type === 'chartShowTableOption');
909
+ if (showTableOption?.type === 'chartShowTableOption') {
910
+ const resolved = evaluateExpression(showTableOption.expression, env, file);
911
+ if (typeof resolved !== 'boolean') {
912
+ staticError('AMX3002', `Expected Boolean, got ${typeof resolved}`, showTableOption.expression.source, file);
913
+ }
914
+ showTable = resolved;
915
+ }
779
916
  const labelsOption = declaration.options.find(option => option.type === 'chartFieldOption' && option.role === 'labels');
780
917
  if (labelsOption?.type === 'chartFieldOption') {
781
918
  const labelValues = env.get(labelsOption.field, labelsOption.fieldSource, file);
@@ -810,7 +947,7 @@ function snapshotView(name, env, file, source) {
810
947
  return declaration.type === 'tableDeclaration'
811
948
  ? Object.freeze({ kind: 'table', ...emission, declaration })
812
949
  : Object.freeze({
813
- kind: 'chart', ...emission, declaration,
950
+ kind: 'chart', ...emission, declaration, showTable,
814
951
  ...(labels ? { labels } : {}), ...(headings ? { headings } : {}),
815
952
  ...(measurementDescriptors?.length ? { measurementDescriptors } : {})
816
953
  });
@@ -893,7 +1030,7 @@ function normalizeChartValue(value, target, name, source, declaration, file) {
893
1030
  if (!isMeasurement(value) || !sameMeasurementUnits(value, target)) {
894
1031
  staticError('AMX3007', `Chart '${name}' contains an incompatible measurement value`, source, file, declaration.source);
895
1032
  }
896
- const converted = value.value * value.unit.scale / target.unit.scale;
1033
+ const converted = measurementDisplayValue(measurementPhysicalValue(value), target.unit);
897
1034
  if (!Number.isFinite(converted)) {
898
1035
  staticError('AMX3007', `Chart '${name}' measurement cannot be normalized to its first display unit`, source, file, declaration.source);
899
1036
  }
@@ -1,4 +1,4 @@
1
- import { composeUnits, powerUnit, unitFromMetadata } from './measurement';
1
+ import { composeUnits, isAffineUnit, powerUnit, unitFromMetadata } from './measurement';
2
2
  export class ExternalUnitTextError extends Error {
3
3
  unknownUnit;
4
4
  constructor(message, unknownUnit) {
@@ -9,6 +9,7 @@ export class ExternalUnitTextError extends Error {
9
9
  }
10
10
  const unitless = Object.freeze({
11
11
  scale: 1,
12
+ offset: 0,
12
13
  vector: Object.freeze({}),
13
14
  factors: Object.freeze([]),
14
15
  text: '1'
@@ -32,10 +33,16 @@ export function parseExternalUnitText(text, registry) {
32
33
  const parseProduct = () => {
33
34
  let unit = parseFactor();
34
35
  while (true) {
35
- if (consume('*'))
36
- unit = validateUnit(composeUnits(unit, parseFactor()));
37
- else if (consume('/'))
38
- unit = validateUnit(composeUnits(unit, parseFactor(), true));
36
+ if (consume('*')) {
37
+ const right = parseFactor();
38
+ rejectAffineComposition(unit, right);
39
+ unit = validateUnit(composeUnits(unit, right));
40
+ }
41
+ else if (consume('/')) {
42
+ const right = parseFactor();
43
+ rejectAffineComposition(unit, right);
44
+ unit = validateUnit(composeUnits(unit, right, true));
45
+ }
39
46
  else
40
47
  return unit;
41
48
  }
@@ -63,6 +70,9 @@ export function parseExternalUnitText(text, registry) {
63
70
  unit = unitFromMetadata(metadata);
64
71
  }
65
72
  if (consume('^')) {
73
+ if (isAffineUnit(unit)) {
74
+ throw new ExternalUnitTextError('Affine units may not be used in external unit powers', false);
75
+ }
66
76
  skipWhitespace();
67
77
  const exponent = source.slice(offset).match(/^[+-]?\d+/);
68
78
  if (!exponent)
@@ -81,8 +91,13 @@ export function parseExternalUnitText(text, registry) {
81
91
  throw new ExternalUnitTextError(`Unexpected '${source[offset]}' in unit expression`, false);
82
92
  return Object.freeze({ ...parsed, text: source });
83
93
  }
94
+ function rejectAffineComposition(left, right) {
95
+ if (isAffineUnit(left) || isAffineUnit(right)) {
96
+ throw new ExternalUnitTextError('Affine units may not be used in external unit products or divisions', false);
97
+ }
98
+ }
84
99
  function validateUnit(unit) {
85
- if (!Number.isFinite(unit.scale) || unit.scale <= 0
100
+ if (!Number.isFinite(unit.scale) || unit.scale <= 0 || !Number.isFinite(unit.offset)
86
101
  || Object.values(unit.vector).some(exponent => !Number.isSafeInteger(exponent))
87
102
  || unit.factors.some(factor => !Number.isSafeInteger(factor.exponent))) {
88
103
  throw new ExternalUnitTextError('Unit expression exceeds supported scale or exponent limits', false);