@nova-energy/openamx 0.0.0-stage → 0.10.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/COMMERCIAL-LICENSE.md +74 -0
- package/LICENSE.md +660 -0
- package/README.md +513 -2
- package/dist/ast/types.js +2 -0
- package/dist/cli.js +186 -0
- package/dist/diagnostics/errors.js +94 -0
- package/dist/editor/completion.js +313 -0
- package/dist/editor/highlighting.js +224 -0
- package/dist/editor/moduleAnalysis.js +206 -0
- package/dist/editor/refactoring.js +46 -0
- package/dist/editor/sourceRanges.js +50 -0
- package/dist/editor/symbols.js +203 -0
- package/dist/formatter/formatAmx.js +79 -0
- package/dist/index.js +10 -0
- package/dist/parser/parseDocument.js +114 -0
- package/dist/parser/parseExpression.js +768 -0
- package/dist/parser/parseFor.js +53 -0
- package/dist/parser/parseFrontMatter.js +65 -0
- package/dist/parser/parseStatements.js +667 -0
- package/dist/parser/stringScanner.js +71 -0
- package/dist/renderer/chartModel.js +476 -0
- package/dist/renderer/renderHtml.js +383 -0
- package/dist/renderer/reportDocx.js +163 -0
- package/dist/renderer/reportPdf.js +202 -0
- package/dist/renderer/reportPreparation.js +208 -0
- package/dist/runtime/csvTextSerialization.js +8 -0
- package/dist/runtime/dataText.js +191 -0
- package/dist/runtime/docxDestination.js +55 -0
- package/dist/runtime/environment.js +105 -0
- package/dist/runtime/evaluateDocument.js +32 -0
- package/dist/runtime/evaluateExpression.js +888 -0
- package/dist/runtime/externalUnits.js +91 -0
- package/dist/runtime/inputData.js +508 -0
- package/dist/runtime/measurement.js +110 -0
- package/dist/runtime/moduleLoader.js +279 -0
- package/dist/runtime/outputData.js +303 -0
- package/dist/runtime/pdfDestination.js +57 -0
- package/dist/runtime/standardLibrary.js +145 -0
- package/dist/typechecker/checkDocument.js +1282 -0
- package/dist/typechecker/declarationRegistry.js +7 -0
- package/dist/typechecker/dimensionTypes.js +1 -0
- package/package.json +33 -4
|
@@ -0,0 +1,888 @@
|
|
|
1
|
+
import { inputError, staticError, throwInputErrors, throwInvalidLoopIterable, throwInvalidRangeBounds, throwInvalidReturnContext, throwListOperationError, throwMeasurementDomainError } from '../diagnostics/errors';
|
|
2
|
+
import { Environment } from './environment';
|
|
3
|
+
import { evaluateStandardLibraryCall } from './standardLibrary';
|
|
4
|
+
import { fieldRegistry } from '../typechecker/declarationRegistry';
|
|
5
|
+
import { canonicalUnit, composeUnits, isMeasurement, measurement, powerUnit, sqrtMeasurement, unitFromMetadata } from './measurement';
|
|
6
|
+
function validateRuntimeValue(value, expected, env, source, file, valuePath) {
|
|
7
|
+
const diagnostics = [];
|
|
8
|
+
const report = (message, target, actual, dataPath, fieldSource) => {
|
|
9
|
+
const diagnostic = inputError('AMX4003', message, {
|
|
10
|
+
file,
|
|
11
|
+
line: source?.line,
|
|
12
|
+
column: source?.column,
|
|
13
|
+
dataPath,
|
|
14
|
+
expected: formatCheckedType(target),
|
|
15
|
+
actual: runtimeDescription(actual),
|
|
16
|
+
fieldSource
|
|
17
|
+
});
|
|
18
|
+
diagnostics.push(diagnostic);
|
|
19
|
+
if (env.validationMode === 'fail-fast')
|
|
20
|
+
throwInputErrors([diagnostic]);
|
|
21
|
+
};
|
|
22
|
+
const visit = (actual, target, dataPath, fieldSource) => {
|
|
23
|
+
if (target.kind === 'null') {
|
|
24
|
+
if (actual !== null)
|
|
25
|
+
report('Expected null', target, actual, dataPath, fieldSource);
|
|
26
|
+
return;
|
|
27
|
+
}
|
|
28
|
+
if (target.kind === 'nullable') {
|
|
29
|
+
if (actual !== null)
|
|
30
|
+
visit(actual, target.element, dataPath, fieldSource);
|
|
31
|
+
return;
|
|
32
|
+
}
|
|
33
|
+
if (target.kind === 'list') {
|
|
34
|
+
if (!Array.isArray(actual)) {
|
|
35
|
+
report('Expected a list value', target, actual, dataPath, fieldSource);
|
|
36
|
+
return;
|
|
37
|
+
}
|
|
38
|
+
actual.forEach((item, index) => visit(item, target.element, `${dataPath}[${index}]`, fieldSource));
|
|
39
|
+
return;
|
|
40
|
+
}
|
|
41
|
+
if (target.kind === 'measurement') {
|
|
42
|
+
if (!isMeasurement(actual)) {
|
|
43
|
+
report('Expected a measurement value', target, actual, dataPath, fieldSource);
|
|
44
|
+
return;
|
|
45
|
+
}
|
|
46
|
+
const vector = actual.unit.vector;
|
|
47
|
+
if (Object.keys(vector).length !== target.vector.size
|
|
48
|
+
|| [...target.vector].some(([identity, exponent]) => vector[identity] !== exponent)) {
|
|
49
|
+
report('Measurement dimension does not match the declared dimension', target, actual, dataPath, fieldSource);
|
|
50
|
+
}
|
|
51
|
+
if (!Number.isFinite(actual.value) || !Number.isFinite(actual.value * actual.unit.scale)) {
|
|
52
|
+
report('Measurement value must be finite', target, actual, dataPath, fieldSource);
|
|
53
|
+
}
|
|
54
|
+
return;
|
|
55
|
+
}
|
|
56
|
+
if (target.kind !== 'named')
|
|
57
|
+
return;
|
|
58
|
+
if (target.name === 'Number') {
|
|
59
|
+
if (typeof actual !== 'number' || !Number.isFinite(actual))
|
|
60
|
+
report('Expected a finite Number value', target, actual, dataPath, fieldSource);
|
|
61
|
+
return;
|
|
62
|
+
}
|
|
63
|
+
if (target.name === 'String' || target.name === 'DateTime') {
|
|
64
|
+
if (typeof actual !== 'string')
|
|
65
|
+
report(`Expected a ${target.name} value`, target, actual, dataPath, fieldSource);
|
|
66
|
+
else if (target.name === 'DateTime' && !validDateTime(actual))
|
|
67
|
+
report('Invalid RFC 3339 DateTime value', target, actual, dataPath, fieldSource);
|
|
68
|
+
return;
|
|
69
|
+
}
|
|
70
|
+
if (target.name === 'Boolean') {
|
|
71
|
+
if (typeof actual !== 'boolean')
|
|
72
|
+
report('Expected a Boolean value', target, actual, dataPath, fieldSource);
|
|
73
|
+
return;
|
|
74
|
+
}
|
|
75
|
+
const declaration = env.recordTypes.get(target.name);
|
|
76
|
+
if (!declaration || typeof actual !== 'object' || actual === null || Array.isArray(actual)) {
|
|
77
|
+
report(`Expected a ${target.name} record`, target, actual, dataPath, fieldSource);
|
|
78
|
+
return;
|
|
79
|
+
}
|
|
80
|
+
const record = actual;
|
|
81
|
+
const fieldNames = new Set(declaration.fields.map(field => field.name));
|
|
82
|
+
const recordRegistry = fieldRegistry(declaration, env.dimensionRegistry);
|
|
83
|
+
for (const field of declaration.fields) {
|
|
84
|
+
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
|
+
}
|
|
87
|
+
else {
|
|
88
|
+
visit(record[field.name], checkedType(field.annotation, recordRegistry), `${dataPath}.${field.name}`, field.source);
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
for (const name of Object.keys(record).filter(name => !fieldNames.has(name)).sort()) {
|
|
92
|
+
report(`Unknown computed field '${name}'`, target, record[name], `${dataPath}.${name}`, fieldSource);
|
|
93
|
+
}
|
|
94
|
+
};
|
|
95
|
+
visit(value, expected, valuePath);
|
|
96
|
+
if (diagnostics.length)
|
|
97
|
+
throwInputErrors(diagnostics);
|
|
98
|
+
}
|
|
99
|
+
function checkedType(reference, scope) {
|
|
100
|
+
const registry = scope instanceof Environment ? scope.dimensionRegistry : scope;
|
|
101
|
+
if (reference.type === 'namedType') {
|
|
102
|
+
const dimension = registry?.dimensions.get(reference.name);
|
|
103
|
+
return dimension ? { kind: 'measurement', vector: dimension.vector } : { kind: 'named', name: reference.name };
|
|
104
|
+
}
|
|
105
|
+
const element = checkedType(reference.element, registry);
|
|
106
|
+
return reference.type === 'listType' ? { kind: 'list', element } : { kind: 'nullable', element };
|
|
107
|
+
}
|
|
108
|
+
function formatCheckedType(type) {
|
|
109
|
+
if (type.kind === 'named')
|
|
110
|
+
return type.name;
|
|
111
|
+
if (type.kind === 'measurement')
|
|
112
|
+
return 'measurement';
|
|
113
|
+
if (type.kind === 'null')
|
|
114
|
+
return 'null';
|
|
115
|
+
return type.kind === 'list' ? `${formatCheckedType(type.element)}[]` : `${formatCheckedType(type.element)}?`;
|
|
116
|
+
}
|
|
117
|
+
function runtimeDescription(value) {
|
|
118
|
+
if (typeof value === 'number' && !Number.isFinite(value))
|
|
119
|
+
return String(value);
|
|
120
|
+
let description;
|
|
121
|
+
try {
|
|
122
|
+
description = JSON.stringify(value) ?? String(value);
|
|
123
|
+
}
|
|
124
|
+
catch {
|
|
125
|
+
description = String(value);
|
|
126
|
+
}
|
|
127
|
+
return description.replace(/[\x00-\x1f\x7f]/g, character => `\\u${character.charCodeAt(0).toString(16).padStart(4, '0')}`).slice(0, 160);
|
|
128
|
+
}
|
|
129
|
+
function sameMeasurementVector(value, vector) {
|
|
130
|
+
return Object.keys(value.unit.vector).length === vector.size
|
|
131
|
+
&& [...vector].every(([identity, exponent]) => value.unit.vector[identity] === exponent);
|
|
132
|
+
}
|
|
133
|
+
function validDateTime(value) {
|
|
134
|
+
const parts = value.match(/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.\d{1,9})?(Z|[+-]\d{2}:\d{2})$/);
|
|
135
|
+
if (!parts)
|
|
136
|
+
return false;
|
|
137
|
+
const [, year, month, day, hour, minute, second, offset] = parts;
|
|
138
|
+
const date = new Date(0);
|
|
139
|
+
date.setUTCFullYear(+year, +month - 1, +day);
|
|
140
|
+
return date.getUTCFullYear() === +year && date.getUTCMonth() === +month - 1 && date.getUTCDate() === +day
|
|
141
|
+
&& +hour <= 23 && +minute <= 59 && +second <= 59
|
|
142
|
+
&& (offset === 'Z' || (+offset.slice(1, 3) <= 23 && +offset.slice(4) <= 59));
|
|
143
|
+
}
|
|
144
|
+
/** Evaluate V0.2 expressions, including ranges and expression-form loops. */
|
|
145
|
+
export function evaluateExpression(node, env, file) {
|
|
146
|
+
switch (node.type) {
|
|
147
|
+
case 'nullLiteral':
|
|
148
|
+
return null;
|
|
149
|
+
case 'recordConstructor': {
|
|
150
|
+
const declaration = env.recordTypes.get(node.name);
|
|
151
|
+
if (!declaration)
|
|
152
|
+
throw new Error(`Unknown record type '${node.name}'`);
|
|
153
|
+
const supplied = new Map(node.fields.map(field => [field.name, evaluateExpression(field.expression, env, file)]));
|
|
154
|
+
const record = {};
|
|
155
|
+
for (const field of declaration.fields) {
|
|
156
|
+
record[field.name] = supplied.has(field.name) ? supplied.get(field.name)
|
|
157
|
+
: field.defaultExpression ? evaluateExpression(field.defaultExpression, env, file) : null;
|
|
158
|
+
}
|
|
159
|
+
validateRuntimeValue(record, { kind: 'named', name: node.name }, env, node.source, file, `record ${node.name}`);
|
|
160
|
+
return record;
|
|
161
|
+
}
|
|
162
|
+
case 'fieldAccess':
|
|
163
|
+
return evaluateExpression(node.receiver, env, file)[node.field];
|
|
164
|
+
case 'listAccess':
|
|
165
|
+
return evalListAccess(node, env, file);
|
|
166
|
+
case 'numberLiteral':
|
|
167
|
+
return node.value;
|
|
168
|
+
case 'stringLiteral':
|
|
169
|
+
return node.value;
|
|
170
|
+
case 'stringInterpolation':
|
|
171
|
+
return node.parts.map(part => {
|
|
172
|
+
if (typeof part === 'string')
|
|
173
|
+
return part;
|
|
174
|
+
const value = evaluateExpression(part, env, file);
|
|
175
|
+
if (value === null)
|
|
176
|
+
return 'null';
|
|
177
|
+
if (typeof value === 'string' || typeof value === 'number')
|
|
178
|
+
return String(value);
|
|
179
|
+
if (typeof value === 'boolean')
|
|
180
|
+
return value ? 'true' : 'false';
|
|
181
|
+
if (isMeasurement(value))
|
|
182
|
+
return `${String(value.value)} ${value.unit.text}`;
|
|
183
|
+
return staticError('AMX3007', 'Only String, Number, Boolean, measurement, and null values can be interpolated', part.source, file);
|
|
184
|
+
}).join('');
|
|
185
|
+
case 'booleanLiteral':
|
|
186
|
+
return node.value;
|
|
187
|
+
case 'identifier':
|
|
188
|
+
// Pass source location for better diagnostics
|
|
189
|
+
return env.get(node.name, node.source, file);
|
|
190
|
+
case 'measurementAttachment': {
|
|
191
|
+
const value = evaluateExpression(node.value, env, file);
|
|
192
|
+
const unit = env.dimensionRegistry?.units.get(node.unit);
|
|
193
|
+
if (!unit)
|
|
194
|
+
return staticError('AMX3008', `Unknown or invisible unit '${node.unit}'`, node.unitSource ?? node.source, file);
|
|
195
|
+
if (typeof value !== 'number')
|
|
196
|
+
return staticError('AMX3007', 'Unit attachment requires a Number expression', node.source, file);
|
|
197
|
+
const result = measurement(value, unitFromMetadata(unit));
|
|
198
|
+
if (!Number.isFinite(result.value * result.unit.scale)) {
|
|
199
|
+
throwMeasurementDomainError('Measurement physical value must be finite', node.source, file);
|
|
200
|
+
}
|
|
201
|
+
return result;
|
|
202
|
+
}
|
|
203
|
+
case 'measurementConversion': {
|
|
204
|
+
const value = evaluateExpression(node.value, env, file);
|
|
205
|
+
const unit = env.dimensionRegistry?.units.get(node.unit);
|
|
206
|
+
if (!unit)
|
|
207
|
+
return staticError('AMX3008', `Unknown or invisible unit '${node.unit}'`, node.unitSource ?? node.source, file);
|
|
208
|
+
if (!isMeasurement(value) || !sameMeasurementVector(value, unit.vector)) {
|
|
209
|
+
return staticError('AMX3007', `Cannot convert value to unit '${node.unit}'`, node.source, file);
|
|
210
|
+
}
|
|
211
|
+
const converted = value.value * value.unit.scale / unit.scale;
|
|
212
|
+
if (!Number.isFinite(converted))
|
|
213
|
+
throwMeasurementDomainError('Converted measurement value must be finite', node.source, file);
|
|
214
|
+
return measurement(converted, unitFromMetadata(unit));
|
|
215
|
+
}
|
|
216
|
+
case 'binaryExpression':
|
|
217
|
+
return evalBinary(node, env, file);
|
|
218
|
+
case 'unaryExpression':
|
|
219
|
+
return evalUnary(node, env, file);
|
|
220
|
+
case 'conditionalExpression':
|
|
221
|
+
return evalConditional(node, env, file);
|
|
222
|
+
case 'listLiteral':
|
|
223
|
+
return evalListLiteral(node, env, file);
|
|
224
|
+
case 'functionCall':
|
|
225
|
+
return evalFunctionCall(node, env, file);
|
|
226
|
+
case 'rangeExpression':
|
|
227
|
+
return evalRange(node, env, file);
|
|
228
|
+
case 'forExpression':
|
|
229
|
+
return evalForExpression(node, env, file);
|
|
230
|
+
case 'matchExpression':
|
|
231
|
+
return evalMatch(node, env, file);
|
|
232
|
+
default: {
|
|
233
|
+
// Exhaustiveness check: if a new node type is added without a case, this will fail to compile.
|
|
234
|
+
const _exhaustive = node;
|
|
235
|
+
throw new Error(`Unsupported expression node type: ${_exhaustive}`);
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
function evalMatch(node, env, file) {
|
|
240
|
+
const value = evaluateExpression(node.expression, env, file);
|
|
241
|
+
for (const arm of node.cases) {
|
|
242
|
+
if (value === arm.value.value)
|
|
243
|
+
return evaluateExpression(arm.expression, env, file);
|
|
244
|
+
}
|
|
245
|
+
return evaluateExpression(node.defaultExpression, env, file);
|
|
246
|
+
}
|
|
247
|
+
function evalBinary(node, env, file) {
|
|
248
|
+
const left = evaluateExpression(node.left, env, file);
|
|
249
|
+
const right = evaluateExpression(node.right, env, file);
|
|
250
|
+
const operatorSource = node.operatorSource ?? node.source;
|
|
251
|
+
switch (node.operator) {
|
|
252
|
+
// Arithmetic (numeric)
|
|
253
|
+
case '+':
|
|
254
|
+
case '-': {
|
|
255
|
+
if (isMeasurement(left) || isMeasurement(right)) {
|
|
256
|
+
if (!isMeasurement(left) || !isMeasurement(right) || !sameMeasurementVector(left, new Map(Object.entries(right.unit.vector)))) {
|
|
257
|
+
return staticError('AMX3007', 'Addition and subtraction require compatible measurements', operatorSource, file);
|
|
258
|
+
}
|
|
259
|
+
const physicalLeft = left.value * left.unit.scale;
|
|
260
|
+
const physicalRight = right.value * right.unit.scale;
|
|
261
|
+
const physical = node.operator === '+' ? physicalLeft + physicalRight : physicalLeft - physicalRight;
|
|
262
|
+
const value = physical / left.unit.scale;
|
|
263
|
+
if (!Number.isFinite(value) || !Number.isFinite(physical)) {
|
|
264
|
+
throwMeasurementDomainError('Measurement arithmetic result must be finite', operatorSource, file);
|
|
265
|
+
}
|
|
266
|
+
return measurement(value, left.unit);
|
|
267
|
+
}
|
|
268
|
+
const lNum = toNumber(left, node.left);
|
|
269
|
+
const rNum = toNumber(right, node.right);
|
|
270
|
+
return node.operator === '+' ? lNum + rNum : lNum - rNum;
|
|
271
|
+
}
|
|
272
|
+
case '*':
|
|
273
|
+
case '/': {
|
|
274
|
+
if (isMeasurement(left) || isMeasurement(right)) {
|
|
275
|
+
const numberUnit = { scale: 1, vector: {}, factors: [], text: '1' };
|
|
276
|
+
const leftMeasurement = isMeasurement(left) ? left : undefined;
|
|
277
|
+
const rightMeasurement = isMeasurement(right) ? right : undefined;
|
|
278
|
+
const leftValue = leftMeasurement ? leftMeasurement.value : toNumber(left, node.left);
|
|
279
|
+
const rightValue = rightMeasurement ? rightMeasurement.value : toNumber(right, node.right);
|
|
280
|
+
const leftUnit = leftMeasurement?.unit ?? numberUnit;
|
|
281
|
+
const rightUnit = rightMeasurement?.unit ?? numberUnit;
|
|
282
|
+
const rightPhysical = rightValue * rightUnit.scale;
|
|
283
|
+
if (node.operator === '/' && rightPhysical === 0) {
|
|
284
|
+
throwMeasurementDomainError('Measurement division by zero', operatorSource, file);
|
|
285
|
+
}
|
|
286
|
+
const unit = composeUnits(leftUnit, rightUnit, node.operator === '/');
|
|
287
|
+
const physical = node.operator === '/'
|
|
288
|
+
? leftValue * leftUnit.scale / rightPhysical
|
|
289
|
+
: leftValue * leftUnit.scale * rightValue * rightUnit.scale;
|
|
290
|
+
if (unit.vector && Object.keys(unit.vector).length === 0) {
|
|
291
|
+
if (!Number.isFinite(physical))
|
|
292
|
+
throwMeasurementDomainError('Measurement arithmetic result must be finite', operatorSource, file);
|
|
293
|
+
return physical;
|
|
294
|
+
}
|
|
295
|
+
const value = node.operator === '/' ? leftValue / rightValue : leftValue * rightValue;
|
|
296
|
+
if (!Number.isFinite(unit.scale) || unit.scale <= 0 || !Number.isFinite(value) || !Number.isFinite(physical)) {
|
|
297
|
+
throwMeasurementDomainError('Measurement arithmetic result must be finite', operatorSource, file);
|
|
298
|
+
}
|
|
299
|
+
return measurement(value, unit);
|
|
300
|
+
}
|
|
301
|
+
const lNum = toNumber(left, node.left);
|
|
302
|
+
const rNum = toNumber(right, node.right);
|
|
303
|
+
return node.operator === '*' ? lNum * rNum : lNum / rNum;
|
|
304
|
+
}
|
|
305
|
+
case '%': {
|
|
306
|
+
const lNum = toNumber(left, node.left);
|
|
307
|
+
const rNum = toNumber(right, node.right);
|
|
308
|
+
return lNum % rNum;
|
|
309
|
+
}
|
|
310
|
+
case '^': {
|
|
311
|
+
if (isMeasurement(left)) {
|
|
312
|
+
const exponent = toNumber(right, node.right);
|
|
313
|
+
if (!Number.isSafeInteger(exponent)) {
|
|
314
|
+
return staticError('AMX3007', 'A dimensional power exponent must be an integer literal', node.right.source, file);
|
|
315
|
+
}
|
|
316
|
+
if (left.value === 0 && exponent < 0) {
|
|
317
|
+
throwMeasurementDomainError('Zero measurement cannot be raised to a negative power', operatorSource, file);
|
|
318
|
+
}
|
|
319
|
+
const unit = powerUnit(left.unit, exponent);
|
|
320
|
+
const value = Math.pow(left.value, exponent);
|
|
321
|
+
if (!Number.isFinite(value) || !Number.isFinite(unit.scale)) {
|
|
322
|
+
throwMeasurementDomainError('Measurement power result must be finite', operatorSource, file);
|
|
323
|
+
}
|
|
324
|
+
if (Object.keys(unit.vector).length === 0)
|
|
325
|
+
return value * unit.scale;
|
|
326
|
+
return measurement(value, unit);
|
|
327
|
+
}
|
|
328
|
+
const lNum = toNumber(left, node.left);
|
|
329
|
+
const rNum = toNumber(right, node.right);
|
|
330
|
+
return Math.pow(lNum, rNum);
|
|
331
|
+
}
|
|
332
|
+
// Comparisons (produce boolean)
|
|
333
|
+
case '==':
|
|
334
|
+
if (isMeasurement(left) && isMeasurement(right)) {
|
|
335
|
+
return sameMeasurementVector(left, new Map(Object.entries(right.unit.vector)))
|
|
336
|
+
&& left.value * left.unit.scale === right.value * right.unit.scale;
|
|
337
|
+
}
|
|
338
|
+
return left === right;
|
|
339
|
+
case '!=':
|
|
340
|
+
if (isMeasurement(left) && isMeasurement(right)) {
|
|
341
|
+
return !sameMeasurementVector(left, new Map(Object.entries(right.unit.vector)))
|
|
342
|
+
|| left.value * left.unit.scale !== right.value * right.unit.scale;
|
|
343
|
+
}
|
|
344
|
+
return left !== right;
|
|
345
|
+
case '>':
|
|
346
|
+
if (isMeasurement(left) && isMeasurement(right))
|
|
347
|
+
return left.value * left.unit.scale > right.value * right.unit.scale;
|
|
348
|
+
return toNumber(left, node.left) > toNumber(right, node.right);
|
|
349
|
+
case '>=':
|
|
350
|
+
if (isMeasurement(left) && isMeasurement(right))
|
|
351
|
+
return left.value * left.unit.scale >= right.value * right.unit.scale;
|
|
352
|
+
return toNumber(left, node.left) >= toNumber(right, node.right);
|
|
353
|
+
case '<':
|
|
354
|
+
if (isMeasurement(left) && isMeasurement(right))
|
|
355
|
+
return left.value * left.unit.scale < right.value * right.unit.scale;
|
|
356
|
+
return toNumber(left, node.left) < toNumber(right, node.right);
|
|
357
|
+
case '<=':
|
|
358
|
+
if (isMeasurement(left) && isMeasurement(right))
|
|
359
|
+
return left.value * left.unit.scale <= right.value * right.unit.scale;
|
|
360
|
+
return toNumber(left, node.left) <= toNumber(right, node.right);
|
|
361
|
+
// Logical (short-circuit not required for simple impl; evaluate both then apply)
|
|
362
|
+
case 'and':
|
|
363
|
+
return toBoolean(left) && toBoolean(right);
|
|
364
|
+
case 'or':
|
|
365
|
+
return toBoolean(left) || toBoolean(right);
|
|
366
|
+
default:
|
|
367
|
+
throw new Error(`Unsupported binary operator: ${node.operator}`);
|
|
368
|
+
}
|
|
369
|
+
}
|
|
370
|
+
function evalUnary(node, env, file) {
|
|
371
|
+
const arg = evaluateExpression(node.argument, env, file);
|
|
372
|
+
if (node.operator === '-') {
|
|
373
|
+
if (isMeasurement(arg))
|
|
374
|
+
return measurement(-arg.value, arg.unit);
|
|
375
|
+
return -toNumber(arg, node.argument);
|
|
376
|
+
}
|
|
377
|
+
if (node.operator === 'not') {
|
|
378
|
+
return !toBoolean(arg);
|
|
379
|
+
}
|
|
380
|
+
throw new Error(`Unsupported unary operator: ${node.operator}`);
|
|
381
|
+
}
|
|
382
|
+
function evalConditional(node, env, file) {
|
|
383
|
+
const testVal = evaluateExpression(node.test, env, file);
|
|
384
|
+
return toBoolean(testVal)
|
|
385
|
+
? evaluateExpression(node.consequent, env, file)
|
|
386
|
+
: evaluateExpression(node.alternate, env, file);
|
|
387
|
+
}
|
|
388
|
+
function evalListLiteral(node, env, file) {
|
|
389
|
+
return node.elements.map(el => evaluateExpression(el, env, file));
|
|
390
|
+
}
|
|
391
|
+
function evalListAccess(node, env, file) {
|
|
392
|
+
const receiver = evaluateExpression(node.receiver, env, file);
|
|
393
|
+
const index = evaluateExpression(node.index, env, file);
|
|
394
|
+
if (!Array.isArray(receiver)) {
|
|
395
|
+
throwListOperationError('List access requires a list value', node.source, file);
|
|
396
|
+
}
|
|
397
|
+
if (typeof index !== 'number' || !Number.isFinite(index) || !Number.isInteger(index) || index < 1) {
|
|
398
|
+
throwListOperationError(`List index must be a positive integer; got ${runtimeDescription(index)}`, node.index.source ?? node.source, file);
|
|
399
|
+
}
|
|
400
|
+
if (index > receiver.length) {
|
|
401
|
+
throwListOperationError(`List index ${index} is out of bounds for length ${receiver.length}; expected 1..${receiver.length}`, node.index.source ?? node.source, file);
|
|
402
|
+
}
|
|
403
|
+
return receiver[index - 1];
|
|
404
|
+
}
|
|
405
|
+
function evalFunctionCall(node, env, file) {
|
|
406
|
+
const args = node.arguments.map(a => evaluateExpression(a, env, file));
|
|
407
|
+
const userFunction = env.functions.get(node.callee);
|
|
408
|
+
if (userFunction) {
|
|
409
|
+
const functionRegistry = fieldRegistry(userFunction, env.dimensionRegistry);
|
|
410
|
+
const parameters = {};
|
|
411
|
+
userFunction.parameters.forEach((parameter, index) => {
|
|
412
|
+
validateRuntimeValue(args[index], checkedType(parameter.annotation, functionRegistry), env, node.arguments[index]?.source ?? node.source, file, `function ${node.callee}.${parameter.name}`);
|
|
413
|
+
parameters[parameter.name] = args[index];
|
|
414
|
+
});
|
|
415
|
+
const frame = env.createCallFrame(parameters);
|
|
416
|
+
frame.dimensionRegistry = functionRegistry;
|
|
417
|
+
userFunction.parameters.forEach(parameter => {
|
|
418
|
+
frame.bindingTypes.set(parameter.name, checkedType(parameter.annotation, functionRegistry));
|
|
419
|
+
});
|
|
420
|
+
const result = evaluateExpression(userFunction.body, frame, file);
|
|
421
|
+
validateRuntimeValue(result, checkedType(userFunction.returnType, functionRegistry), env, node.source, file, `function ${node.callee} return`);
|
|
422
|
+
return result;
|
|
423
|
+
}
|
|
424
|
+
const values = args[0];
|
|
425
|
+
if (['sum', 'mean', 'min', 'max'].includes(node.callee) && Array.isArray(values)
|
|
426
|
+
&& (values.length > 0 && isMeasurement(values[0]))) {
|
|
427
|
+
const measurements = values;
|
|
428
|
+
const first = measurements[0];
|
|
429
|
+
for (const current of measurements) {
|
|
430
|
+
if (!sameMeasurementVector(first, new Map(Object.entries(current.unit.vector)))) {
|
|
431
|
+
return staticError('AMX3007', `${node.callee} requires compatible measurement dimensions`, node.source, file);
|
|
432
|
+
}
|
|
433
|
+
if (Array.isArray(values) && values.length > 0 && typeof values[0] === 'number'
|
|
434
|
+
&& ['sum', 'mean', 'min', 'max'].includes(node.callee)) {
|
|
435
|
+
return evaluateStandardLibraryCall(node.callee, args, node.source, file);
|
|
436
|
+
}
|
|
437
|
+
}
|
|
438
|
+
if (node.callee === 'min' || node.callee === 'max') {
|
|
439
|
+
if (!measurements.length)
|
|
440
|
+
return evaluateStandardLibraryCall(node.callee, args, node.source, file);
|
|
441
|
+
return measurements.reduce((best, current) => {
|
|
442
|
+
const better = node.callee === 'min'
|
|
443
|
+
? current.value * current.unit.scale < best.value * best.unit.scale
|
|
444
|
+
: current.value * current.unit.scale > best.value * best.unit.scale;
|
|
445
|
+
return better ? current : best;
|
|
446
|
+
});
|
|
447
|
+
}
|
|
448
|
+
const physicalSum = measurements.reduce((sum, current) => sum + current.value * current.unit.scale, 0);
|
|
449
|
+
const value = (node.callee === 'mean' ? physicalSum / measurements.length : physicalSum) / first.unit.scale;
|
|
450
|
+
if (!Number.isFinite(value))
|
|
451
|
+
throwMeasurementDomainError(`${node.callee} result must be finite`, node.source, file);
|
|
452
|
+
return measurement(value, first.unit);
|
|
453
|
+
}
|
|
454
|
+
if (node.callee === 'sum' && Array.isArray(values) && values.length === 0
|
|
455
|
+
&& node.arguments[0]?.type === 'identifier') {
|
|
456
|
+
const type = env.bindingTypes.get(node.arguments[0].name);
|
|
457
|
+
if (type?.kind === 'list' && type.element.kind === 'measurement' && env.dimensionRegistry) {
|
|
458
|
+
return measurement(0, canonicalUnit(type.element.vector, env.dimensionRegistry));
|
|
459
|
+
}
|
|
460
|
+
}
|
|
461
|
+
if (isMeasurement(args[0])) {
|
|
462
|
+
const value = args[0];
|
|
463
|
+
switch (node.callee) {
|
|
464
|
+
case 'abs':
|
|
465
|
+
return measurement(Math.abs(value.value), value.unit);
|
|
466
|
+
case 'round': {
|
|
467
|
+
const digits = args.length > 1 ? toNumber(args[1], node.arguments[1]) : 0;
|
|
468
|
+
const factor = Math.pow(10, Math.trunc(digits));
|
|
469
|
+
const rounded = Math.round(value.value * factor) / factor;
|
|
470
|
+
if (!Number.isFinite(rounded))
|
|
471
|
+
throwMeasurementDomainError('round result must be finite', node.source, file);
|
|
472
|
+
return measurement(rounded, value.unit);
|
|
473
|
+
}
|
|
474
|
+
case 'sqrt': {
|
|
475
|
+
const physical = value.value * value.unit.scale;
|
|
476
|
+
if (physical < 0)
|
|
477
|
+
throwMeasurementDomainError('sqrt of a negative measurement value', node.source, file);
|
|
478
|
+
if (!env.dimensionRegistry)
|
|
479
|
+
throw new Error('Measurement registry is unavailable during sqrt evaluation');
|
|
480
|
+
try {
|
|
481
|
+
const result = sqrtMeasurement(value, env.dimensionRegistry);
|
|
482
|
+
if (!Number.isFinite(result.value) || !Number.isFinite(result.unit.scale)) {
|
|
483
|
+
throwMeasurementDomainError('sqrt result must be finite', node.source, file);
|
|
484
|
+
}
|
|
485
|
+
if (Object.keys(result.unit.vector).length === 0)
|
|
486
|
+
return result.value * result.unit.scale;
|
|
487
|
+
return result;
|
|
488
|
+
}
|
|
489
|
+
catch (error) {
|
|
490
|
+
if (error instanceof Error && error.message.startsWith('sqrt requires')) {
|
|
491
|
+
return staticError('AMX3007', error.message, node.source, file);
|
|
492
|
+
}
|
|
493
|
+
throw error;
|
|
494
|
+
}
|
|
495
|
+
}
|
|
496
|
+
case 'pow': {
|
|
497
|
+
const exponent = toNumber(args[1], node.arguments[1]);
|
|
498
|
+
if (!Number.isSafeInteger(exponent))
|
|
499
|
+
return staticError('AMX3007', 'A dimensional pow exponent must be an integer literal', node.arguments[1]?.source, file);
|
|
500
|
+
if (value.value === 0 && exponent < 0)
|
|
501
|
+
throwMeasurementDomainError('Zero measurement cannot be raised to a negative power', node.source, file);
|
|
502
|
+
const unit = powerUnit(value.unit, exponent);
|
|
503
|
+
const result = Math.pow(value.value, exponent);
|
|
504
|
+
if (!Number.isFinite(result) || !Number.isFinite(unit.scale))
|
|
505
|
+
throwMeasurementDomainError('pow result must be finite', node.source, file);
|
|
506
|
+
if (!Object.keys(unit.vector).length)
|
|
507
|
+
return result * unit.scale;
|
|
508
|
+
return measurement(result, unit);
|
|
509
|
+
}
|
|
510
|
+
}
|
|
511
|
+
}
|
|
512
|
+
return evaluateStandardLibraryCall(node.callee, args, node.source, file);
|
|
513
|
+
}
|
|
514
|
+
function toNumber(v, nodeForError) {
|
|
515
|
+
if (typeof v === 'number')
|
|
516
|
+
return v;
|
|
517
|
+
if (typeof v === 'boolean')
|
|
518
|
+
return v ? 1 : 0;
|
|
519
|
+
if (typeof v === 'string') {
|
|
520
|
+
const n = Number(v);
|
|
521
|
+
if (!Number.isNaN(n))
|
|
522
|
+
return n;
|
|
523
|
+
}
|
|
524
|
+
const loc = nodeForError?.source;
|
|
525
|
+
const locInfo = loc ? ` at line ${loc.line}` : '';
|
|
526
|
+
throw new Error(`Cannot convert value to number${locInfo}`);
|
|
527
|
+
}
|
|
528
|
+
function toBoolean(v) {
|
|
529
|
+
if (typeof v === 'boolean')
|
|
530
|
+
return v;
|
|
531
|
+
if (typeof v === 'number')
|
|
532
|
+
return v !== 0;
|
|
533
|
+
if (typeof v === 'string')
|
|
534
|
+
return v.length > 0;
|
|
535
|
+
// Treat non-empty arrays/objects as truthy for list/aggregate contexts
|
|
536
|
+
if (Array.isArray(v))
|
|
537
|
+
return v.length > 0;
|
|
538
|
+
if (v && typeof v === 'object')
|
|
539
|
+
return true;
|
|
540
|
+
return false;
|
|
541
|
+
}
|
|
542
|
+
export function evaluateStatements(statements, env, file) {
|
|
543
|
+
const priorStatementIndex = env.currentStatementIndex;
|
|
544
|
+
try {
|
|
545
|
+
for (let statementIndex = 0; statementIndex < statements.length; statementIndex++) {
|
|
546
|
+
env.currentStatementIndex = statementIndex;
|
|
547
|
+
evaluateStatement(statements[statementIndex], env, file);
|
|
548
|
+
}
|
|
549
|
+
}
|
|
550
|
+
finally {
|
|
551
|
+
env.currentStatementIndex = priorStatementIndex;
|
|
552
|
+
}
|
|
553
|
+
}
|
|
554
|
+
function snapshotValue(value) {
|
|
555
|
+
if (isMeasurement(value))
|
|
556
|
+
return `${value.value} ${value.unit.text}`;
|
|
557
|
+
if (Array.isArray(value))
|
|
558
|
+
return Object.freeze(value.map(snapshotValue));
|
|
559
|
+
if (value && typeof value === 'object') {
|
|
560
|
+
const copy = {};
|
|
561
|
+
for (const [key, item] of Object.entries(value))
|
|
562
|
+
copy[key] = snapshotValue(item);
|
|
563
|
+
return Object.freeze(copy);
|
|
564
|
+
}
|
|
565
|
+
return value;
|
|
566
|
+
}
|
|
567
|
+
function snapshotView(name, env, file, source) {
|
|
568
|
+
const declaration = env.viewDefinitions.get(name);
|
|
569
|
+
if (!declaration)
|
|
570
|
+
return staticError('AMX3001', `Unknown visualization '${name}'`, source, file);
|
|
571
|
+
const value = env.get(declaration.binding, declaration.bindingSource, file);
|
|
572
|
+
if (!Array.isArray(value)) {
|
|
573
|
+
const diagnostic = inputError('AMX4003', `Visualization '${name}' requires a list value`, {
|
|
574
|
+
file, line: declaration.bindingSource?.line, column: declaration.bindingSource?.column,
|
|
575
|
+
dataPath: `visualization ${name}`, expected: 'list', actual: Array.isArray(value) ? 'list' : typeof value
|
|
576
|
+
});
|
|
577
|
+
throwInputErrors([diagnostic]);
|
|
578
|
+
}
|
|
579
|
+
let labels;
|
|
580
|
+
let headings;
|
|
581
|
+
let measurementDescriptors;
|
|
582
|
+
let viewData;
|
|
583
|
+
if (declaration.type === 'chartDeclaration') {
|
|
584
|
+
const labelsOption = declaration.options.find(option => option.type === 'chartFieldOption' && option.role === 'labels');
|
|
585
|
+
if (labelsOption?.type === 'chartFieldOption') {
|
|
586
|
+
const labelValues = env.get(labelsOption.field, labelsOption.fieldSource, file);
|
|
587
|
+
if (!Array.isArray(labelValues) || !labelValues.every(label => typeof label === 'string')) {
|
|
588
|
+
const diagnostic = inputError('AMX4003', `Chart '${name}' labels must be a String[] value`, {
|
|
589
|
+
file, line: labelsOption.source?.line, column: labelsOption.source?.column,
|
|
590
|
+
dataPath: `visualization ${name}.labels`, expected: 'String[]', actual: Array.isArray(labelValues) ? 'invalid list value' : typeof labelValues
|
|
591
|
+
});
|
|
592
|
+
throwInputErrors([diagnostic]);
|
|
593
|
+
}
|
|
594
|
+
if (labelValues.length !== value.length) {
|
|
595
|
+
const diagnostic = inputError('AMX4003', `Chart '${name}' has ${value.length} values but ${labelValues.length} labels`, {
|
|
596
|
+
file, line: labelsOption.source?.line, column: labelsOption.source?.column,
|
|
597
|
+
dataPath: `visualization ${name}.labels`, expected: `${value.length} labels`, actual: `${labelValues.length} labels`
|
|
598
|
+
});
|
|
599
|
+
throwInputErrors([diagnostic]);
|
|
600
|
+
}
|
|
601
|
+
labels = snapshotValue(labelValues);
|
|
602
|
+
}
|
|
603
|
+
const normalized = normalizeChartMeasurements(value, declaration, name, file);
|
|
604
|
+
viewData = normalized.data;
|
|
605
|
+
headings = normalized.headings;
|
|
606
|
+
measurementDescriptors = normalized.measurementDescriptors;
|
|
607
|
+
}
|
|
608
|
+
else {
|
|
609
|
+
viewData = snapshotValue(value);
|
|
610
|
+
}
|
|
611
|
+
const emission = {
|
|
612
|
+
name, data: viewData,
|
|
613
|
+
documentNodeIndex: env.currentDocumentNodeIndex, statementIndex: env.currentStatementIndex, source
|
|
614
|
+
};
|
|
615
|
+
return declaration.type === 'tableDeclaration'
|
|
616
|
+
? Object.freeze({ kind: 'table', ...emission, declaration })
|
|
617
|
+
: Object.freeze({
|
|
618
|
+
kind: 'chart', ...emission, declaration,
|
|
619
|
+
...(labels ? { labels } : {}), ...(headings ? { headings } : {}),
|
|
620
|
+
...(measurementDescriptors?.length ? { measurementDescriptors } : {})
|
|
621
|
+
});
|
|
622
|
+
}
|
|
623
|
+
function normalizeChartMeasurements(data, declaration, name, file) {
|
|
624
|
+
const scatter = declaration.kind === 'scatter';
|
|
625
|
+
const selectedColumns = scatter
|
|
626
|
+
? declaration.options
|
|
627
|
+
.filter((option) => option.type === 'chartFieldOption' && (option.role === 'x' || option.role === 'y'))
|
|
628
|
+
.map(option => ({ role: option.role, field: option.field, label: option.role, source: option.source }))
|
|
629
|
+
: declaration.options
|
|
630
|
+
.filter((option) => option.type === 'chartSeriesOption')
|
|
631
|
+
.map(option => ({ role: 'series', field: option.field, label: option.label, source: option.source }));
|
|
632
|
+
const chosenUnits = selectedColumns.map(column => {
|
|
633
|
+
const field = column.field;
|
|
634
|
+
const values = data.map(item => item !== null && typeof item === 'object' && !Array.isArray(item) && !isMeasurement(item)
|
|
635
|
+
? item[field ?? '']
|
|
636
|
+
: field === undefined ? item : undefined);
|
|
637
|
+
const first = values.find(value => value !== null && value !== undefined);
|
|
638
|
+
const measurementFirst = isMeasurement(first) ? first : undefined;
|
|
639
|
+
for (const value of values) {
|
|
640
|
+
if (value === null || value === undefined)
|
|
641
|
+
continue;
|
|
642
|
+
if (measurementFirst) {
|
|
643
|
+
if (!isMeasurement(value) || !sameMeasurementUnits(value, measurementFirst)) {
|
|
644
|
+
staticError('AMX3007', `Chart '${name}' contains incompatible measurement dimensions`, column.source, file, declaration.source);
|
|
645
|
+
}
|
|
646
|
+
}
|
|
647
|
+
else if (isMeasurement(value)) {
|
|
648
|
+
staticError('AMX3007', `Chart '${name}' mixes measurements with non-measurement values`, column.source, file, declaration.source);
|
|
649
|
+
}
|
|
650
|
+
}
|
|
651
|
+
return measurementFirst;
|
|
652
|
+
});
|
|
653
|
+
const headings = scatter
|
|
654
|
+
? ['x', 'y'].map((axis, index) => chosenUnits[index] ? `${axis} (${chosenUnits[index].unit.text})` : axis).concat('group')
|
|
655
|
+
: ['label', ...selectedColumns.flatMap((column, index) => column.role === 'series'
|
|
656
|
+
? [chosenUnits[index] ? `${column.label} (${chosenUnits[index].unit.text})` : column.label]
|
|
657
|
+
: [])];
|
|
658
|
+
const measurementDescriptors = selectedColumns.flatMap((column, index) => {
|
|
659
|
+
const unit = chosenUnits[index]?.unit;
|
|
660
|
+
if (!unit)
|
|
661
|
+
return [];
|
|
662
|
+
return [Object.freeze({
|
|
663
|
+
role: column.role,
|
|
664
|
+
...(column.field === undefined ? {} : { field: column.field }),
|
|
665
|
+
label: column.label,
|
|
666
|
+
unit: Object.freeze({
|
|
667
|
+
text: unit.text,
|
|
668
|
+
scale: unit.scale,
|
|
669
|
+
vector: Object.freeze({ ...unit.vector }),
|
|
670
|
+
factors: Object.freeze(unit.factors.map(factor => Object.freeze({ ...factor })))
|
|
671
|
+
})
|
|
672
|
+
})];
|
|
673
|
+
});
|
|
674
|
+
const normalizedData = data.map((item) => {
|
|
675
|
+
if (item !== null && typeof item === 'object' && !Array.isArray(item) && !isMeasurement(item)) {
|
|
676
|
+
const values = {};
|
|
677
|
+
for (const [field, value] of Object.entries(item)) {
|
|
678
|
+
const columnIndex = selectedColumns.findIndex(column => column.field === field);
|
|
679
|
+
values[field] = columnIndex < 0
|
|
680
|
+
? snapshotValue(value)
|
|
681
|
+
: normalizeChartValue(value, chosenUnits[columnIndex], name, selectedColumns[columnIndex]?.source, declaration, file);
|
|
682
|
+
}
|
|
683
|
+
return Object.freeze(values);
|
|
684
|
+
}
|
|
685
|
+
return normalizeChartValue(item, chosenUnits[0], name, selectedColumns[0]?.source, declaration, file);
|
|
686
|
+
});
|
|
687
|
+
return {
|
|
688
|
+
data: Object.freeze(normalizedData),
|
|
689
|
+
headings: Object.freeze(headings),
|
|
690
|
+
measurementDescriptors: Object.freeze(measurementDescriptors)
|
|
691
|
+
};
|
|
692
|
+
}
|
|
693
|
+
function normalizeChartValue(value, target, name, source, declaration, file) {
|
|
694
|
+
if (value === null || value === undefined)
|
|
695
|
+
return null;
|
|
696
|
+
if (!target)
|
|
697
|
+
return snapshotValue(value);
|
|
698
|
+
if (!isMeasurement(value) || !sameMeasurementUnits(value, target)) {
|
|
699
|
+
staticError('AMX3007', `Chart '${name}' contains an incompatible measurement value`, source, file, declaration.source);
|
|
700
|
+
}
|
|
701
|
+
const converted = value.value * value.unit.scale / target.unit.scale;
|
|
702
|
+
if (!Number.isFinite(converted)) {
|
|
703
|
+
staticError('AMX3007', `Chart '${name}' measurement cannot be normalized to its first display unit`, source, file, declaration.source);
|
|
704
|
+
}
|
|
705
|
+
return converted;
|
|
706
|
+
}
|
|
707
|
+
function sameMeasurementUnits(left, right) {
|
|
708
|
+
const leftEntries = Object.entries(left.unit.vector);
|
|
709
|
+
return leftEntries.length === Object.keys(right.unit.vector).length
|
|
710
|
+
&& leftEntries.every(([identity, exponent]) => right.unit.vector[identity] === exponent);
|
|
711
|
+
}
|
|
712
|
+
function evaluateStatement(statement, env, file) {
|
|
713
|
+
switch (statement.type) {
|
|
714
|
+
case 'importDeclaration':
|
|
715
|
+
case 'exportNamesDeclaration':
|
|
716
|
+
// Import materialization is the module loader's responsibility; imported
|
|
717
|
+
// names are already present in the environment before statements run.
|
|
718
|
+
return;
|
|
719
|
+
case 'dimensionDeclaration':
|
|
720
|
+
case 'unitDeclaration':
|
|
721
|
+
return;
|
|
722
|
+
case 'inputDeclaration':
|
|
723
|
+
// Input values are validated and seeded by the module loader before evaluation.
|
|
724
|
+
return;
|
|
725
|
+
case 'tableDeclaration':
|
|
726
|
+
case 'chartDeclaration':
|
|
727
|
+
env.viewDefinitions.set(statement.name, statement);
|
|
728
|
+
return;
|
|
729
|
+
case 'showStatement':
|
|
730
|
+
env.viewEmissions.push(snapshotView(statement.name, env, file, statement.source));
|
|
731
|
+
return;
|
|
732
|
+
case 'typeDeclaration':
|
|
733
|
+
env.recordTypes.set(statement.name, statement);
|
|
734
|
+
return;
|
|
735
|
+
case 'functionDeclaration':
|
|
736
|
+
env.functions.set(statement.name, statement);
|
|
737
|
+
return;
|
|
738
|
+
case 'variableDeclaration':
|
|
739
|
+
{
|
|
740
|
+
const value = evaluateExpression(statement.expression, env, file);
|
|
741
|
+
const type = env.bindingTypes.get(statement.name);
|
|
742
|
+
if (type)
|
|
743
|
+
validateRuntimeValue(value, type, env, statement.source, file, statement.name);
|
|
744
|
+
env.set(statement.name, value);
|
|
745
|
+
}
|
|
746
|
+
return;
|
|
747
|
+
case 'assignmentStatement': {
|
|
748
|
+
const value = evaluateExpression(statement.expression, env, file);
|
|
749
|
+
const type = env.bindingTypes.get(statement.name);
|
|
750
|
+
if (type)
|
|
751
|
+
validateRuntimeValue(value, type, env, statement.source, file, statement.name);
|
|
752
|
+
env.update(statement.name, value, statement.source, file);
|
|
753
|
+
return;
|
|
754
|
+
}
|
|
755
|
+
case 'compoundAssignmentStatement': {
|
|
756
|
+
const value = evaluateExpression({
|
|
757
|
+
type: 'binaryExpression',
|
|
758
|
+
operator: '+',
|
|
759
|
+
left: { type: 'identifier', name: statement.name, source: statement.source },
|
|
760
|
+
right: statement.expression,
|
|
761
|
+
source: statement.source
|
|
762
|
+
}, env, file);
|
|
763
|
+
const type = env.bindingTypes.get(statement.name);
|
|
764
|
+
if (type)
|
|
765
|
+
validateRuntimeValue(value, type, env, statement.source, file, statement.name);
|
|
766
|
+
env.update(statement.name, value, statement.source, file);
|
|
767
|
+
return;
|
|
768
|
+
}
|
|
769
|
+
case 'addStatement':
|
|
770
|
+
evaluateAddStatement(statement, env, file);
|
|
771
|
+
return;
|
|
772
|
+
case 'removeStatement':
|
|
773
|
+
evaluateRemoveStatement(statement, env, file);
|
|
774
|
+
return;
|
|
775
|
+
case 'forStatement':
|
|
776
|
+
evalForStatement(statement, env, file);
|
|
777
|
+
return;
|
|
778
|
+
case 'returnStatement':
|
|
779
|
+
throwInvalidReturnContext(statement.source, file);
|
|
780
|
+
}
|
|
781
|
+
}
|
|
782
|
+
function mutationTarget(name, env, source, file) {
|
|
783
|
+
const target = env.get(name, source, file);
|
|
784
|
+
if (!Array.isArray(target))
|
|
785
|
+
throwListOperationError(`Mutation target '${name}' is not a list`, source, file);
|
|
786
|
+
if (env.isImmutable(target))
|
|
787
|
+
throwListOperationError(`Cannot mutate immutable imported list '${name}'`, source, file);
|
|
788
|
+
return target;
|
|
789
|
+
}
|
|
790
|
+
function mutationElementType(name, env) {
|
|
791
|
+
const type = env.bindingTypes.get(name);
|
|
792
|
+
return type?.kind === 'list' ? type.element : undefined;
|
|
793
|
+
}
|
|
794
|
+
function checkedPositiveInteger(value, description, source, file) {
|
|
795
|
+
if (typeof value !== 'number' || !Number.isFinite(value) || !Number.isInteger(value) || value < 1) {
|
|
796
|
+
throwListOperationError(`${description} must be a positive integer; got ${runtimeDescription(value)}`, source, file);
|
|
797
|
+
}
|
|
798
|
+
return value;
|
|
799
|
+
}
|
|
800
|
+
function evaluateAddStatement(node, env, file) {
|
|
801
|
+
const target = mutationTarget(node.name, env, node.source, file);
|
|
802
|
+
const value = evaluateExpression(node.value, env, file);
|
|
803
|
+
const elementType = mutationElementType(node.name, env);
|
|
804
|
+
if (elementType)
|
|
805
|
+
validateRuntimeValue(value, elementType, env, node.value.source ?? node.source, file, `${node.name} element`);
|
|
806
|
+
const position = node.index
|
|
807
|
+
? checkedPositiveInteger(evaluateExpression(node.index, env, file), 'Insertion position', node.index.source ?? node.source, file)
|
|
808
|
+
: target.length + 1;
|
|
809
|
+
if (position > target.length + 1) {
|
|
810
|
+
throwListOperationError(`Insertion position ${position} is out of bounds for length ${target.length}; expected 1..${target.length + 1}`, node.index?.source ?? node.source, file);
|
|
811
|
+
}
|
|
812
|
+
target.splice(position - 1, 0, value);
|
|
813
|
+
}
|
|
814
|
+
function evaluateRemoveStatement(node, env, file) {
|
|
815
|
+
const target = mutationTarget(node.name, env, node.source, file);
|
|
816
|
+
const count = checkedPositiveInteger(evaluateExpression(node.count, env, file), 'Removal count', node.count.source ?? node.source, file);
|
|
817
|
+
if (target.length === 0)
|
|
818
|
+
throwListOperationError('Cannot remove from an empty list', node.source, file);
|
|
819
|
+
if (!node.index) {
|
|
820
|
+
target.pop();
|
|
821
|
+
return;
|
|
822
|
+
}
|
|
823
|
+
const position = checkedPositiveInteger(evaluateExpression(node.index, env, file), 'Removal position', node.index.source ?? node.source, file);
|
|
824
|
+
if (position > target.length) {
|
|
825
|
+
throwListOperationError(`Removal position ${position} is out of bounds for length ${target.length}; expected 1..${target.length}`, node.index.source ?? node.source, file);
|
|
826
|
+
}
|
|
827
|
+
if (count > target.length - position + 1) {
|
|
828
|
+
throwListOperationError(`Removal interval ${position}..${position + count - 1} exceeds list length ${target.length}`, node.count.source ?? node.source, file);
|
|
829
|
+
}
|
|
830
|
+
target.splice(position - 1, count);
|
|
831
|
+
}
|
|
832
|
+
function evalRange(node, env, file) {
|
|
833
|
+
const start = evaluateExpression(node.start, env, file);
|
|
834
|
+
const end = evaluateExpression(node.end, env, file);
|
|
835
|
+
if (typeof start !== 'number' || !Number.isFinite(start) || !Number.isInteger(start)
|
|
836
|
+
|| typeof end !== 'number' || !Number.isFinite(end) || !Number.isInteger(end)) {
|
|
837
|
+
throwInvalidRangeBounds(node.source, file);
|
|
838
|
+
}
|
|
839
|
+
const values = [];
|
|
840
|
+
const step = start <= end ? 1 : -1;
|
|
841
|
+
for (let value = start; step > 0 ? value <= end : value >= end; value += step) {
|
|
842
|
+
values.push(value);
|
|
843
|
+
if (value + step === value && value !== end)
|
|
844
|
+
throwInvalidRangeBounds(node.source, file);
|
|
845
|
+
}
|
|
846
|
+
return values;
|
|
847
|
+
}
|
|
848
|
+
function evalForStatement(node, env, file) {
|
|
849
|
+
const values = evaluateLoopIterable(node.iterable, env, file);
|
|
850
|
+
withLoopBinding(node.variable, values, env, () => evaluateStatements(node.body, env, file));
|
|
851
|
+
}
|
|
852
|
+
function evalForExpression(node, env, file) {
|
|
853
|
+
const values = evaluateLoopIterable(node.iterable, env, file);
|
|
854
|
+
const results = [];
|
|
855
|
+
withLoopBinding(node.variable, values, env, () => {
|
|
856
|
+
for (const statement of node.body) {
|
|
857
|
+
if (statement.type === 'returnStatement') {
|
|
858
|
+
results.push(evaluateExpression(statement.expression, env, file));
|
|
859
|
+
}
|
|
860
|
+
else {
|
|
861
|
+
evaluateStatement(statement, env, file);
|
|
862
|
+
}
|
|
863
|
+
}
|
|
864
|
+
});
|
|
865
|
+
return results;
|
|
866
|
+
}
|
|
867
|
+
function evaluateLoopIterable(node, env, file) {
|
|
868
|
+
const value = evaluateExpression(node, env, file);
|
|
869
|
+
if (!Array.isArray(value))
|
|
870
|
+
throwInvalidLoopIterable(node.source, file);
|
|
871
|
+
return value.slice();
|
|
872
|
+
}
|
|
873
|
+
function withLoopBinding(name, values, env, runIteration) {
|
|
874
|
+
const existed = env.has(name);
|
|
875
|
+
const previous = existed ? env.get(name) : undefined;
|
|
876
|
+
try {
|
|
877
|
+
for (const value of values) {
|
|
878
|
+
env.set(name, value);
|
|
879
|
+
runIteration();
|
|
880
|
+
}
|
|
881
|
+
}
|
|
882
|
+
finally {
|
|
883
|
+
if (existed)
|
|
884
|
+
env.set(name, previous);
|
|
885
|
+
else
|
|
886
|
+
env.delete(name);
|
|
887
|
+
}
|
|
888
|
+
}
|