@nova-energy/openamx 0.21.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.
@@ -0,0 +1,131 @@
1
+ import ComplexMath from 'complex.js';
2
+ import { AmxError } from '../diagnostics/errors';
3
+ const complexValueBrand = Symbol('openamx-complex');
4
+ function normalized(value) {
5
+ return value === 0 ? 0 : value;
6
+ }
7
+ function complexError(code, message, source, file) {
8
+ throw new AmxError({ code, message, file, line: source?.line, column: source?.column });
9
+ }
10
+ function invalidDomain(source, file, message = 'Invalid input for mathematical function') {
11
+ return complexError('AMXSL001', message, source, file);
12
+ }
13
+ function nonFiniteResult(source, file) {
14
+ return complexError('AMXSL002', 'Function evaluation results in infinite result', source, file);
15
+ }
16
+ function finite(value, source, file) {
17
+ if (!Number.isFinite(value))
18
+ return nonFiniteResult(source, file);
19
+ return normalized(value);
20
+ }
21
+ export function createComplex(real, imaginary, source, file) {
22
+ const value = {
23
+ real: finite(real, source, file),
24
+ imaginary: finite(imaginary, source, file)
25
+ };
26
+ Object.defineProperty(value, complexValueBrand, { value: true });
27
+ return Object.freeze(value);
28
+ }
29
+ export function isComplex(value) {
30
+ if (typeof value !== 'object' || value === null)
31
+ return false;
32
+ try {
33
+ const candidate = value;
34
+ return candidate[complexValueBrand] === true
35
+ && Object.isFrozen(value)
36
+ && Number.isFinite(candidate.real)
37
+ && Number.isFinite(candidate.imaginary)
38
+ && !Object.is(candidate.real, -0)
39
+ && !Object.is(candidate.imaginary, -0);
40
+ }
41
+ catch {
42
+ return false;
43
+ }
44
+ }
45
+ function fromLibrary(value, source, file) {
46
+ return createComplex(value.re, value.im, source, file);
47
+ }
48
+ function toLibrary(value) {
49
+ return new ComplexMath(value.real, value.imaginary);
50
+ }
51
+ function promote(value, source, file) {
52
+ if (isComplex(value))
53
+ return value;
54
+ if (typeof value === 'number')
55
+ return createComplex(value, 0, source, file);
56
+ return invalidDomain(source, file, 'Invalid input for Complex operation');
57
+ }
58
+ export function complexUnary(operator, value, source, file) {
59
+ const operand = promote(value, source, file);
60
+ return operator === '+'
61
+ ? operand
62
+ : createComplex(-operand.real, -operand.imaginary, source, file);
63
+ }
64
+ export function complexBinary(operator, leftValue, rightValue, source, file) {
65
+ const left = promote(leftValue, source, file);
66
+ if (operator === '==' || operator === '!=') {
67
+ const right = promote(rightValue, source, file);
68
+ const equal = left.real === right.real && left.imaginary === right.imaginary;
69
+ return operator === '==' ? equal : !equal;
70
+ }
71
+ if (operator === '^') {
72
+ if (typeof rightValue !== 'number' || !Number.isFinite(rightValue)) {
73
+ return invalidDomain(source, file, 'Invalid Complex exponent');
74
+ }
75
+ if (left.real === 0 && left.imaginary === 0) {
76
+ if (rightValue < 0)
77
+ return invalidDomain(source, file, 'Zero cannot be raised to a negative exponent');
78
+ return createComplex(rightValue === 0 ? 1 : 0, 0, source, file);
79
+ }
80
+ return fromLibrary(toLibrary(left).pow(rightValue), source, file);
81
+ }
82
+ const right = promote(rightValue, source, file);
83
+ const leftComplex = toLibrary(left);
84
+ const rightComplex = toLibrary(right);
85
+ switch (operator) {
86
+ case '+': return fromLibrary(leftComplex.add(rightComplex), source, file);
87
+ case '-': return fromLibrary(leftComplex.sub(rightComplex), source, file);
88
+ case '*': return fromLibrary(leftComplex.mul(rightComplex), source, file);
89
+ case '/':
90
+ if (right.real === 0 && right.imaginary === 0) {
91
+ return invalidDomain(source, file, 'Complex division by zero');
92
+ }
93
+ return fromLibrary(leftComplex.div(rightComplex), source, file);
94
+ }
95
+ }
96
+ export function complexBuiltin(name, value, source, file) {
97
+ if (name === 'abs')
98
+ return finite(Math.hypot(value.real, value.imaginary), source, file);
99
+ if (name === 'arg') {
100
+ if (value.real === 0 && value.imaginary === 0)
101
+ return invalidDomain(source, file, 'Argument of zero is undefined');
102
+ const angle = Math.atan2(value.imaginary, value.real);
103
+ return finite(angle <= -Math.PI ? Math.PI : angle, source, file);
104
+ }
105
+ if (name === 'log' && value.real === 0 && value.imaginary === 0) {
106
+ return invalidDomain(source, file, 'Logarithm of zero is undefined');
107
+ }
108
+ const operand = toLibrary(value);
109
+ switch (name) {
110
+ case 'conjugate': return fromLibrary(operand.conjugate(), source, file);
111
+ case 'sqrt': return fromLibrary(operand.sqrt(), source, file);
112
+ case 'exp': return fromLibrary(operand.exp(), source, file);
113
+ case 'log': {
114
+ const naturalLog = operand.log();
115
+ return createComplex(naturalLog.re / Math.LN10, naturalLog.im / Math.LN10, source, file);
116
+ }
117
+ case 'sin': return fromLibrary(operand.sin(), source, file);
118
+ case 'cos': return fromLibrary(operand.cos(), source, file);
119
+ }
120
+ }
121
+ export function formatComplex(value) {
122
+ const real = normalized(value.real);
123
+ const imaginary = normalized(value.imaginary);
124
+ if (imaginary === 0)
125
+ return real === 0 ? '0' : String(real);
126
+ const coefficient = Math.abs(imaginary) === 1 ? '' : String(Math.abs(imaginary));
127
+ const imaginaryTerm = `${coefficient}im`;
128
+ if (real === 0)
129
+ return imaginary < 0 ? `-${imaginaryTerm}` : imaginaryTerm;
130
+ return `${String(real)}${imaginary < 0 ? '-' : '+'}${imaginaryTerm}`;
131
+ }
@@ -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,6 +1,6 @@
1
1
  import { Environment } from './environment';
