@nova-energy/openamx 0.22.0 → 0.23.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/dist/editor/highlighting.js +9 -0
- package/dist/parser/parseExpression.js +23 -5
- package/dist/renderer/diagramBrowserRuntime.js +1 -1
- package/dist/runtime/complex.js +131 -0
- package/dist/runtime/dateTime.js +232 -0
- package/dist/runtime/environment.js +9 -0
- package/dist/runtime/evaluateExpression.js +33 -15
- package/dist/runtime/inputData.js +3 -13
- package/dist/runtime/outputData.js +18 -2
- package/dist/runtime/standardLibrary.js +79 -0
- package/dist/runtime/valueSerialization.js +3 -0
- package/dist/transpiler/emit.js +41 -8
- package/dist/transpilerRuntime.js +20 -14
- package/dist/typechecker/checkDocument.js +88 -23
- package/dist/typechecker/typescriptAnalysis.js +1 -1
- package/package.json +2 -1
|
@@ -0,0 +1,232 @@
|
|
|
1
|
+
const nanosecondsPerSecond = 1000000000n;
|
|
2
|
+
const nanosecondsPerMinute = 60n * nanosecondsPerSecond;
|
|
3
|
+
const nanosecondsPerHour = 60n * nanosecondsPerMinute;
|
|
4
|
+
const secondsPerDay = 86400n;
|
|
5
|
+
const nanosecondsPerDay = secondsPerDay * nanosecondsPerSecond;
|
|
6
|
+
const dateTimePattern = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.(\d{1,9}))?(Z|[+-]\d{2}:\d{2})$/;
|
|
7
|
+
export const dateTimeUnitValues = ['years', 'months', 'days', 'hours', 'minutes', 'seconds'];
|
|
8
|
+
function floorDivide(value, divisor) {
|
|
9
|
+
const quotient = value / divisor;
|
|
10
|
+
return value % divisor < 0n ? quotient - 1n : quotient;
|
|
11
|
+
}
|
|
12
|
+
function daysFromCivil(year, month, day) {
|
|
13
|
+
let adjustedYear = year;
|
|
14
|
+
if (month <= 2)
|
|
15
|
+
adjustedYear -= 1n;
|
|
16
|
+
const era = floorDivide(adjustedYear, 400n);
|
|
17
|
+
const yearOfEra = adjustedYear - era * 400n;
|
|
18
|
+
const monthOfYear = BigInt(month + (month > 2 ? -3 : 9));
|
|
19
|
+
const dayOfYear = (153n * monthOfYear + 2n) / 5n + BigInt(day - 1);
|
|
20
|
+
const dayOfEra = yearOfEra * 365n + yearOfEra / 4n - yearOfEra / 100n + dayOfYear;
|
|
21
|
+
return era * 146097n + dayOfEra - 719468n;
|
|
22
|
+
}
|
|
23
|
+
function isLeapYear(year) {
|
|
24
|
+
return year % 4n === 0n && (year % 100n !== 0n || year % 400n === 0n);
|
|
25
|
+
}
|
|
26
|
+
function daysInMonth(year, month) {
|
|
27
|
+
if (month === 2)
|
|
28
|
+
return isLeapYear(year) ? 29 : 28;
|
|
29
|
+
return [4, 6, 9, 11].includes(month) ? 30 : 31;
|
|
30
|
+
}
|
|
31
|
+
function civilFromDays(daysSinceEpoch) {
|
|
32
|
+
const shiftedDays = daysSinceEpoch + 719468n;
|
|
33
|
+
const era = floorDivide(shiftedDays, 146097n);
|
|
34
|
+
const dayOfEra = shiftedDays - era * 146097n;
|
|
35
|
+
const yearOfEra = (dayOfEra - dayOfEra / 1460n + dayOfEra / 36524n - dayOfEra / 146096n) / 365n;
|
|
36
|
+
let year = yearOfEra + era * 400n;
|
|
37
|
+
const dayOfYear = dayOfEra - (365n * yearOfEra + yearOfEra / 4n - yearOfEra / 100n);
|
|
38
|
+
const monthPrime = (5n * dayOfYear + 2n) / 153n;
|
|
39
|
+
const day = Number(dayOfYear - (153n * monthPrime + 2n) / 5n + 1n);
|
|
40
|
+
const month = Number(monthPrime + (monthPrime < 10n ? 3n : -9n));
|
|
41
|
+
if (month <= 2)
|
|
42
|
+
year += 1n;
|
|
43
|
+
return { year, month, day };
|
|
44
|
+
}
|
|
45
|
+
function localParts(parsed) {
|
|
46
|
+
return {
|
|
47
|
+
year: BigInt(parsed.year), month: parsed.month, day: parsed.day,
|
|
48
|
+
hour: parsed.hour, minute: parsed.minute, second: parsed.second
|
|
49
|
+
};
|
|
50
|
+
}
|
|
51
|
+
function localNanoseconds(parts, fraction) {
|
|
52
|
+
const seconds = daysFromCivil(parts.year, parts.month, parts.day) * secondsPerDay
|
|
53
|
+
+ BigInt(parts.hour * 3600 + parts.minute * 60 + parts.second);
|
|
54
|
+
return seconds * nanosecondsPerSecond + BigInt(fraction.padEnd(9, '0') || '0');
|
|
55
|
+
}
|
|
56
|
+
function offsetText(offsetMinutes) {
|
|
57
|
+
const sign = offsetMinutes < 0 ? '-' : '+';
|
|
58
|
+
const magnitude = Math.abs(offsetMinutes);
|
|
59
|
+
return `${sign}${String(Math.floor(magnitude / 60)).padStart(2, '0')}:${String(magnitude % 60).padStart(2, '0')}`;
|
|
60
|
+
}
|
|
61
|
+
function formatParts(parts, fraction, offset) {
|
|
62
|
+
if (parts.year < 0n || parts.year > 9999n)
|
|
63
|
+
throw new RangeError('DateTime result is outside the supported four-digit-year range');
|
|
64
|
+
const date = `${String(parts.year).padStart(4, '0')}-${String(parts.month).padStart(2, '0')}-${String(parts.day).padStart(2, '0')}`;
|
|
65
|
+
const time = `${String(parts.hour).padStart(2, '0')}:${String(parts.minute).padStart(2, '0')}:${String(parts.second).padStart(2, '0')}`;
|
|
66
|
+
return `${date}T${time}${fraction ? `.${fraction}` : ''}${offset}`;
|
|
67
|
+
}
|
|
68
|
+
function partsAtInstant(instantNanoseconds, offsetMinutes) {
|
|
69
|
+
const local = instantNanoseconds + BigInt(offsetMinutes) * nanosecondsPerMinute;
|
|
70
|
+
const days = floorDivide(local, nanosecondsPerDay);
|
|
71
|
+
let withinDay = local - days * nanosecondsPerDay;
|
|
72
|
+
const date = civilFromDays(days);
|
|
73
|
+
const hour = Number(withinDay / nanosecondsPerHour);
|
|
74
|
+
withinDay %= nanosecondsPerHour;
|
|
75
|
+
const minute = Number(withinDay / nanosecondsPerMinute);
|
|
76
|
+
withinDay %= nanosecondsPerMinute;
|
|
77
|
+
const second = Number(withinDay / nanosecondsPerSecond);
|
|
78
|
+
return {
|
|
79
|
+
...date, hour, minute, second,
|
|
80
|
+
fractionNanoseconds: withinDay % nanosecondsPerSecond
|
|
81
|
+
};
|
|
82
|
+
}
|
|
83
|
+
function formatInstant(parsed, instantNanoseconds) {
|
|
84
|
+
const parts = partsAtInstant(instantNanoseconds, parsed.offsetMinutes);
|
|
85
|
+
return formatParts(parts, parsed.fraction, parsed.offsetText);
|
|
86
|
+
}
|
|
87
|
+
function shiftedCalendarParts(parsed, monthDelta) {
|
|
88
|
+
const source = localParts(parsed);
|
|
89
|
+
const targetMonthIndex = source.year * 12n + BigInt(source.month - 1) + monthDelta;
|
|
90
|
+
const targetYear = floorDivide(targetMonthIndex, 12n);
|
|
91
|
+
const targetMonth = Number(targetMonthIndex - targetYear * 12n) + 1;
|
|
92
|
+
return {
|
|
93
|
+
...source,
|
|
94
|
+
year: targetYear,
|
|
95
|
+
month: targetMonth,
|
|
96
|
+
day: Math.min(source.day, daysInMonth(targetYear, targetMonth))
|
|
97
|
+
};
|
|
98
|
+
}
|
|
99
|
+
function instantForCalendarParts(parts, fraction, offsetMinutes) {
|
|
100
|
+
return localNanoseconds(parts, fraction) - BigInt(offsetMinutes) * nanosecondsPerMinute;
|
|
101
|
+
}
|
|
102
|
+
function requireParsedDateTime(value) {
|
|
103
|
+
const parsed = parseDateTime(value);
|
|
104
|
+
if (!parsed)
|
|
105
|
+
throw new RangeError('Invalid offset-bearing DateTime value');
|
|
106
|
+
return parsed;
|
|
107
|
+
}
|
|
108
|
+
function localOffset(date) {
|
|
109
|
+
return offsetText(-date.getTimezoneOffset());
|
|
110
|
+
}
|
|
111
|
+
export function parseDateTime(value) {
|
|
112
|
+
if (typeof value !== 'string')
|
|
113
|
+
return undefined;
|
|
114
|
+
const parts = dateTimePattern.exec(value);
|
|
115
|
+
if (!parts)
|
|
116
|
+
return undefined;
|
|
117
|
+
const [, yearText, monthText, dayText, hourText, minuteText, secondText, fraction = '', offsetText] = parts;
|
|
118
|
+
const year = Number(yearText);
|
|
119
|
+
const month = Number(monthText);
|
|
120
|
+
const day = Number(dayText);
|
|
121
|
+
const hour = Number(hourText);
|
|
122
|
+
const minute = Number(minuteText);
|
|
123
|
+
const second = Number(secondText);
|
|
124
|
+
if (month < 1 || month > 12 || day < 1 || day > daysInMonth(BigInt(year), month)
|
|
125
|
+
|| hour > 23 || minute > 59 || second > 59)
|
|
126
|
+
return undefined;
|
|
127
|
+
let offsetMinutes = 0;
|
|
128
|
+
if (offsetText !== 'Z') {
|
|
129
|
+
const offsetHour = Number(offsetText.slice(1, 3));
|
|
130
|
+
const offsetMinute = Number(offsetText.slice(4, 6));
|
|
131
|
+
if (offsetHour > 23 || offsetMinute > 59)
|
|
132
|
+
return undefined;
|
|
133
|
+
const magnitude = offsetHour * 60 + offsetMinute;
|
|
134
|
+
offsetMinutes = offsetText[0] === '-' ? -magnitude : magnitude;
|
|
135
|
+
}
|
|
136
|
+
const localSeconds = daysFromCivil(BigInt(year), month, day) * secondsPerDay
|
|
137
|
+
+ BigInt(hour * 3600 + minute * 60 + second);
|
|
138
|
+
const fractionalNanoseconds = BigInt(fraction.padEnd(9, '0') || '0');
|
|
139
|
+
const instantNanoseconds = (localSeconds - BigInt(offsetMinutes * 60)) * nanosecondsPerSecond
|
|
140
|
+
+ fractionalNanoseconds;
|
|
141
|
+
return {
|
|
142
|
+
year, month, day, hour, minute, second, fraction,
|
|
143
|
+
offsetText, offsetMinutes, instantNanoseconds
|
|
144
|
+
};
|
|
145
|
+
}
|
|
146
|
+
export function isValidDateTime(value) {
|
|
147
|
+
return parseDateTime(value) !== undefined;
|
|
148
|
+
}
|
|
149
|
+
export function isDateTimeUnit(value) {
|
|
150
|
+
return typeof value === 'string' && dateTimeUnitValues.includes(value);
|
|
151
|
+
}
|
|
152
|
+
export function nowLocalDateTime() {
|
|
153
|
+
const now = new Date();
|
|
154
|
+
const parts = {
|
|
155
|
+
year: BigInt(now.getFullYear()), month: now.getMonth() + 1, day: now.getDate(),
|
|
156
|
+
hour: now.getHours(), minute: now.getMinutes(), second: now.getSeconds()
|
|
157
|
+
};
|
|
158
|
+
return formatParts(parts, String(now.getMilliseconds()).padStart(3, '0'), localOffset(now));
|
|
159
|
+
}
|
|
160
|
+
export function createLocalDateTime(day, month, year, hours = 0, minutes = 0, seconds = 0) {
|
|
161
|
+
if (![day, month, year, hours, minutes, seconds].every(Number.isInteger)
|
|
162
|
+
|| year < 0 || year > 9999 || month < 1 || month > 12
|
|
163
|
+
|| day < 1 || day > daysInMonth(BigInt(year), month)
|
|
164
|
+
|| hours < 0 || hours > 23 || minutes < 0 || minutes > 59 || seconds < 0 || seconds > 59) {
|
|
165
|
+
throw new RangeError('Invalid DateTime calendar or clock fields');
|
|
166
|
+
}
|
|
167
|
+
const date = new Date(0);
|
|
168
|
+
date.setFullYear(year, month - 1, day);
|
|
169
|
+
date.setHours(hours, minutes, seconds, 0);
|
|
170
|
+
if (!Number.isFinite(date.getTime()))
|
|
171
|
+
throw new RangeError('DateTime fields are outside the host date range');
|
|
172
|
+
const parts = {
|
|
173
|
+
year: BigInt(date.getFullYear()), month: date.getMonth() + 1, day: date.getDate(),
|
|
174
|
+
hour: date.getHours(), minute: date.getMinutes(), second: date.getSeconds()
|
|
175
|
+
};
|
|
176
|
+
return formatParts(parts, '', localOffset(date));
|
|
177
|
+
}
|
|
178
|
+
export function dateTimeDifference(fromValue, toValue, unit) {
|
|
179
|
+
const from = requireParsedDateTime(fromValue);
|
|
180
|
+
const to = requireParsedDateTime(toValue);
|
|
181
|
+
const elapsed = to.instantNanoseconds - from.instantNanoseconds;
|
|
182
|
+
if (unit === 'days')
|
|
183
|
+
return Number(elapsed / nanosecondsPerDay);
|
|
184
|
+
if (unit === 'hours')
|
|
185
|
+
return Number(elapsed / nanosecondsPerHour);
|
|
186
|
+
if (unit === 'minutes')
|
|
187
|
+
return Number(elapsed / nanosecondsPerMinute);
|
|
188
|
+
if (unit === 'seconds')
|
|
189
|
+
return Number(elapsed / nanosecondsPerSecond);
|
|
190
|
+
const target = partsAtInstant(to.instantNanoseconds, from.offsetMinutes);
|
|
191
|
+
const monthDelta = (target.year - BigInt(from.year)) * 12n + BigInt(target.month - from.month);
|
|
192
|
+
let completed;
|
|
193
|
+
if (unit === 'months') {
|
|
194
|
+
completed = monthDelta;
|
|
195
|
+
const anniversary = shiftedCalendarParts(from, completed);
|
|
196
|
+
const anniversaryInstant = instantForCalendarParts(anniversary, from.fraction, from.offsetMinutes);
|
|
197
|
+
if (completed > 0n && anniversaryInstant > to.instantNanoseconds)
|
|
198
|
+
completed -= 1n;
|
|
199
|
+
else if (completed < 0n && anniversaryInstant < to.instantNanoseconds)
|
|
200
|
+
completed += 1n;
|
|
201
|
+
}
|
|
202
|
+
else {
|
|
203
|
+
completed = target.year - BigInt(from.year);
|
|
204
|
+
const anniversary = shiftedCalendarParts(from, completed * 12n);
|
|
205
|
+
const anniversaryInstant = instantForCalendarParts(anniversary, from.fraction, from.offsetMinutes);
|
|
206
|
+
if (completed > 0n && anniversaryInstant > to.instantNanoseconds)
|
|
207
|
+
completed -= 1n;
|
|
208
|
+
else if (completed < 0n && anniversaryInstant < to.instantNanoseconds)
|
|
209
|
+
completed += 1n;
|
|
210
|
+
}
|
|
211
|
+
return Number(completed);
|
|
212
|
+
}
|
|
213
|
+
function adjustDateTime(value, amount, unit, sign) {
|
|
214
|
+
const parsed = requireParsedDateTime(value);
|
|
215
|
+
if (!Number.isFinite(amount) || !Number.isInteger(amount))
|
|
216
|
+
throw new RangeError('DateTime arithmetic value must be a finite integer');
|
|
217
|
+
const displacement = BigInt(amount) * sign;
|
|
218
|
+
if (unit === 'years' || unit === 'months') {
|
|
219
|
+
const monthDelta = unit === 'years' ? displacement * 12n : displacement;
|
|
220
|
+
return formatParts(shiftedCalendarParts(parsed, monthDelta), parsed.fraction, parsed.offsetText);
|
|
221
|
+
}
|
|
222
|
+
const multiplier = unit === 'days' ? nanosecondsPerDay
|
|
223
|
+
: unit === 'hours' ? nanosecondsPerHour
|
|
224
|
+
: unit === 'minutes' ? nanosecondsPerMinute : nanosecondsPerSecond;
|
|
225
|
+
return formatInstant(parsed, parsed.instantNanoseconds + displacement * multiplier);
|
|
226
|
+
}
|
|
227
|
+
export function addToDateTime(value, amount, unit) {
|
|
228
|
+
return adjustDateTime(value, amount, unit, 1n);
|
|
229
|
+
}
|
|
230
|
+
export function subtractFromDateTime(value, amount, unit) {
|
|
231
|
+
return adjustDateTime(value, amount, unit, -1n);
|
|
232
|
+
}
|
|
@@ -1,4 +1,11 @@
|
|
|
1
1
|
import { throwUndefinedIdentifier } from '../diagnostics/errors';
|
|
2
|
+
const dateTimeUnitValues = ['years', 'months', 'days', 'hours', 'minutes', 'seconds'];
|
|
3
|
+
const dateTimeUnitDeclaration = {
|
|
4
|
+
type: 'enumDeclaration',
|
|
5
|
+
name: 'DateTimeUnit',
|
|
6
|
+
members: dateTimeUnitValues.map(name => ({ name })),
|
|
7
|
+
resolvedValues: [...dateTimeUnitValues]
|
|
8
|
+
};
|
|
2
9
|
/**
|
|
3
10
|
* Runtime environment for variable storage during evaluation.
|
|
4
11
|
* Variables are stored in declaration order (source order).
|
|
@@ -23,6 +30,8 @@ export class Environment {
|
|
|
23
30
|
this.recordTypes = recordTypes;
|
|
24
31
|
this.functions = functions;
|
|
25
32
|
this.dimensionRegistry = dimensionRegistry;
|
|
33
|
+
this.enumDeclarations.set('DateTimeUnit', dateTimeUnitDeclaration);
|
|
34
|
+
this.enumValues.set('DateTimeUnit', Object.fromEntries(dateTimeUnitValues.map(name => [name, name])));
|
|
26
35
|
}
|
|
27
36
|
/**
|
|
28
37
|
* Create an isolated call frame sharing this module's record types and functions
|
|
@@ -1,8 +1,10 @@
|
|
|
1
1
|
import { inputError, staticError, throwInputErrors, throwInvalidLoopIterable, throwInvalidRangeBounds, throwInvalidReturnContext, throwFunctionFallthrough, throwListOperationError, throwMeasurementDomainError } from '../diagnostics/errors';
|
|
2
2
|
import { Environment } from './environment';
|
|
3
3
|
import { evaluateStandardLibraryCall, isMathematicalFunction } from './standardLibrary';
|
|
4
|
+
import { isValidDateTime } from './dateTime';
|
|
4
5
|
import { fieldRegistry } from '../typechecker/declarationRegistry';
|
|
5
6
|
import { canonicalUnit, composeUnits, isAffineUnit, isMeasurement, measurement, measurementDisplayValue, measurementPhysicalValue, powerUnit, sqrtMeasurement, unitFromMetadata } from './measurement';
|
|
7
|
+
import { complexBinary, complexUnary, createComplex, isComplex } from './complex';
|
|
6
8
|
import { createDiagramModel } from './diagramModel';
|
|
7
9
|
export function validateRuntimeValue(value, expected, env, source, file, valuePath) {
|
|
8
10
|
const diagnostics = [];
|
|
@@ -123,10 +125,15 @@ export function validateRuntimeValue(value, expected, env, source, file, valuePa
|
|
|
123
125
|
report('Expected a finite Number value', target, actual, dataPath, fieldSource);
|
|
124
126
|
return;
|
|
125
127
|
}
|
|
128
|
+
if (target.name === 'Complex') {
|
|
129
|
+
if (!isComplex(actual))
|
|
130
|
+
report('Expected a finite Complex value', target, actual, dataPath, fieldSource);
|
|
131
|
+
return;
|
|
132
|
+
}
|
|
126
133
|
if (target.name === 'String' || target.name === 'DateTime') {
|
|
127
134
|
if (typeof actual !== 'string')
|
|
128
135
|
report(`Expected a ${target.name} value`, target, actual, dataPath, fieldSource);
|
|
129
|
-
else if (target.name === 'DateTime' && !
|
|
136
|
+
else if (target.name === 'DateTime' && !isValidDateTime(actual))
|
|
130
137
|
report('Invalid RFC 3339 DateTime value', target, actual, dataPath, fieldSource);
|
|
131
138
|
return;
|
|
132
139
|
}
|
|
@@ -273,17 +280,6 @@ function sameMeasurementVector(value, vector) {
|
|
|
273
280
|
return Object.keys(value.unit.vector).length === vector.size
|
|
274
281
|
&& [...vector].every(([identity, exponent]) => value.unit.vector[identity] === exponent);
|
|
275
282
|
}
|
|
276
|
-
function validDateTime(value) {
|
|
277
|
-
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})$/);
|
|
278
|
-
if (!parts)
|
|
279
|
-
return false;
|
|
280
|
-
const [, year, month, day, hour, minute, second, offset] = parts;
|
|
281
|
-
const date = new Date(0);
|
|
282
|
-
date.setUTCFullYear(+year, +month - 1, +day);
|
|
283
|
-
return date.getUTCFullYear() === +year && date.getUTCMonth() === +month - 1 && date.getUTCDate() === +day
|
|
284
|
-
&& +hour <= 23 && +minute <= 59 && +second <= 59
|
|
285
|
-
&& (offset === 'Z' || (+offset.slice(1, 3) <= 23 && +offset.slice(4) <= 59));
|
|
286
|
-
}
|
|
287
283
|
function matchesRuntimeType(value, target, env, file, registry = env.dimensionRegistry) {
|
|
288
284
|
if (target.type === 'nullableType') {
|
|
289
285
|
return value === null || matchesRuntimeType(value, target.element, env, file, registry);
|
|
@@ -297,12 +293,14 @@ function matchesRuntimeType(value, target, env, file, registry = env.dimensionRe
|
|
|
297
293
|
return isMeasurement(value) && sameMeasurementVector(value, dimension.vector);
|
|
298
294
|
if (name === 'Number')
|
|
299
295
|
return typeof value === 'number';
|
|
296
|
+
if (name === 'Complex')
|
|
297
|
+
return isComplex(value);
|
|
300
298
|
if (name === 'String')
|
|
301
299
|
return typeof value === 'string';
|
|
302
300
|
if (name === 'Boolean')
|
|
303
301
|
return typeof value === 'boolean';
|
|
304
302
|
if (name === 'DateTime')
|
|
305
|
-
return
|
|
303
|
+
return isValidDateTime(value);
|
|
306
304
|
const enumeration = env.enumDeclarations.get(name);
|
|
307
305
|
if (enumeration) {
|
|
308
306
|
if (typeof value !== 'number' && typeof value !== 'string')
|
|
@@ -354,6 +352,8 @@ export function evaluateExpression(node, env, file) {
|
|
|
354
352
|
return evalListAccess(node, env, file);
|
|
355
353
|
case 'numberLiteral':
|
|
356
354
|
return node.value;
|
|
355
|
+
case 'imaginaryLiteral':
|
|
356
|
+
return createComplex(0, node.coefficient, node.source, file);
|
|
357
357
|
case 'stringLiteral':
|
|
358
358
|
return node.value;
|
|
359
359
|
case 'stringInterpolation':
|
|
@@ -468,6 +468,9 @@ function evalBinary(node, env, file) {
|
|
|
468
468
|
}
|
|
469
469
|
return measurement(value, left.unit);
|
|
470
470
|
}
|
|
471
|
+
if (isComplex(left) || isComplex(right)) {
|
|
472
|
+
return complexBinary(node.operator, left, right, operatorSource, file);
|
|
473
|
+
}
|
|
471
474
|
const lNum = toNumber(left, node.left);
|
|
472
475
|
const rNum = toNumber(right, node.right);
|
|
473
476
|
return node.operator === '+' ? lNum + rNum : lNum - rNum;
|
|
@@ -505,6 +508,9 @@ function evalBinary(node, env, file) {
|
|
|
505
508
|
}
|
|
506
509
|
return measurement(value, unit);
|
|
507
510
|
}
|
|
511
|
+
if (isComplex(left) || isComplex(right)) {
|
|
512
|
+
return complexBinary(node.operator, left, right, operatorSource, file);
|
|
513
|
+
}
|
|
508
514
|
const lNum = toNumber(left, node.left);
|
|
509
515
|
const rNum = toNumber(right, node.right);
|
|
510
516
|
return node.operator === '*' ? lNum * rNum : lNum / rNum;
|
|
@@ -536,18 +542,24 @@ function evalBinary(node, env, file) {
|
|
|
536
542
|
return measurementPhysicalValue(result);
|
|
537
543
|
return result;
|
|
538
544
|
}
|
|
545
|
+
if (isComplex(left))
|
|
546
|
+
return complexBinary('^', left, right, operatorSource, file);
|
|
539
547
|
const lNum = toNumber(left, node.left);
|
|
540
548
|
const rNum = toNumber(right, node.right);
|
|
541
549
|
return Math.pow(lNum, rNum);
|
|
542
550
|
}
|
|
543
551
|
// Comparisons (produce boolean)
|
|
544
552
|
case '==':
|
|
553
|
+
if (isComplex(left) || isComplex(right))
|
|
554
|
+
return complexBinary('==', left, right, operatorSource, file);
|
|
545
555
|
if (isMeasurement(left) && isMeasurement(right)) {
|
|
546
556
|
return sameMeasurementVector(left, new Map(Object.entries(right.unit.vector)))
|
|
547
557
|
&& measurementPhysicalValue(left) === measurementPhysicalValue(right);
|
|
548
558
|
}
|
|
549
559
|
return left === right;
|
|
550
560
|
case '!=':
|
|
561
|
+
if (isComplex(left) || isComplex(right))
|
|
562
|
+
return complexBinary('!=', left, right, operatorSource, file);
|
|
551
563
|
if (isMeasurement(left) && isMeasurement(right)) {
|
|
552
564
|
return !sameMeasurementVector(left, new Map(Object.entries(right.unit.vector)))
|
|
553
565
|
|| measurementPhysicalValue(left) !== measurementPhysicalValue(right);
|
|
@@ -580,7 +592,11 @@ function evalBinary(node, env, file) {
|
|
|
580
592
|
}
|
|
581
593
|
function evalUnary(node, env, file) {
|
|
582
594
|
const arg = evaluateExpression(node.argument, env, file);
|
|
595
|
+
if (node.operator === '+' && isComplex(arg))
|
|
596
|
+
return complexUnary('+', arg, node.source, file);
|
|
583
597
|
if (node.operator === '-') {
|
|
598
|
+
if (isComplex(arg))
|
|
599
|
+
return complexUnary('-', arg, node.source, file);
|
|
584
600
|
if (isMeasurement(arg))
|
|
585
601
|
return measurement(-arg.value, arg.unit);
|
|
586
602
|
return -toNumber(arg, node.argument);
|
|
@@ -616,13 +632,13 @@ export function evaluateUnaryValue(operator, value, source, file) {
|
|
|
616
632
|
source
|
|
617
633
|
}, environment, file);
|
|
618
634
|
}
|
|
619
|
-
export function evaluateBuiltinValues(callee, values, source, file, dimensionRegistry) {
|
|
635
|
+
export function evaluateBuiltinValues(callee, values, source, file, dimensionRegistry, argumentSources = []) {
|
|
620
636
|
const environment = new Environment();
|
|
621
637
|
environment.dimensionRegistry = dimensionRegistry;
|
|
622
638
|
const argumentsList = values.map((value, index) => {
|
|
623
639
|
const name = `__amxRuntimeArgument${index}`;
|
|
624
640
|
environment.set(name, value);
|
|
625
|
-
return { type: 'identifier', name, source };
|
|
641
|
+
return { type: 'identifier', name, source: argumentSources[index] ?? source };
|
|
626
642
|
});
|
|
627
643
|
return evalFunctionCall({
|
|
628
644
|
type: 'functionCall',
|
|
@@ -1005,6 +1021,8 @@ export function evaluateStatements(statements, env, file) {
|
|
|
1005
1021
|
}
|
|
1006
1022
|
}
|
|
1007
1023
|
function snapshotValue(value) {
|
|
1024
|
+
if (isComplex(value))
|
|
1025
|
+
return value;
|
|
1008
1026
|
if (isMeasurement(value))
|
|
1009
1027
|
return `${value.value} ${value.unit.text}`;
|
|
1010
1028
|
if (Array.isArray(value))
|
|
@@ -6,6 +6,7 @@ import { parseStrictCsvText, parseStrictJsonText } from './dataText';
|
|
|
6
6
|
import { isMeasurement, measurement, measurementPhysicalValue } from './measurement';
|
|
7
7
|
import { ExternalUnitTextError, parseExternalUnitText } from './externalUnits';
|
|
8
8
|
import { fieldRegistry } from '../typechecker/declarationRegistry';
|
|
9
|
+
import { isValidDateTime } from './dateTime';
|
|
9
10
|
function defaultsEnvironment(environment, registry) {
|
|
10
11
|
return registry && environment.dimensionRegistry !== registry
|
|
11
12
|
? new Environment(environment.recordTypes, environment.functions, registry)
|
|
@@ -204,7 +205,7 @@ function convertJson(value, annotation, pointer, declarationSource, types, envir
|
|
|
204
205
|
report(shapeDiagnostic(name === 'DateTime' ? 'Expected an RFC 3339 DateTime string' : 'Input value has the wrong scalar type', name, describe(value), pointer, context, declarationSource, fieldSource));
|
|
205
206
|
return value;
|
|
206
207
|
}
|
|
207
|
-
if (name === 'DateTime' && !
|
|
208
|
+
if (name === 'DateTime' && !isValidDateTime(value)) {
|
|
208
209
|
report(shapeDiagnostic('Invalid RFC 3339 DateTime value', name, describe(value), pointer, context, declarationSource, fieldSource));
|
|
209
210
|
}
|
|
210
211
|
return value;
|
|
@@ -381,7 +382,7 @@ function convertCsvCell(cell, annotation, dataPath, recordNumber, columnNumber,
|
|
|
381
382
|
return Number(cell.value);
|
|
382
383
|
}
|
|
383
384
|
if (base.name === 'DateTime') {
|
|
384
|
-
if (!
|
|
385
|
+
if (!isValidDateTime(cell.value))
|
|
385
386
|
report(shapeDiagnostic('Invalid RFC 3339 DateTime CSV cell', 'DateTime', cell.value, dataPath, location, undefined, fieldSource));
|
|
386
387
|
return cell.value;
|
|
387
388
|
}
|
|
@@ -522,17 +523,6 @@ function validateCsvEnumValue(value, name, declaration, dataPath, context, field
|
|
|
522
523
|
report(shapeDiagnostic(`Value is not a member of enum '${name}'`, name, String(value), dataPath, context, undefined, fieldSource));
|
|
523
524
|
}
|
|
524
525
|
}
|
|
525
|
-
function isDateTime(value) {
|
|
526
|
-
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})$/);
|
|
527
|
-
if (!parts)
|
|
528
|
-
return false;
|
|
529
|
-
const [, year, month, day, hour, minute, second, offset] = parts;
|
|
530
|
-
const date = new Date(0);
|
|
531
|
-
date.setUTCFullYear(+year, +month - 1, +day);
|
|
532
|
-
return date.getUTCFullYear() === +year && date.getUTCMonth() === +month - 1 && date.getUTCDate() === +day
|
|
533
|
-
&& +hour <= 23 && +minute <= 59 && +second <= 59
|
|
534
|
-
&& (offset === 'Z' || (+offset.slice(1, 3) <= 23 && +offset.slice(4) <= 59));
|
|
535
|
-
}
|
|
536
526
|
function actualType(value) {
|
|
537
527
|
if (value === null)
|
|
538
528
|
return 'null';
|
|
@@ -2,6 +2,8 @@ import * as path from 'path';
|
|
|
2
2
|
import { outputError } from '../diagnostics/errors';
|
|
3
3
|
import { isMeasurement, measurementPhysicalValue } from './measurement';
|
|
4
4
|
import { fieldRegistry } from '../typechecker/declarationRegistry';
|
|
5
|
+
import { isValidDateTime } from './dateTime';
|
|
6
|
+
import { formatComplex, isComplex } from './complex';
|
|
5
7
|
function typeName(type) {
|
|
6
8
|
if (type.kind === 'named')
|
|
7
9
|
return type.name;
|
|
@@ -12,7 +14,7 @@ function typeName(type) {
|
|
|
12
14
|
return type.kind === 'list' ? `${typeName(type.element)}[]` : `${typeName(type.element)}?`;
|
|
13
15
|
}
|
|
14
16
|
function isPrimitive(type) {
|
|
15
|
-
return type.kind === 'named' && ['Number', 'String', 'Boolean', 'DateTime'].includes(type.name);
|
|
17
|
+
return type.kind === 'named' && ['Number', 'String', 'Boolean', 'DateTime', 'Complex'].includes(type.name);
|
|
16
18
|
}
|
|
17
19
|
function isCsvScalar(type) {
|
|
18
20
|
return type.kind === 'measurement' || isPrimitive(type) || (type.kind === 'nullable' && isCsvScalar(type.element));
|
|
@@ -163,9 +165,16 @@ function jsonValue(value, type, output, recordTypes, registry) {
|
|
|
163
165
|
return invalidValue(output, `expected a finite Number, got ${String(value)}`);
|
|
164
166
|
return value;
|
|
165
167
|
}
|
|
168
|
+
if (type.name === 'Complex') {
|
|
169
|
+
if (!isComplex(value))
|
|
170
|
+
return invalidValue(output, 'expected a finite Complex value');
|
|
171
|
+
return { real: value.real, imaginary: value.imaginary };
|
|
172
|
+
}
|
|
166
173
|
if (type.name === 'String' || type.name === 'DateTime') {
|
|
167
174
|
if (typeof value !== 'string')
|
|
168
175
|
return invalidValue(output, `expected ${type.name}`);
|
|
176
|
+
if (type.name === 'DateTime' && !isValidDateTime(value))
|
|
177
|
+
return invalidValue(output, 'expected a valid offset-bearing DateTime');
|
|
169
178
|
return value;
|
|
170
179
|
}
|
|
171
180
|
if (type.name === 'Boolean') {
|
|
@@ -210,7 +219,12 @@ function csvCell(value, type, output, registry) {
|
|
|
210
219
|
}
|
|
211
220
|
if (type.kind !== 'named')
|
|
212
221
|
return invalidValue(output, `unsupported CSV cell type ${typeName(type)}`);
|
|
213
|
-
if (type.name === '
|
|
222
|
+
if (type.name === 'Complex') {
|
|
223
|
+
if (!isComplex(value))
|
|
224
|
+
return invalidValue(output, 'expected a finite Complex value');
|
|
225
|
+
text = formatComplex(value);
|
|
226
|
+
}
|
|
227
|
+
else if (type.name === 'Number') {
|
|
214
228
|
if (typeof value !== 'number' || !Number.isFinite(value))
|
|
215
229
|
return invalidValue(output, `expected a finite Number, got ${String(value)}`);
|
|
216
230
|
text = JSON.stringify(value);
|
|
@@ -223,6 +237,8 @@ function csvCell(value, type, output, registry) {
|
|
|
223
237
|
else if (type.name === 'String' || type.name === 'DateTime') {
|
|
224
238
|
if (typeof value !== 'string')
|
|
225
239
|
return invalidValue(output, `expected ${type.name}`);
|
|
240
|
+
if (type.name === 'DateTime' && !isValidDateTime(value))
|
|
241
|
+
return invalidValue(output, 'expected a valid offset-bearing DateTime');
|
|
226
242
|
text = value;
|
|
227
243
|
}
|
|
228
244
|
else {
|
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
import { AmxError } from '../diagnostics/errors';
|
|
2
2
|
import { isMeasurement } from './measurement';
|
|
3
|
+
import { complexBuiltin, isComplex } from './complex';
|
|
4
|
+
import { addToDateTime, createLocalDateTime, dateTimeDifference, isDateTimeUnit, isValidDateTime, nowLocalDateTime, subtractFromDateTime } from './dateTime';
|
|
3
5
|
/**
|
|
4
6
|
* Standard library for OpenAMX v0.1.
|
|
5
7
|
*
|
|
@@ -117,6 +119,34 @@ function ensureLibraryArity(callee, args, min, max, source, file) {
|
|
|
117
119
|
throw libraryError('AMX3004', `Invalid arity for '${callee}'`, source, file);
|
|
118
120
|
}
|
|
119
121
|
}
|
|
122
|
+
function dateTimeIntegerArgument(callee, value, label, source, file) {
|
|
123
|
+
if (typeof value !== 'number' || !Number.isFinite(value) || !Number.isInteger(value)) {
|
|
124
|
+
throw libraryError('AMX3002', `${callee} requires a finite integer Number for ${label}`, source, file);
|
|
125
|
+
}
|
|
126
|
+
return value;
|
|
127
|
+
}
|
|
128
|
+
function dateTimeArgument(callee, value, source, file) {
|
|
129
|
+
if (typeof value !== 'string' || !isValidDateTime(value)) {
|
|
130
|
+
throw libraryError('AMX3002', `${callee} requires a valid offset-bearing DateTime`, source, file);
|
|
131
|
+
}
|
|
132
|
+
return value;
|
|
133
|
+
}
|
|
134
|
+
function dateTimeUnitArgument(callee, value, source, file) {
|
|
135
|
+
if (!isDateTimeUnit(value)) {
|
|
136
|
+
throw libraryError('AMX3002', `${callee} requires a DateTimeUnit member`, source, file);
|
|
137
|
+
}
|
|
138
|
+
return value;
|
|
139
|
+
}
|
|
140
|
+
function runDateTimeOperation(action, source, file) {
|
|
141
|
+
try {
|
|
142
|
+
return action();
|
|
143
|
+
}
|
|
144
|
+
catch (error) {
|
|
145
|
+
if (error instanceof RangeError)
|
|
146
|
+
throw libraryError('AMX3002', error.message, source, file);
|
|
147
|
+
throw error;
|
|
148
|
+
}
|
|
149
|
+
}
|
|
120
150
|
function textArgument(callee, value, source, file) {
|
|
121
151
|
if (typeof value !== 'string') {
|
|
122
152
|
throw libraryError('AMX3002', `${callee} requires a String, got ${runtimeType(value)}`, source, file);
|
|
@@ -199,6 +229,36 @@ function formatNumericValue(value, pattern, locale) {
|
|
|
199
229
|
}
|
|
200
230
|
export function evaluateStandardLibraryCall(callee, args, source, file, argumentSources = []) {
|
|
201
231
|
const argumentSource = (index) => argumentSources[index] ?? source;
|
|
232
|
+
if (callee === 'now') {
|
|
233
|
+
ensureLibraryArity(callee, args, 0, 0, source, file);
|
|
234
|
+
return nowLocalDateTime();
|
|
235
|
+
}
|
|
236
|
+
if (callee === 'createDateTime') {
|
|
237
|
+
ensureLibraryArity(callee, args, 3, 6, source, file);
|
|
238
|
+
const day = dateTimeIntegerArgument(callee, args[0], 'day', argumentSource(0), file);
|
|
239
|
+
const month = dateTimeIntegerArgument(callee, args[1], 'month', argumentSource(1), file);
|
|
240
|
+
const year = dateTimeIntegerArgument(callee, args[2], 'year', argumentSource(2), file);
|
|
241
|
+
const hours = args.length > 3 ? dateTimeIntegerArgument(callee, args[3], 'hours', argumentSource(3), file) : 0;
|
|
242
|
+
const minutes = args.length > 4 ? dateTimeIntegerArgument(callee, args[4], 'minutes', argumentSource(4), file) : 0;
|
|
243
|
+
const seconds = args.length > 5 ? dateTimeIntegerArgument(callee, args[5], 'seconds', argumentSource(5), file) : 0;
|
|
244
|
+
return runDateTimeOperation(() => createLocalDateTime(day, month, year, hours, minutes, seconds), argumentSource(0), file);
|
|
245
|
+
}
|
|
246
|
+
if (callee === 'dateDiff') {
|
|
247
|
+
ensureLibraryArity(callee, args, 3, 3, source, file);
|
|
248
|
+
const from = dateTimeArgument(callee, args[0], argumentSource(0), file);
|
|
249
|
+
const to = dateTimeArgument(callee, args[1], argumentSource(1), file);
|
|
250
|
+
const unit = dateTimeUnitArgument(callee, args[2], argumentSource(2), file);
|
|
251
|
+
return runDateTimeOperation(() => dateTimeDifference(from, to, unit), source, file);
|
|
252
|
+
}
|
|
253
|
+
if (callee === 'addToDateTime' || callee === 'subtractFromDateTime') {
|
|
254
|
+
ensureLibraryArity(callee, args, 3, 3, source, file);
|
|
255
|
+
const value = dateTimeArgument(callee, args[0], argumentSource(0), file);
|
|
256
|
+
const amount = dateTimeIntegerArgument(callee, args[1], 'value', argumentSource(1), file);
|
|
257
|
+
const unit = dateTimeUnitArgument(callee, args[2], argumentSource(2), file);
|
|
258
|
+
return runDateTimeOperation(() => callee === 'addToDateTime'
|
|
259
|
+
? addToDateTime(value, amount, unit)
|
|
260
|
+
: subtractFromDateTime(value, amount, unit), source, file);
|
|
261
|
+
}
|
|
202
262
|
if (callee === 'len') {
|
|
203
263
|
ensureLibraryArity(callee, args, 1, 1, source, file);
|
|
204
264
|
const value = args[0];
|
|
@@ -255,6 +315,12 @@ export function evaluateStandardLibraryCall(callee, args, source, file, argument
|
|
|
255
315
|
});
|
|
256
316
|
}
|
|
257
317
|
const value = args[0];
|
|
318
|
+
if (isComplex(value)) {
|
|
319
|
+
if (callee === 'sin' || callee === 'cos' || callee === 'exp' || callee === 'log') {
|
|
320
|
+
return complexBuiltin(callee, value, source, file);
|
|
321
|
+
}
|
|
322
|
+
throw libraryError('AMX3002', `Expected Number or dimensionless Measurement, got Complex`, argumentSource(0), file);
|
|
323
|
+
}
|
|
258
324
|
if (typeof value !== 'number') {
|
|
259
325
|
const actual = value === null ? 'null'
|
|
260
326
|
: Array.isArray(value) ? 'list'
|
|
@@ -279,6 +345,15 @@ export function evaluateStandardLibraryCall(callee, args, source, file, argument
|
|
|
279
345
|
return result;
|
|
280
346
|
}
|
|
281
347
|
switch (callee) {
|
|
348
|
+
case 'conjugate':
|
|
349
|
+
case 'arg': {
|
|
350
|
+
ensureArgCount(args, 1, callee, source, file);
|
|
351
|
+
const value = args[0];
|
|
352
|
+
if (!isComplex(value)) {
|
|
353
|
+
throw libraryError('AMX3002', `Expected Complex, got ${runtimeType(value)}`, argumentSource(0), file);
|
|
354
|
+
}
|
|
355
|
+
return complexBuiltin(callee, value, argumentSource(0), file);
|
|
356
|
+
}
|
|
282
357
|
case 'sum': {
|
|
283
358
|
ensureArgCount(args, 1, 'sum', source, file);
|
|
284
359
|
const list = ensureList(args[0], 'sum', source, file);
|
|
@@ -321,11 +396,15 @@ export function evaluateStandardLibraryCall(callee, args, source, file, argument
|
|
|
321
396
|
}
|
|
322
397
|
case 'abs': {
|
|
323
398
|
ensureArgCount(args, 1, 'abs', source, file);
|
|
399
|
+
if (isComplex(args[0]))
|
|
400
|
+
return complexBuiltin('abs', args[0], argumentSource(0), file);
|
|
324
401
|
const value = ensureNumber(args[0], 'abs value', source, file);
|
|
325
402
|
return Math.abs(value);
|
|
326
403
|
}
|
|
327
404
|
case 'sqrt': {
|
|
328
405
|
ensureArgCount(args, 1, 'sqrt', source, file);
|
|
406
|
+
if (isComplex(args[0]))
|
|
407
|
+
return complexBuiltin('sqrt', args[0], argumentSource(0), file);
|
|
329
408
|
const value = ensureNumber(args[0], 'sqrt value', source, file);
|
|
330
409
|
if (value < 0) {
|
|
331
410
|
const loc = source ? ` at line ${source.line}` : '';
|
|
@@ -1,9 +1,12 @@
|
|
|
1
1
|
import { isMeasurement } from './measurement';
|
|
2
|
+
import { formatComplex, isComplex } from './complex';
|
|
2
3
|
export function formatAmxValue(value, nullText = '') {
|
|
3
4
|
if (value === null || value === undefined)
|
|
4
5
|
return nullText;
|
|
5
6
|
if (Array.isArray(value))
|
|
6
7
|
return value.map(item => formatAmxValue(item, nullText)).join(', ');
|
|
8
|
+
if (isComplex(value))
|
|
9
|
+
return formatComplex(value);
|
|
7
10
|
if (isMeasurement(value))
|
|
8
11
|
return `${String(value.value)} ${value.unit.text}`;
|
|
9
12
|
if (typeof value === 'object')
|