@nova-energy/openamx 0.16.0 → 0.19.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,17 @@
1
1
  import { AmxError, staticError } from '../diagnostics/errors';
2
2
  import { fieldRegistry, setDeclaringRegistry } from '../typechecker/declarationRegistry';
3
- import { evaluateExpression } from './evaluateExpression';
3
+ import { evaluateExpression, evaluateLoopIterable, toBoolean, withLoopBinding } from './evaluateExpression';
4
4
  import { Environment } from './environment';
5
5
  const capturedContexts = new WeakMap();
6
+ const expandedElementsByModel = new WeakMap();
7
+ function hasDiagramControls(content) {
8
+ return content.some(node => node.type !== 'diagramElement');
9
+ }
10
+ function assertLegacyDiagramSerializationSupported(model) {
11
+ if (hasDiagramControls(model.declaration.content)) {
12
+ throw new Error('Version 1 control-bearing diagram models are missing expanded instances.');
13
+ }
14
+ }
6
15
  function serializeValue(value, ancestors = new Set()) {
7
16
  if (value === undefined)
8
17
  return ['undefined'];
@@ -107,10 +116,168 @@ function mapValue(value, field) {
107
116
  throw new Error(`Invalid key in serialized diagram context map '${field}'.`);
108
117
  return value;
109
118
  }
119
+ function serializeBindingValue(value, ancestors = new Set()) {
120
+ if (value === undefined || value === null || typeof value === 'boolean'
121
+ || typeof value === 'number' || typeof value === 'string')
122
+ return serializeValue(value);
123
+ if (!value || typeof value !== 'object')
124
+ throw new Error('Unsupported diagram instance binding value.');
125
+ if (ancestors.has(value))
126
+ throw new Error('Diagram instance binding contains a cyclic value.');
127
+ ancestors.add(value);
128
+ try {
129
+ if (Array.isArray(value))
130
+ return ['array', value.map(item => serializeBindingValue(item, ancestors))];
131
+ const prototype = Object.getPrototypeOf(value);
132
+ if (prototype !== Object.prototype && prototype !== null || Object.getOwnPropertySymbols(value).length > 0) {
133
+ throw new Error('Unsupported diagram instance binding value.');
134
+ }
135
+ return ['object', Object.entries(value).map(([key, item]) => [key, serializeBindingValue(item, ancestors)])];
136
+ }
137
+ finally {
138
+ ancestors.delete(value);
139
+ }
140
+ }
141
+ function assertDiagramBindingValue(value, ancestors = new Set()) {
142
+ if (value === undefined || value === null || typeof value === 'boolean'
143
+ || typeof value === 'number' || typeof value === 'string')
144
+ return;
145
+ if (!value || typeof value !== 'object')
146
+ throw new Error('Unsupported serialized diagram instance binding value.');
147
+ if (ancestors.has(value))
148
+ throw new Error('Serialized diagram instance binding contains a cyclic value.');
149
+ ancestors.add(value);
150
+ try {
151
+ if (Array.isArray(value)) {
152
+ value.forEach(item => assertDiagramBindingValue(item, ancestors));
153
+ return;
154
+ }
155
+ const prototype = Object.getPrototypeOf(value);
156
+ if (prototype !== Object.prototype && prototype !== null) {
157
+ throw new Error('Unsupported serialized diagram instance binding value.');
158
+ }
159
+ Object.values(value).forEach(item => assertDiagramBindingValue(item, ancestors));
160
+ }
161
+ finally {
162
+ ancestors.delete(value);
163
+ }
164
+ }
165
+ function collectDiagramElementPaths(content, paths = new Map(), prefix = []) {
166
+ content.forEach((node, index) => {
167
+ const path = [...prefix, { type: 'content', index }];
168
+ if (node.type === 'diagramElement') {
169
+ if (paths.has(node))
170
+ throw new Error('A diagram primitive appears at multiple AST paths.');
171
+ paths.set(node, path);
172
+ }
173
+ else if (node.type === 'diagramForBlock') {
174
+ collectDiagramElementPaths(node.content, paths, path);
175
+ }
176
+ else {
177
+ collectDiagramElementPaths(node.consequent, paths, [...path, { type: 'branch', branch: 'consequent' }]);
178
+ if (node.alternate) {
179
+ collectDiagramElementPaths(node.alternate, paths, [...path, { type: 'branch', branch: 'alternate' }]);
180
+ }
181
+ }
182
+ });
183
+ return paths;
184
+ }
185
+ function resolveDiagramElementPath(content, sourcePath) {
186
+ if (!Array.isArray(sourcePath))
187
+ throw new Error('Invalid serialized diagram instance source path.');
188
+ let currentContent = content;
189
+ let pathIndex = 0;
190
+ let controlOriginating = false;
191
+ const bindingNames = [];
192
+ while (pathIndex < sourcePath.length) {
193
+ const segment = sourcePath[pathIndex++];
194
+ if (!segment || typeof segment !== 'object' || Array.isArray(segment)
195
+ || segment.type !== 'content' || !Number.isSafeInteger(segment.index) || segment.index < 0) {
196
+ throw new Error('Invalid serialized diagram instance source path.');
197
+ }
198
+ const node = currentContent[segment.index];
199
+ if (!node)
200
+ throw new Error('Serialized diagram instance source path does not resolve.');
201
+ if (node.type === 'diagramElement') {
202
+ if (pathIndex !== sourcePath.length)
203
+ throw new Error('Serialized diagram instance source path continues past a primitive.');
204
+ return { element: node, bindingNames, controlOriginating };
205
+ }
206
+ controlOriginating = true;
207
+ if (node.type === 'diagramForBlock') {
208
+ bindingNames.push(node.variable);
209
+ currentContent = node.content;
210
+ continue;
211
+ }
212
+ const branch = sourcePath[pathIndex++];
213
+ if (!branch || typeof branch !== 'object' || Array.isArray(branch)
214
+ || branch.type !== 'branch' || (branch.branch !== 'consequent' && branch.branch !== 'alternate')) {
215
+ throw new Error('Invalid serialized diagram instance branch path.');
216
+ }
217
+ currentContent = branch.branch === 'consequent' ? node.consequent : node.alternate ?? [];
218
+ if (branch.branch === 'alternate' && !node.alternate) {
219
+ throw new Error('Serialized diagram instance source path does not resolve.');
220
+ }
221
+ }
222
+ throw new Error('Serialized diagram instance source path does not resolve to a primitive.');
223
+ }
224
+ function serializeDiagramInstances(model, instances) {
225
+ const paths = collectDiagramElementPaths(model.declaration.content);
226
+ return instances.map(instance => {
227
+ const sourcePath = paths.get(instance.element);
228
+ if (!sourcePath)
229
+ throw new Error('Diagram instance source is absent from its declaration.');
230
+ return {
231
+ identity: instance.identity,
232
+ sourcePath,
233
+ bindings: instance.bindings.map(binding => ({
234
+ name: binding.name,
235
+ value: serializeBindingValue(binding.value)
236
+ }))
237
+ };
238
+ });
239
+ }
240
+ function deserializeDiagramInstances(content, value) {
241
+ if (!Array.isArray(value))
242
+ throw new Error('Invalid serialized diagram instance list.');
243
+ let controlCount = 0;
244
+ const instances = value.map((raw, index) => {
245
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)
246
+ || !('identity' in raw) || !('bindings' in raw)
247
+ || !Number.isSafeInteger(raw.identity) || raw.identity !== index || !Array.isArray(raw.bindings)) {
248
+ throw new Error('Invalid serialized diagram instance descriptor.');
249
+ }
250
+ const descriptor = raw;
251
+ const rawBindings = descriptor.bindings;
252
+ const resolved = resolveDiagramElementPath(content, descriptor.sourcePath);
253
+ if (resolved.controlOriginating && ++controlCount > generatedElementLimit) {
254
+ throw new Error('Serialized diagram instance list exceeds the generated element limit.');
255
+ }
256
+ if (rawBindings.length !== resolved.bindingNames.length) {
257
+ throw new Error('Serialized diagram instance has incomplete loop bindings.');
258
+ }
259
+ const bindings = rawBindings.map((binding, bindingIndex) => {
260
+ if (!binding || typeof binding !== 'object' || Array.isArray(binding)
261
+ || !('name' in binding) || !('value' in binding)) {
262
+ throw new Error('Invalid serialized diagram instance loop binding.');
263
+ }
264
+ const entry = binding;
265
+ if (entry.name !== resolved.bindingNames[bindingIndex] || typeof entry.name !== 'string') {
266
+ throw new Error('Invalid serialized diagram instance loop binding.');
267
+ }
268
+ const bindingValue = deserializeValue(entry.value);
269
+ assertDiagramBindingValue(bindingValue);
270
+ return Object.freeze({ name: entry.name, value: bindingValue });
271
+ });
272
+ return Object.freeze({ identity: descriptor.identity, element: resolved.element, bindings: Object.freeze(bindings) });
273
+ });
274
+ return Object.freeze(instances);
275
+ }
110
276
  export function serializeDiagramSceneModel(model) {
111
277
  const env = capturedContexts.get(model);
112
278
  if (!env)
113
279
  throw new Error('Diagram model has no captured AMX evaluation context');
280
+ const instances = expandedElementsByModel.get(model) ?? directDiagramElements(model.declaration.content);
114
281
  const context = {
115
282
  values: env.toObject(),
116
283
  immutableValues: Object.entries(env.toObject()).filter(([, value]) => env.isImmutable(value)).map(([name]) => name),
@@ -135,26 +302,43 @@ export function serializeDiagramSceneModel(model) {
135
302
  }
136
303
  };
137
304
  const payload = {
138
- version: 1,
305
+ version: 2,
139
306
  model: serializeValue(model),
140
- context: serializeValue(context)
307
+ context: serializeValue(context),
308
+ instances: serializeDiagramInstances(model, instances),
309
+ instanceCount: instances.length
141
310
  };
142
311
  return JSON.stringify(payload);
143
312
  }
