@nova-energy/openamx 0.11.0 → 0.14.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,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
- export function evaluateStandardLibraryCall(callee, args, source, file) {
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
+ }