2
- import { evaluateStatements } from './evaluateExpression';
3
- import { checkDocument } from '../typechecker/checkDocument';
2
+ import { checkDocumentWithRuntimePlan } from '../typechecker/checkDocument';
3
+ import { evaluateDocumentNodes, prepareTypeScriptBlocks } from './typescriptBridge';
4
4
  /**
5
5
  * Evaluate an OpenAmxDocument in source order.
6
6
  * - Only executable code-block statements are processed.
@@ -13,20 +13,15 @@ export function evaluateDocument(doc, file) {
13
13
  }
14
14
  /** Evaluate executable blocks once and return their shared final environment. */
15
15
  export function evaluateDocumentEnvironment(doc, file) {
16
- const checked = checkDocument(doc, file);
16
+ const checked = checkDocumentWithRuntimePlan(doc, file);
17
+ const prepared = prepareTypeScriptBlocks(checked.typescriptBlocks, file);
17
18
  const env = new Environment(new Map(), new Map(), {
18
- dimensions: checked.dimensions,
19
- units: checked.units,
20
- baseUnits: checked.baseUnits
19
+ dimensions: checked.result.dimensions,
20
+ units: checked.result.units,
21
+ baseUnits: checked.result.baseUnits
21
22
  });
22
- for (const [name, type] of checked.bindingTypes)
23
+ for (const [name, type] of checked.result.bindingTypes)
23
24
  env.bindingTypes.set(name, type);
24
- for (let nodeIndex = 0; nodeIndex < doc.nodes.length; nodeIndex++) {
25
- const node = doc.nodes[nodeIndex];
26
- if (node.type === 'executableCodeBlock') {
27
- env.currentDocumentNodeIndex = nodeIndex;
28
- evaluateStatements(node.statements, env, file);
29
- }
30
- }
25
+ evaluateDocumentNodes(doc, env, file, checked.typescriptBlocks, prepared);
31
26
  return env;
32
27
  }