144
313
  export function deserializeDiagramSceneModel(serialized) {
145
314
  const payload = JSON.parse(serialized);
146
315
  if (!payload || typeof payload !== 'object' || Array.isArray(payload)
147
- || !('version' in payload) || payload.version !== 1
316
+ || !('version' in payload) || (payload.version !== 1 && payload.version !== 2)
148
317
  || !('model' in payload) || !('context' in payload)) {
149
318
  throw new Error('Invalid serialized diagram model envelope.');
150
319
  }
151
- const modelValue = deserializeValue(payload.model);
152
- const contextValue = deserializeValue(payload.context);
320
+ const envelope = payload;
321
+ const version = envelope.version;
322
+ if (version === 2) {
323
+ if (!Array.isArray(envelope.instances))
324
+ throw new Error('Invalid serialized diagram instance list.');
325
+ if (!Number.isSafeInteger(envelope.instanceCount) || envelope.instanceCount !== envelope.instances.length) {
326
+ throw new Error('Serialized diagram instance count does not match its payload.');
327
+ }
328
+ }
329
+ const modelValue = deserializeValue(envelope.model);
330
+ const contextValue = deserializeValue(envelope.context);
153
331
  if (!modelValue || typeof modelValue !== 'object' || Array.isArray(modelValue)
154
332
  || !contextValue || typeof contextValue !== 'object' || Array.isArray(contextValue)) {
155
333
  throw new Error('Invalid serialized diagram model or evaluation context.');
156
334
  }
157
335
  const model = freezeData(modelValue);
336
+ if (!model.declaration || !Array.isArray(model.declaration.content)) {
337
+ throw new Error('Invalid serialized diagram declaration.');
338
+ }
339
+ const instances = version === 1
340
+ ? (assertLegacyDiagramSerializationSupported(model), directDiagramElements(model.declaration.content))
341
+ : deserializeDiagramInstances(model.declaration.content, envelope.instances);
158
342
  const context = contextValue;
159
343
  if (!context.values || typeof context.values !== 'object' || Array.isArray(context.values)
160
344
  || !Array.isArray(context.immutableValues) || !context.declarationRegistries
@@ -202,6 +386,7 @@ export function deserializeDiagramSceneModel(serialized) {
202
386
  setDeclaringRegistry(declaration, item.declaration);
203
387
  }
204
388
  capturedContexts.set(model, env);
389
+ expandedElementsByModel.set(model, instances);
205
390
  return model;
206
391
  }
207
392
  function cloneData(value, seen = new Map()) {
@@ -287,6 +472,73 @@ function cloneEnvironment(source) {
287
472
  }
288
473
  return copy;
289
474
  }
475
+ const generatedElementLimit = 64;
476
+ function directDiagramElements(content) {
477
+ if (hasDiagramControls(content)) {
478
+ throw new Error('Control-bearing diagram models are missing their expanded per-instance bindings.');
479
+ }
480
+ return Object.freeze(content.map((node, identity) => {
481
+ if (node.type !== 'diagramElement')
482
+ throw new Error('Unexpected diagram control in static content.');
483
+ return Object.freeze({ identity, element: node, bindings: Object.freeze([]) });
484
+ }));
485
+ }
486
+ function expandDiagramContent(content, env, file) {
487
+ const instances = [];
488
+ const bindings = [];
489
+ let generatedCount = 0;
490
+ const visit = (nodes, controlOriginating) => {
491
+ for (const node of nodes) {
492
+ if (node.type === 'diagramElement') {
493
+ if (controlOriginating) {
494
+ if (generatedCount >= generatedElementLimit) {
495
+ staticError('AMXD6004', 'Number of elements in this diagram exceed the maximum (64)', node.source ?? node.nameSource, file);
496
+ }
497
+ generatedCount++;
498
+ }
499
+ instances.push(Object.freeze({
500
+ identity: instances.length,
501
+ element: node,
502
+ bindings: Object.freeze(bindings.map(binding => Object.freeze({
503
+ name: binding.name,
504
+ value: cloneData(binding.value)
505
+ })))
506
+ }));
507
+ continue;
508
+ }
509
+ if (node.type === 'diagramForBlock') {
510
+ const values = evaluateLoopIterable(node.iterable, env, file);
511
+ withLoopBinding(node.variable, values, env, () => {
512
+ bindings.push({ name: node.variable, value: env.get(node.variable) });
513
+ try {
514
+ visit(node.content, true);
515
+ }
516
+ finally {
517
+ bindings.pop();
518
+ }
519
+ });
520
+ continue;
521
+ }
522
+ const branch = toBoolean(evaluateExpression(node.test, env, file))
523
+ ? node.consequent
524
+ : node.alternate;
525
+ if (branch)
526
+ visit(branch, true);
527
+ }
528
+ };
529
+ visit(content, false);
530
+ return Object.freeze(instances);
531
+ }
532
+ function withInstanceBindings(bindings, env, run, index = 0) {
533
+ if (index >= bindings.length)
534
+ return run();
535
+ let result;
536
+ const binding = bindings[index];
537
+ withLoopBinding(binding.name, [binding.value], env, () => {
538
+ result = withInstanceBindings(bindings, env, run, index + 1);
539
+ });
540
+ return result;
541
+ }
290
542
  function property(element, name) {
291
543
  const found = element.properties.find(item => item.name === name);
292
544
  if (!found)
@@ -307,13 +559,13 @@ function requiredNumber(element, name, env, file, timeline, time) {
307
559
  }
308
560
  return value;
309
561
  }
310
- function evaluateFrame(declaration, timeline, time, sourceEnvironment, file) {
562
+ function evaluateFrame(declaration, timeline, time, instances, sourceEnvironment, file) {
311
563
  if (typeof time !== 'number' || !Number.isFinite(time) || time < timeline.from || time > timeline.to) {
312
564
  staticError('AMXD004', 'Invalid time bounds', declaration.times[0]?.source ?? declaration.source, file);
313
565
  }
314
566
  const env = cloneEnvironment(sourceEnvironment);
315
567
  env.set(timeline.variable, time);
316
- const elements = declaration.elements.map((element) => {
568
+ const evaluateElement = (element) => {
317
569
  const readNumber = (name) => requiredNumber(element, name, env, file, timeline, time);
318
570
  const readStyle = (name) => {
319
571
  const value = property(element, name).expression;
@@ -394,7 +646,8 @@ function evaluateFrame(declaration, timeline, time, sourceEnvironment, file) {
394
646
  }
395
647
  throw error;
396
648
  }
397
- });
649
+ };
650
+ const elements = instances.map((instance) => withInstanceBindings(instance.bindings, env, () => evaluateElement(instance.element)));
398
651
  return Object.freeze({ time, elements: Object.freeze(elements) });
399
652
  }
400
653
  function evaluateDocumentNumber(expression, env, file, code, message, source) {
@@ -430,7 +683,8 @@ export function createDiagramModel(sourceDeclaration, sourceEnvironment, file, d
430
683
  staticError('AMXD004', 'Invalid time bounds', time.source ?? declaration.source, file);
431
684
  const duration = evaluateDocumentNumber(time.duration, env, file, 'AMXD005', 'Invalid playback duration value', time.durationSource ?? time.source);
432
685
  const timeline = Object.freeze({ variable: time.name, from, to, duration });
433
- const initialFrame = evaluateFrame(declaration, timeline, from, env, file);
686
+ const instances = expandDiagramContent(declaration.content, env, file);
687
+ const initialFrame = evaluateFrame(declaration, timeline, from, instances, env, file);
434
688
  const model = Object.freeze({
435
689
  name: declaration.name,
436
690
  title: titleExpression.value,
@@ -445,11 +699,13 @@ export function createDiagramModel(sourceDeclaration, sourceEnvironment, file, d
445
699
  statementIndex
446
700
  });
447
701
  capturedContexts.set(model, env);
702
+ expandedElementsByModel.set(model, instances);
448
703
  return model;
449
704
  }
450
705
  export function evaluateDiagramFrame(model, time, file = model.file) {
451
706
  const env = capturedContexts.get(model);
452
707
  if (!env)
453
708
  throw new Error('Diagram model has no captured AMX evaluation context');
454
- return evaluateFrame(model.declaration, model.timeline, time, env, file);
709
+ const instances = expandedElementsByModel.get(model) ?? directDiagramElements(model.declaration.content);
710
+ return evaluateFrame(model.declaration, model.timeline, time, instances, env, file);
455
711
  }
@@ -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':
@@ -629,15 +643,17 @@ function evalFunctionCall(node, env, file) {
629
643
  return evaluateStandardLibraryCall(node.callee, args, node.source, file);
630
644
  return measurements.reduce((best, current) => {
631
645
  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;
646
+ ? measurementPhysicalValue(current) < measurementPhysicalValue(best)
647
+ : measurementPhysicalValue(current) > measurementPhysicalValue(best);
634
648
  return better ? current : best;
635
649
  });
636
650
  }
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))
651
+ const physicalSum = measurements.reduce((sum, current) => sum + measurementPhysicalValue(current), 0);
652
+ const physicalResult = node.callee === 'mean' ? physicalSum / measurements.length : physicalSum;
653
+ const value = measurementDisplayValue(physicalResult, first.unit);
654
+ if (!Number.isFinite(physicalSum) || !Number.isFinite(physicalResult) || !Number.isFinite(value)) {
640
655
  throwMeasurementDomainError(`${node.callee} result must be finite`, node.source, file);
656
+ }
641
657
  return measurement(value, first.unit);
642
658
  }
643
659
  if (node.callee === 'sum' && Array.isArray(values) && values.length === 0
@@ -653,7 +669,7 @@ function evalFunctionCall(node, env, file) {
653
669
  if (Object.keys(value.unit.vector).length !== 0) {
654
670
  return staticError('AMX3007', `'${node.callee}' requires a Number or dimensionless Measurement`, node.arguments[0]?.source ?? node.source, file);
655
671
  }
656
- return evaluateStandardLibraryCall(node.callee, [value.value * value.unit.scale], node.source, file);
672
+ return evaluateStandardLibraryCall(node.callee, [measurementPhysicalValue(value)], node.source, file);
657
673
  }
658
674
  switch (node.callee) {
659
675
  case 'abs':
@@ -667,7 +683,10 @@ function evalFunctionCall(node, env, file) {
667
683
  return measurement(rounded, value.unit);
668
684
  }
669
685
  case 'sqrt': {
670
- const physical = value.value * value.unit.scale;
686
+ if (isAffineUnit(value.unit)) {
687
+ return staticError('AMX3007', 'Affine measurement sqrt is not supported', node.source, file);
688
+ }
689
+ const physical = measurementPhysicalValue(value);
671
690
  if (physical < 0)
672
691
  throwMeasurementDomainError('sqrt of a negative measurement value', node.source, file);
673
692
  if (!env.dimensionRegistry)
@@ -678,7 +697,7 @@ function evalFunctionCall(node, env, file) {
678
697
  throwMeasurementDomainError('sqrt result must be finite', node.source, file);
679
698
  }
680
699
  if (Object.keys(result.unit.vector).length === 0)
681
- return result.value * result.unit.scale;
700
+ return measurementPhysicalValue(result);
682
701
  return result;
683
702
  }
684
703
  catch (error) {
@@ -689,6 +708,9 @@ function evalFunctionCall(node, env, file) {
689
708
  }
690
709
  }
691
710
  case 'pow': {
711
+ if (isAffineUnit(value.unit)) {
712
+ return staticError('AMX3007', 'Affine measurement powers are not supported', node.source, file);
713
+ }
692
714
  const exponent = toNumber(args[1], node.arguments[1]);
693
715
  if (!Number.isSafeInteger(exponent))
694
716
  return staticError('AMX3007', 'A dimensional pow exponent must be an integer literal', node.arguments[1]?.source, file);
@@ -698,9 +720,10 @@ function evalFunctionCall(node, env, file) {
698
720
  const result = Math.pow(value.value, exponent);
699
721
  if (!Number.isFinite(result) || !Number.isFinite(unit.scale))
700
722
  throwMeasurementDomainError('pow result must be finite', node.source, file);
723
+ const powered = measurement(result, unit);
701
724
  if (!Object.keys(unit.vector).length)
702
- return result * unit.scale;
703
- return measurement(result, unit);
725
+ return measurementPhysicalValue(powered);
726
+ return powered;
704
727
  }
705
728
  }
706
729
  }
@@ -720,7 +743,7 @@ function toNumber(v, nodeForError) {
720
743
  const locInfo = loc ? ` at line ${loc.line}` : '';
721
744
  throw new Error(`Cannot convert value to number${locInfo}`);
722
745
  }
723
- function toBoolean(v) {
746
+ export function toBoolean(v) {
724
747
  if (typeof v === 'boolean')
725
748
  return v;
726
749
  if (typeof v === 'number')
@@ -774,8 +797,17 @@ function snapshotView(name, env, file, source) {
774
797
  let labels;
775
798
  let headings;
776
799
  let measurementDescriptors;
800
+ let showTable = false;
777
801
  let viewData;
778
802
  if (declaration.type === 'chartDeclaration') {
803
+ const showTableOption = declaration.options.find(option => option.type === 'chartShowTableOption');
804
+ if (showTableOption?.type === 'chartShowTableOption') {
805
+ const resolved = evaluateExpression(showTableOption.expression, env, file);
806
+ if (typeof resolved !== 'boolean') {
807
+ staticError('AMX3002', `Expected Boolean, got ${typeof resolved}`, showTableOption.expression.source, file);
808
+ }
809
+ showTable = resolved;
810
+ }
779
811
  const labelsOption = declaration.options.find(option => option.type === 'chartFieldOption' && option.role === 'labels');
780
812
  if (labelsOption?.type === 'chartFieldOption') {
781
813
  const labelValues = env.get(labelsOption.field, labelsOption.fieldSource, file);
@@ -810,7 +842,7 @@ function snapshotView(name, env, file, source) {
810
842
  return declaration.type === 'tableDeclaration'
811
843
  ? Object.freeze({ kind: 'table', ...emission, declaration })
812
844
  : Object.freeze({
813
- kind: 'chart', ...emission, declaration,
845
+ kind: 'chart', ...emission, declaration, showTable,
814
846
  ...(labels ? { labels } : {}), ...(headings ? { headings } : {}),
815
847
  ...(measurementDescriptors?.length ? { measurementDescriptors } : {})
816
848
  });
@@ -893,7 +925,7 @@ function normalizeChartValue(value, target, name, source, declaration, file) {
893
925
  if (!isMeasurement(value) || !sameMeasurementUnits(value, target)) {
894
926
  staticError('AMX3007', `Chart '${name}' contains an incompatible measurement value`, source, file, declaration.source);
895
927
  }
896
- const converted = value.value * value.unit.scale / target.unit.scale;
928
+ const converted = measurementDisplayValue(measurementPhysicalValue(value), target.unit);
897
929
  if (!Number.isFinite(converted)) {
898
930
  staticError('AMX3007', `Chart '${name}' measurement cannot be normalized to its first display unit`, source, file, declaration.source);
899
931
  }
@@ -1109,13 +1141,13 @@ function evalForExpression(node, env, file) {
1109
1141
  }));
1110
1142
  return results;
1111
1143
  }
1112
- function evaluateLoopIterable(node, env, file) {
1144
+ export function evaluateLoopIterable(node, env, file) {
1113
1145
  const value = evaluateExpression(node, env, file);
1114
1146
  if (!Array.isArray(value))
1115
1147
  throwInvalidLoopIterable(node.source, file);
1116
1148
  return value.slice();
1117
1149
  }
1118
- function withLoopBinding(name, values, env, runIteration) {
1150
+ export function withLoopBinding(name, values, env, runIteration) {
1119
1151
  const existed = env.has(name);
1120
1152
  const previous = existed ? env.get(name) : undefined;
1121
1153
  try {