@nova-energy/openamx 0.12.0 → 0.14.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +39 -9
- package/dist/cli.js +5 -5
- package/dist/editor/completion.js +104 -2
- package/dist/editor/highlighting.js +27 -1
- package/dist/editor/refactoring.js +4 -1
- package/dist/editor/sourceRanges.js +2 -1
- package/dist/editor/symbols.js +104 -45
- package/dist/formatter/formatAmx.js +83 -7
- package/dist/parser/parseExpression.js +68 -3
- package/dist/parser/parseStatements.js +147 -0
- package/dist/renderer/diagramBrowserEntry.js +255 -0
- package/dist/renderer/diagramBrowserRuntime.js +2 -0
- package/dist/renderer/diagramHtml.js +47 -0
- package/dist/renderer/narrativeModel.js +36 -11
- package/dist/renderer/renderHtml.js +95 -41
- package/dist/renderer/reportDocx.js +38 -16
- package/dist/renderer/reportPdf.js +122 -35
- package/dist/renderer/reportPreparation.js +97 -23
- package/dist/renderer/reportSequence.js +29 -0
- package/dist/renderer/staticDiagram.js +94 -0
- package/dist/runtime/diagramModel.js +455 -0
- package/dist/runtime/environment.js +6 -0
- package/dist/runtime/evaluateExpression.js +78 -2
- package/dist/runtime/moduleLoader.js +60 -2
- package/dist/runtime/standardLibrary.js +208 -1
- package/dist/runtime/valueSerialization.js +12 -0
- package/dist/typechecker/checkDocument.js +242 -3
- package/package.json +1 -1
|
@@ -1,8 +1,9 @@
|
|
|
1
1
|
import { inputError, staticError, throwInputErrors, throwInvalidLoopIterable, throwInvalidRangeBounds, throwInvalidReturnContext, throwListOperationError, throwMeasurementDomainError } from '../diagnostics/errors';
|
|
2
2
|
import { Environment } from './environment';
|
|
3
|
-
import { evaluateStandardLibraryCall } from './standardLibrary';
|
|
3
|
+
import { evaluateStandardLibraryCall, isMathematicalFunction } from './standardLibrary';
|
|
4
4
|
import { fieldRegistry } from '../typechecker/declarationRegistry';
|
|
5
5
|
import { canonicalUnit, composeUnits, isMeasurement, measurement, powerUnit, sqrtMeasurement, unitFromMetadata } from './measurement';
|
|
6
|
+
import { createDiagramModel } from './diagramModel';
|
|
6
7
|
function validateRuntimeValue(value, expected, env, source, file, valuePath) {
|
|
7
8
|
const diagnostics = [];
|
|
8
9
|
const report = (message, target, actual, dataPath, fieldSource) => {
|
|
@@ -153,6 +154,46 @@ function validDateTime(value) {
|
|
|
153
154
|
&& +hour <= 23 && +minute <= 59 && +second <= 59
|
|
154
155
|
&& (offset === 'Z' || (+offset.slice(1, 3) <= 23 && +offset.slice(4) <= 59));
|
|
155
156
|
}
|
|
157
|
+
function matchesRuntimeType(value, target, env, file, registry = env.dimensionRegistry) {
|
|
158
|
+
if (target.type === 'nullableType') {
|
|
159
|
+
return value === null || matchesRuntimeType(value, target.element, env, file, registry);
|
|
160
|
+
}
|
|
161
|
+
if (target.type === 'listType') {
|
|
162
|
+
return Array.isArray(value) && value.every(item => matchesRuntimeType(item, target.element, env, file, registry));
|
|
163
|
+
}
|
|
164
|
+
const name = target.name;
|
|
165
|
+
const dimension = registry?.dimensions.get(name);
|
|
166
|
+
if (dimension)
|
|
167
|
+
return isMeasurement(value) && sameMeasurementVector(value, dimension.vector);
|
|
168
|
+
if (name === 'Number')
|
|
169
|
+
return typeof value === 'number';
|
|
170
|
+
if (name === 'String')
|
|
171
|
+
return typeof value === 'string';
|
|
172
|
+
if (name === 'Boolean')
|
|
173
|
+
return typeof value === 'boolean';
|
|
174
|
+
if (name === 'DateTime')
|
|
175
|
+
return typeof value === 'string' && validDateTime(value);
|
|
176
|
+
const enumeration = env.enumDeclarations.get(name);
|
|
177
|
+
if (enumeration) {
|
|
178
|
+
if (typeof value !== 'number' && typeof value !== 'string')
|
|
179
|
+
return false;
|
|
180
|
+
if (!enumeration.resolvedValues)
|
|
181
|
+
throw new Error(`Enum '${name}' has not been resolved`);
|
|
182
|
+
return enumeration.resolvedValues.includes(value);
|
|
183
|
+
}
|
|
184
|
+
const declaration = env.recordTypes.get(name);
|
|
185
|
+
if (declaration) {
|
|
186
|
+
if (typeof value !== 'object' || value === null || Array.isArray(value) || isMeasurement(value))
|
|
187
|
+
return false;
|
|
188
|
+
const record = value;
|
|
189
|
+
return declaration.fields.every(field => {
|
|
190
|
+
if (!Object.prototype.hasOwnProperty.call(record, field.name))
|
|
191
|
+
return field.optional;
|
|
192
|
+
return matchesRuntimeType(record[field.name], field.annotation, env, file, fieldRegistry(field, registry));
|
|
193
|
+
});
|
|
194
|
+
}
|
|
195
|
+
return staticError('AMX3001', `Unknown type '${name}'`, target.source, file);
|
|
196
|
+
}
|
|
156
197
|
/** Evaluate V0.2 expressions, including ranges and expression-form loops. */
|
|
157
198
|
export function evaluateExpression(node, env, file) {
|
|
158
199
|
switch (node.type) {
|
|
@@ -203,6 +244,10 @@ export function evaluateExpression(node, env, file) {
|
|
|
203
244
|
case 'booleanLiteral':
|
|
204
245
|
return node.value;
|
|
205
246
|
case 'identifier':
|
|
247
|
+
if (node.name === 'PI')
|
|
248
|
+
return Math.PI;
|
|
249
|
+
if (node.name === 'E')
|
|
250
|
+
return Math.E;
|
|
206
251
|
// Pass source location for better diagnostics
|
|
207
252
|
return env.get(node.name, node.source, file);
|
|
208
253
|
case 'measurementAttachment': {
|
|
@@ -233,6 +278,8 @@ export function evaluateExpression(node, env, file) {
|
|
|
233
278
|
}
|
|
234
279
|
case 'binaryExpression':
|
|
235
280
|
return evalBinary(node, env, file);
|
|
281
|
+
case 'typeTestExpression':
|
|
282
|
+
return matchesRuntimeType(evaluateExpression(node.value, env, file), node.target, env, file);
|
|
236
283
|
case 'unaryExpression':
|
|
237
284
|
return evalUnary(node, env, file);
|
|
238
285
|
case 'conditionalExpression':
|
|
@@ -474,6 +521,24 @@ function evalListAccess(node, env, file) {
|
|
|
474
521
|
}
|
|
475
522
|
return receiver[index - 1];
|
|
476
523
|
}
|
|
524
|
+
function functionArgumentSource(expression, fallback) {
|
|
525
|
+
if (expression.type === 'binaryExpression') {
|
|
526
|
+
return functionArgumentSource(expression.left, fallback) ?? expression.operatorSource ?? expression.source ?? fallback;
|
|
527
|
+
}
|
|
528
|
+
if (expression.type === 'unaryExpression') {
|
|
529
|
+
const operandSource = functionArgumentSource(expression.argument, fallback);
|
|
530
|
+
if (operandSource) {
|
|
531
|
+
return {
|
|
532
|
+
line: operandSource.line,
|
|
533
|
+
column: Math.max(1, operandSource.column - (expression.operator === 'not' ? 3 : 1))
|
|
534
|
+
};
|
|
535
|
+
}
|
|
536
|
+
}
|
|
537
|
+
if (expression.type === 'measurementAttachment' || expression.type === 'measurementConversion') {
|
|
538
|
+
return functionArgumentSource(expression.value, fallback) ?? expression.source ?? fallback;
|
|
539
|
+
}
|
|
540
|
+
return expression.source ?? fallback;
|
|
541
|
+
}
|
|
477
542
|
function evalFunctionCall(node, env, file) {
|
|
478
543
|
const args = node.arguments.map(a => evaluateExpression(a, env, file));
|
|
479
544
|
const userFunction = env.functions.get(node.callee);
|
|
@@ -532,6 +597,12 @@ function evalFunctionCall(node, env, file) {
|
|
|
532
597
|
}
|
|
533
598
|
if (isMeasurement(args[0])) {
|
|
534
599
|
const value = args[0];
|
|
600
|
+
if (isMathematicalFunction(node.callee)) {
|
|
601
|
+
if (Object.keys(value.unit.vector).length !== 0) {
|
|
602
|
+
return staticError('AMX3007', `'${node.callee}' requires a Number or dimensionless Measurement`, node.arguments[0]?.source ?? node.source, file);
|
|
603
|
+
}
|
|
604
|
+
return evaluateStandardLibraryCall(node.callee, [value.value * value.unit.scale], node.source, file);
|
|
605
|
+
}
|
|
535
606
|
switch (node.callee) {
|
|
536
607
|
case 'abs':
|
|
537
608
|
return measurement(Math.abs(value.value), value.unit);
|
|
@@ -581,7 +652,7 @@ function evalFunctionCall(node, env, file) {
|
|
|
581
652
|
}
|
|
582
653
|
}
|
|
583
654
|
}
|
|
584
|
-
return evaluateStandardLibraryCall(node.callee, args, node.source, file);
|
|
655
|
+
return evaluateStandardLibraryCall(node.callee, args, node.source, file, node.arguments.map(argument => functionArgumentSource(argument, node.source)));
|
|
585
656
|
}
|
|
586
657
|
function toNumber(v, nodeForError) {
|
|
587
658
|
if (typeof v === 'number')
|
|
@@ -798,6 +869,11 @@ function evaluateStatement(statement, env, file) {
|
|
|
798
869
|
case 'chartDeclaration':
|
|
799
870
|
env.viewDefinitions.set(statement.name, statement);
|
|
800
871
|
return;
|
|
872
|
+
case 'diagramDeclaration':
|
|
873
|
+
env.diagramEmissions.push({
|
|
874
|
+
model: createDiagramModel(statement, env, file, env.currentDocumentNodeIndex, env.currentStatementIndex)
|
|
875
|
+
});
|
|
876
|
+
return;
|
|
801
877
|
case 'showStatement':
|
|
802
878
|
env.viewEmissions.push(snapshotView(statement.name, env, file, statement.source));
|
|
803
879
|
return;
|
|
@@ -15,6 +15,45 @@ function flattenStatements(doc) {
|
|
|
15
15
|
}
|
|
16
16
|
return statements;
|
|
17
17
|
}
|
|
18
|
+
function collectDiagramDeclarations(statements, output) {
|
|
19
|
+
for (const statement of statements) {
|
|
20
|
+
if (statement.type === 'diagramDeclaration')
|
|
21
|
+
output.push(statement);
|
|
22
|
+
else if (statement.type === 'forStatement')
|
|
23
|
+
collectDiagramDeclarations(statement.body, output);
|
|
24
|
+
else if (statement.type === 'bracedIfStatement') {
|
|
25
|
+
collectDiagramDeclarations(statement.consequent, output);
|
|
26
|
+
if (statement.alternate)
|
|
27
|
+
collectDiagramDeclarations(statement.alternate, output);
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
function reportDiagramDeclarations(doc) {
|
|
32
|
+
const declarations = [];
|
|
33
|
+
for (const node of doc.nodes) {
|
|
34
|
+
if (node.type === 'executableCodeBlock')
|
|
35
|
+
collectDiagramDeclarations(node.statements, declarations);
|
|
36
|
+
}
|
|
37
|
+
return declarations;
|
|
38
|
+
}
|
|
39
|
+
function validateReportDiagramCaps(records) {
|
|
40
|
+
let diagramCount = 0;
|
|
41
|
+
let elementCount = 0;
|
|
42
|
+
for (const record of records) {
|
|
43
|
+
for (const declaration of reportDiagramDeclarations(record.doc)) {
|
|
44
|
+
diagramCount++;
|
|
45
|
+
if (diagramCount > 16) {
|
|
46
|
+
staticError('AMXD012', 'A single report can have up to 16 diagrams maximum.', declaration.source, record.canonicalPath);
|
|
47
|
+
}
|
|
48
|
+
for (const element of declaration.elements) {
|
|
49
|
+
elementCount++;
|
|
50
|
+
if (elementCount > 512) {
|
|
51
|
+
staticError('AMXD013', 'A single report can have up to 512 elements maximum.', element.source, record.canonicalPath);
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
}
|
|
18
57
|
function validateImportPathSyntax(importNode, file) {
|
|
19
58
|
const importPath = importNode.path;
|
|
20
59
|
if (!(importPath.startsWith('./') || importPath.startsWith('../'))) {
|
|
@@ -201,6 +240,7 @@ export async function loadEntryModule(entryPath, options = {}) {
|
|
|
201
240
|
return record;
|
|
202
241
|
}
|
|
203
242
|
await visit(realEntry, undefined);
|
|
243
|
+
validateReportDiagramCaps(evaluationOrder.map(canonicalPath => resolved.get(canonicalPath)));
|
|
204
244
|
const entryRecord = resolved.get(realEntry);
|
|
205
245
|
const registry = {
|
|
206
246
|
dimensions: entryRecord.checkResult.dimensions,
|
|
@@ -234,6 +274,7 @@ export async function loadEntryModule(entryPath, options = {}) {
|
|
|
234
274
|
env: new Environment(entryTypes, new Map(), registry),
|
|
235
275
|
outputs,
|
|
236
276
|
viewEmissions: [],
|
|
277
|
+
diagramEmissions: [],
|
|
237
278
|
registry,
|
|
238
279
|
inputInspection: {
|
|
239
280
|
schema: describeInputSchema(declaration, entryTypes, registry),
|
|
@@ -244,7 +285,15 @@ export async function loadEntryModule(entryPath, options = {}) {
|
|
|
244
285
|
};
|
|
245
286
|
}
|
|
246
287
|
if (options.outputInspection) {
|
|
247
|
-
return {
|
|
288
|
+
return {
|
|
289
|
+
doc: entryRecord.doc,
|
|
290
|
+
env: new Environment(entryTypes, new Map(), registry),
|
|
291
|
+
outputs,
|
|
292
|
+
viewEmissions: [],
|
|
293
|
+
diagramEmissions: [],
|
|
294
|
+
outputSchemas: outputSchemas ?? [],
|
|
295
|
+
registry
|
|
296
|
+
};
|
|
248
297
|
}
|
|
249
298
|
const inputValues = await loadInputValues(inputDeclarations, entryTypes, options.inputMappings, options.validation, entryPath, registry);
|
|
250
299
|
const evaluatedEnvironments = new Map();
|
|
@@ -289,5 +338,14 @@ export async function loadEntryModule(entryPath, options = {}) {
|
|
|
289
338
|
evaluatedEnvironments.set(canonicalPath, env);
|
|
290
339
|
}
|
|
291
340
|
const entryEnv = evaluatedEnvironments.get(realEntry);
|
|
292
|
-
|
|
341
|
+
const diagramEmissions = Object.freeze(evaluationOrder.flatMap(canonicalPath => evaluatedEnvironments.get(canonicalPath).diagramEmissions));
|
|
342
|
+
entryEnv.diagramEmissions.splice(0, entryEnv.diagramEmissions.length, ...diagramEmissions);
|
|
343
|
+
return {
|
|
344
|
+
doc: resolved.get(realEntry).doc,
|
|
345
|
+
env: entryEnv,
|
|
346
|
+
outputs,
|
|
347
|
+
viewEmissions: entryEnv.viewEmissions,
|
|
348
|
+
diagramEmissions,
|
|
349
|
+
registry
|
|
350
|
+
};
|
|
293
351
|
}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { AmxError } from '../diagnostics/errors';
|
|
2
|
+
import { isMeasurement } from './measurement';
|
|
2
3
|
/**
|
|
3
4
|
* Standard library for OpenAMX v0.1.
|
|
4
5
|
*
|
|
@@ -70,7 +71,213 @@ function ensureMinArgCount(args, min, callee, source, file) {
|
|
|
70
71
|
});
|
|
71
72
|
}
|
|
72
73
|
}
|
|
73
|
-
|
|
74
|
+
const mathFunctions = {
|
|
75
|
+
sin: { evaluate: Math.sin, accepts: Number.isFinite },
|
|
76
|
+
cos: { evaluate: Math.cos, accepts: Number.isFinite },
|
|
77
|
+
tan: { evaluate: Math.tan, accepts: Number.isFinite },
|
|
78
|
+
asin: { evaluate: Math.asin, accepts: value => Number.isFinite(value) && value >= -1 && value <= 1 },
|
|
79
|
+
acos: { evaluate: Math.acos, accepts: value => Number.isFinite(value) && value >= -1 && value <= 1 },
|
|
80
|
+
atan: { evaluate: Math.atan, accepts: Number.isFinite },
|
|
81
|
+
sinh: { evaluate: Math.sinh, accepts: Number.isFinite },
|
|
82
|
+
cosh: { evaluate: Math.cosh, accepts: Number.isFinite },
|
|
83
|
+
tanh: { evaluate: Math.tanh, accepts: Number.isFinite },
|
|
84
|
+
asinh: { evaluate: Math.asinh, accepts: Number.isFinite },
|
|
85
|
+
acosh: { evaluate: Math.acosh, accepts: value => Number.isFinite(value) && value >= 1 },
|
|
86
|
+
atanh: { evaluate: Math.atanh, accepts: value => Number.isFinite(value) && value > -1 && value < 1 },
|
|
87
|
+
ln: { evaluate: Math.log, accepts: value => Number.isFinite(value) && value > 0 },
|
|
88
|
+
log: { evaluate: Math.log10, accepts: value => Number.isFinite(value) && value > 0 },
|
|
89
|
+
exp: { evaluate: Math.exp, accepts: Number.isFinite }
|
|
90
|
+
};
|
|
91
|
+
export function isMathematicalFunction(name) {
|
|
92
|
+
return Object.hasOwn(mathFunctions, name);
|
|
93
|
+
}
|
|
94
|
+
function mathError(code, message, source, file) {
|
|
95
|
+
return new AmxError({ code, message, file, line: source?.line, column: source?.column });
|
|
96
|
+
}
|
|
97
|
+
function libraryError(code, message, source, file) {
|
|
98
|
+
return new AmxError({ code, message, file, line: source?.line, column: source?.column });
|
|
99
|
+
}
|
|
100
|
+
function runtimeType(value) {
|
|
101
|
+
if (value === null)
|
|
102
|
+
return 'null';
|
|
103
|
+
if (isMeasurement(value))
|
|
104
|
+
return 'Measurement';
|
|
105
|
+
if (Array.isArray(value))
|
|
106
|
+
return 'list';
|
|
107
|
+
if (typeof value === 'number')
|
|
108
|
+
return 'Number';
|
|
109
|
+
if (typeof value === 'string')
|
|
110
|
+
return 'String';
|
|
111
|
+
if (typeof value === 'boolean')
|
|
112
|
+
return 'Boolean';
|
|
113
|
+
return typeof value;
|
|
114
|
+
}
|
|
115
|
+
function ensureLibraryArity(callee, args, min, max, source, file) {
|
|
116
|
+
if (args.length < min || args.length > max) {
|
|
117
|
+
throw libraryError('AMX3004', `Invalid arity for '${callee}'`, source, file);
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
function textArgument(callee, value, source, file) {
|
|
121
|
+
if (typeof value !== 'string') {
|
|
122
|
+
throw libraryError('AMX3002', `${callee} requires a String, got ${runtimeType(value)}`, source, file);
|
|
123
|
+
}
|
|
124
|
+
return value;
|
|
125
|
+
}
|
|
126
|
+
function isUnicodeWhiteSpace(codePoint) {
|
|
127
|
+
return codePoint >= 0x0009 && codePoint <= 0x000d
|
|
128
|
+
|| codePoint === 0x0020
|
|
129
|
+
|| codePoint === 0x0085
|
|
130
|
+
|| codePoint === 0x00a0
|
|
131
|
+
|| codePoint === 0x1680
|
|
132
|
+
|| codePoint >= 0x2000 && codePoint <= 0x200a
|
|
133
|
+
|| codePoint === 0x2028
|
|
134
|
+
|| codePoint === 0x2029
|
|
135
|
+
|| codePoint === 0x202f
|
|
136
|
+
|| codePoint === 0x205f
|
|
137
|
+
|| codePoint === 0x3000;
|
|
138
|
+
}
|
|
139
|
+
function trimText(value) {
|
|
140
|
+
const points = Array.from(value);
|
|
141
|
+
let start = 0;
|
|
142
|
+
let end = points.length;
|
|
143
|
+
while (start < end && isUnicodeWhiteSpace(points[start].codePointAt(0)))
|
|
144
|
+
start++;
|
|
145
|
+
while (end > start && isUnicodeWhiteSpace(points[end - 1].codePointAt(0)))
|
|
146
|
+
end--;
|
|
147
|
+
return points.slice(start, end).join('');
|
|
148
|
+
}
|
|
149
|
+
function parseNumericPattern(pattern, source, file) {
|
|
150
|
+
if (typeof pattern !== 'string') {
|
|
151
|
+
throw libraryError('AMXSL004', 'Incorrect formatting pattern', source, file);
|
|
152
|
+
}
|
|
153
|
+
const match = /^([$€£])?(#,##0|0)(?:\.(0{1,6}))?(%)?$/.exec(pattern);
|
|
154
|
+
if (!match)
|
|
155
|
+
throw libraryError('AMXSL004', 'Incorrect formatting pattern', source, file);
|
|
156
|
+
return {
|
|
157
|
+
currency: match[1] ?? '',
|
|
158
|
+
grouped: match[2] === '#,##0',
|
|
159
|
+
precision: match[3]?.length ?? 0,
|
|
160
|
+
percent: match[4] === '%'
|
|
161
|
+
};
|
|
162
|
+
}
|
|
163
|
+
function parseNumericLocale(locale, source, file) {
|
|
164
|
+
switch (locale) {
|
|
165
|
+
case 'en-US': return { decimal: '.', group: ',' };
|
|
166
|
+
case 'de-DE': return { decimal: ',', group: '.' };
|
|
167
|
+
case 'fr-FR': return { decimal: ',', group: '\u202f' };
|
|
168
|
+
default: throw libraryError('AMXSL005', 'Formatting locale is malformed or unsupported', source, file);
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
function roundedScaledInteger(value, precision) {
|
|
172
|
+
const [mantissa, exponentText] = Math.abs(value).toString().toLowerCase().split('e');
|
|
173
|
+
const exponent = exponentText === undefined ? 0 : Number(exponentText);
|
|
174
|
+
const [integerPart, fractionalPart = ''] = mantissa.split('.');
|
|
175
|
+
const digits = `${integerPart}${fractionalPart}`.replace(/^0+(?=\d)/, '');
|
|
176
|
+
const coefficient = BigInt(digits || '0');
|
|
177
|
+
const shift = precision + exponent - fractionalPart.length;
|
|
178
|
+
if (shift >= 0)
|
|
179
|
+
return coefficient * 10n ** BigInt(shift);
|
|
180
|
+
const divisor = 10n ** BigInt(-shift);
|
|
181
|
+
const quotient = coefficient / divisor;
|
|
182
|
+
const remainder = coefficient % divisor;
|
|
183
|
+
return quotient + (remainder * 2n >= divisor ? 1n : 0n);
|
|
184
|
+
}
|
|
185
|
+
function groupInteger(value, separator) {
|
|
186
|
+
return value.replace(/\B(?=(\d{3})+(?!\d))/g, separator);
|
|
187
|
+
}
|
|
188
|
+
function formatNumericValue(value, pattern, locale) {
|
|
189
|
+
const displayedValue = pattern.percent ? value * 100 : value;
|
|
190
|
+
const negative = displayedValue < 0;
|
|
191
|
+
const precisionFactor = 10n ** BigInt(pattern.precision);
|
|
192
|
+
const scaled = roundedScaledInteger(displayedValue, pattern.precision);
|
|
193
|
+
const integer = (scaled / precisionFactor).toString();
|
|
194
|
+
const fraction = pattern.precision
|
|
195
|
+
? `${locale.decimal}${(scaled % precisionFactor).toString().padStart(pattern.precision, '0')}`
|
|
196
|
+
: '';
|
|
197
|
+
const integerText = pattern.grouped ? groupInteger(integer, locale.group) : integer;
|
|
198
|
+
return `${negative ? '-' : ''}${pattern.currency}${integerText}${fraction}${pattern.percent ? '%' : ''}`;
|
|
199
|
+
}
|
|
200
|
+
export function evaluateStandardLibraryCall(callee, args, source, file, argumentSources = []) {
|
|
201
|
+
const argumentSource = (index) => argumentSources[index] ?? source;
|
|
202
|
+
if (callee === 'len') {
|
|
203
|
+
ensureLibraryArity(callee, args, 1, 1, source, file);
|
|
204
|
+
const value = args[0];
|
|
205
|
+
if (typeof value === 'string')
|
|
206
|
+
return Array.from(value).length;
|
|
207
|
+
if (Array.isArray(value))
|
|
208
|
+
return value.length;
|
|
209
|
+
throw libraryError('AMX3002', `len requires a String or list, got ${runtimeType(value)}`, argumentSource(0), file);
|
|
210
|
+
}
|
|
211
|
+
if (callee === 'trim') {
|
|
212
|
+
ensureLibraryArity(callee, args, 1, 1, source, file);
|
|
213
|
+
return trimText(textArgument(callee, args[0], argumentSource(0), file));
|
|
214
|
+
}
|
|
215
|
+
if (callee === 'left' || callee === 'right') {
|
|
216
|
+
ensureLibraryArity(callee, args, 1, 2, source, file);
|
|
217
|
+
const points = Array.from(textArgument(callee, args[0], argumentSource(0), file));
|
|
218
|
+
const count = args.length === 1 ? 1 : args[1];
|
|
219
|
+
if (typeof count !== 'number' || !Number.isFinite(count) || !Number.isInteger(count) || count < 0) {
|
|
220
|
+
throw libraryError('AMXSL003', 'Invalid text slice count', argumentSource(1), file);
|
|
221
|
+
}
|
|
222
|
+
const length = Math.min(count, points.length);
|
|
223
|
+
return callee === 'left'
|
|
224
|
+
? points.slice(0, length).join('')
|
|
225
|
+
: points.slice(points.length - length).join('');
|
|
226
|
+
}
|
|
227
|
+
if (callee === 'format') {
|
|
228
|
+
ensureLibraryArity(callee, args, 2, 3, source, file);
|
|
229
|
+
const value = args[0];
|
|
230
|
+
const valueSource = argumentSource(0);
|
|
231
|
+
if (typeof value !== 'number' && !isMeasurement(value)) {
|
|
232
|
+
throw libraryError('AMX3002', `format expects a Number or Measurement, got ${runtimeType(value)}`, valueSource, file);
|
|
233
|
+
}
|
|
234
|
+
const displayedValue = isMeasurement(value) ? value.value : value;
|
|
235
|
+
if (!Number.isFinite(displayedValue)) {
|
|
236
|
+
throw libraryError('AMXSL006', 'Input is non-finite', valueSource, file);
|
|
237
|
+
}
|
|
238
|
+
const pattern = parseNumericPattern(args[1], argumentSource(1), file);
|
|
239
|
+
const locale = parseNumericLocale(args.length === 3 ? args[2] : 'en-US', argumentSource(2), file);
|
|
240
|
+
if (pattern.percent && !Number.isFinite(displayedValue * 100)) {
|
|
241
|
+
throw libraryError('AMXSL006', 'Input is non-finite', valueSource, file);
|
|
242
|
+
}
|
|
243
|
+
const formatted = formatNumericValue(displayedValue, pattern, locale);
|
|
244
|
+
return isMeasurement(value) ? `${formatted} ${value.unit.text}` : formatted;
|
|
245
|
+
}
|
|
246
|
+
const mathFunction = mathFunctions[callee];
|
|
247
|
+
if (mathFunction) {
|
|
248
|
+
if (args.length !== 1) {
|
|
249
|
+
throw new AmxError({
|
|
250
|
+
code: 'AMX3004',
|
|
251
|
+
message: `Invalid arity for '${callee}'`,
|
|
252
|
+
file,
|
|
253
|
+
line: source?.line,
|
|
254
|
+
column: source?.column
|
|
255
|
+
});
|
|
256
|
+
}
|
|
257
|
+
const value = args[0];
|
|
258
|
+
if (typeof value !== 'number') {
|
|
259
|
+
const actual = value === null ? 'null'
|
|
260
|
+
: Array.isArray(value) ? 'list'
|
|
261
|
+
: typeof value === 'object' ? 'Measurement'
|
|
262
|
+
: typeof value === 'string' ? 'String'
|
|
263
|
+
: typeof value === 'boolean' ? 'Boolean' : typeof value;
|
|
264
|
+
throw new AmxError({
|
|
265
|
+
code: 'AMX3002',
|
|
266
|
+
message: `Expected Number or dimensionless Measurement, got ${actual}`,
|
|
267
|
+
file,
|
|
268
|
+
line: source?.line,
|
|
269
|
+
column: source?.column
|
|
270
|
+
});
|
|
271
|
+
}
|
|
272
|
+
if (!mathFunction.accepts(value)) {
|
|
273
|
+
throw mathError('AMXSL001', 'Invalid input for mathematical function', source, file);
|
|
274
|
+
}
|
|
275
|
+
const result = mathFunction.evaluate(value);
|
|
276
|
+
if (!Number.isFinite(result)) {
|
|
277
|
+
throw mathError('AMXSL002', 'Function evaluation results in infinite result', source, file);
|
|
278
|
+
}
|
|
279
|
+
return result;
|
|
280
|
+
}
|
|
74
281
|
switch (callee) {
|
|
75
282
|
case 'sum': {
|
|
76
283
|
ensureArgCount(args, 1, 'sum', source, file);
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import { isMeasurement } from './measurement';
|
|
2
|
+
export function formatAmxValue(value, nullText = '') {
|
|
3
|
+
if (value === null || value === undefined)
|
|
4
|
+
return nullText;
|
|
5
|
+
if (Array.isArray(value))
|
|
6
|
+
return value.map(item => formatAmxValue(item, nullText)).join(', ');
|
|
7
|
+
if (isMeasurement(value))
|
|
8
|
+
return `${String(value.value)} ${value.unit.text}`;
|
|
9
|
+
if (typeof value === 'object')
|
|
10
|
+
return JSON.stringify(value, null, 2) ?? '';
|
|
11
|
+
return String(value);
|
|
12
|
+
}
|