@nova-energy/openamx 0.0.0-stage → 0.11.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.
Files changed (44) hide show
  1. package/COMMERCIAL-LICENSE.md +74 -0
  2. package/LICENSE.md +660 -0
  3. package/README.md +537 -3
  4. package/dist/ast/types.js +2 -0
  5. package/dist/cli.js +197 -0
  6. package/dist/diagnostics/errors.js +94 -0
  7. package/dist/editor/completion.js +313 -0
  8. package/dist/editor/highlighting.js +224 -0
  9. package/dist/editor/moduleAnalysis.js +206 -0
  10. package/dist/editor/refactoring.js +46 -0
  11. package/dist/editor/sourceRanges.js +50 -0
  12. package/dist/editor/symbols.js +203 -0
  13. package/dist/formatter/formatAmx.js +79 -0
  14. package/dist/index.js +10 -0
  15. package/dist/parser/parseDocument.js +114 -0
  16. package/dist/parser/parseExpression.js +768 -0
  17. package/dist/parser/parseFor.js +53 -0
  18. package/dist/parser/parseFrontMatter.js +65 -0
  19. package/dist/parser/parseStatements.js +667 -0
  20. package/dist/parser/stringScanner.js +71 -0
  21. package/dist/renderer/chartModel.js +476 -0
  22. package/dist/renderer/narrativeModel.js +561 -0
  23. package/dist/renderer/renderHtml.js +521 -0
  24. package/dist/renderer/reportDocx.js +725 -0
  25. package/dist/renderer/reportPaths.js +31 -0
  26. package/dist/renderer/reportPdf.js +314 -0
  27. package/dist/renderer/reportPreparation.js +196 -0
  28. package/dist/runtime/csvTextSerialization.js +8 -0
  29. package/dist/runtime/dataText.js +191 -0
  30. package/dist/runtime/docxDestination.js +55 -0
  31. package/dist/runtime/environment.js +105 -0
  32. package/dist/runtime/evaluateDocument.js +32 -0
  33. package/dist/runtime/evaluateExpression.js +888 -0
  34. package/dist/runtime/externalUnits.js +91 -0
  35. package/dist/runtime/inputData.js +508 -0
  36. package/dist/runtime/measurement.js +110 -0
  37. package/dist/runtime/moduleLoader.js +279 -0
  38. package/dist/runtime/outputData.js +303 -0
  39. package/dist/runtime/pdfDestination.js +57 -0
  40. package/dist/runtime/standardLibrary.js +145 -0
  41. package/dist/typechecker/checkDocument.js +1282 -0
  42. package/dist/typechecker/declarationRegistry.js +7 -0
  43. package/dist/typechecker/dimensionTypes.js +1 -0
  44. package/package.json +33 -4
@@ -0,0 +1,768 @@
1
+ import { parseForExpression } from './parseFor';
2
+ import { AmxError, syntaxError } from '../diagnostics/errors';
3
+ import { findInterpolationEnd as findInterpolationClose, findStringLiteralEnd } from './stringScanner';
4
+ function tokenize(text, source) {
5
+ const tokens = [];
6
+ let i = 0;
7
+ const len = text.length;
8
+ function skipWs() {
9
+ while (i < len && /\s/.test(text[i]))
10
+ i++;
11
+ }
12
+ while (i < len) {
13
+ skipWs();
14
+ if (i >= len)
15
+ break;
16
+ const ch = text[i];
17
+ if (text.startsWith('for', i) && !/[A-Za-z0-9_]/.test(text[i + 3] ?? '')) {
18
+ const end = findForExpressionEnd(text, i, source);
19
+ const loopText = text.slice(i, end + 1);
20
+ tokens.push({ type: 'forExpression', value: loopText, text: loopText, offset: i });
21
+ i = end + 1;
22
+ continue;
23
+ }
24
+ if (text.startsWith('match', i) && !/[A-Za-z0-9_]/.test(text[i + 5] ?? '')) {
25
+ const end = findMatchExpressionEnd(text, i, source);
26
+ const matchText = text.slice(i, end + 1);
27
+ tokens.push({ type: 'matchExpression', value: matchText, text: matchText, offset: i });
28
+ i = end + 1;
29
+ continue;
30
+ }
31
+ // Number literal: digits, optional decimal part. No sign here (unary minus is separate).
32
+ if (/\d/.test(ch)) {
33
+ let j = i;
34
+ while (j < len && /\d/.test(text[j]))
35
+ j++;
36
+ if (text[j] === '.') {
37
+ j++;
38
+ while (j < len && /\d/.test(text[j]))
39
+ j++;
40
+ }
41
+ const numStr = text.slice(i, j);
42
+ tokens.push({ type: 'number', value: Number(numStr), text: numStr, offset: i });
43
+ i = j;
44
+ continue;
45
+ }
46
+ // String literal "..." or '...'
47
+ if (ch === '"' || ch === "'") {
48
+ const end = findStringEnd(text, i, source);
49
+ const literal = text.slice(i, end + 1);
50
+ tokens.push({ type: 'string', value: literal.slice(1, -1), text: literal, offset: i });
51
+ i = end + 1;
52
+ continue;
53
+ }
54
+ // Identifier or boolean literal
55
+ if (/[A-Za-z]/.test(ch)) {
56
+ let j = i;
57
+ while (j < len && /[A-Za-z0-9_]/.test(text[j]))
58
+ j++;
59
+ const word = text.slice(i, j);
60
+ if (word === 'true') {
61
+ tokens.push({ type: 'boolean', value: true, text: word, offset: i });
62
+ }
63
+ else if (word === 'false') {
64
+ tokens.push({ type: 'boolean', value: false, text: word, offset: i });
65
+ }
66
+ else if (word === 'null') {
67
+ tokens.push({ type: 'null', text: word, offset: i });
68
+ }
69
+ else if (word === 'and' || word === 'or' || word === 'not' || word === 'if' || word === 'then' || word === 'else') {
70
+ tokens.push({ type: 'keyword', word: word, text: word });
71
+ }
72
+ else {
73
+ tokens.push({ type: 'identifier', name: word, text: word, offset: i });
74
+ }
75
+ i = j;
76
+ continue;
77
+ }
78
+ // Two-character comparison operators
79
+ if (ch === '=' || ch === '!' || ch === '>' || ch === '<') {
80
+ const two = text.slice(i, i + 2);
81
+ if (two === '==' || two === '!=' || two === '>=' || two === '<=') {
82
+ tokens.push({ type: 'operator', op: two, text: two, offset: i });
83
+ i += 2;
84
+ continue;
85
+ }
86
+ }
87
+ // Single-character comparison operators (bare > < after two-char check)
88
+ if (ch === '>' || ch === '<') {
89
+ tokens.push({ type: 'operator', op: ch, text: ch, offset: i });
90
+ i++;
91
+ continue;
92
+ }
93
+ // Single-character operators and grouping
94
+ if ('+-*/%^()[].,{}:='.includes(ch)) {
95
+ if (ch === '(') {
96
+ tokens.push({ type: 'lparen', text: ch, offset: i });
97
+ }
98
+ else if (ch === ')') {
99
+ tokens.push({ type: 'rparen', text: ch, offset: i });
100
+ }
101
+ else if (ch === '[') {
102
+ tokens.push({ type: 'lbracket', text: ch, offset: i });
103
+ }
104
+ else if (ch === ']') {
105
+ tokens.push({ type: 'rbracket', text: ch, offset: i });
106
+ }
107
+ else if (ch === ',') {
108
+ tokens.push({ type: 'comma', text: ch, offset: i });
109
+ }
110
+ else if (ch === '{' || ch === '}' || ch === ':' || ch === '=' || ch === '.') {
111
+ tokens.push({ type: { '{': 'lbrace', '}': 'rbrace', ':': 'colon', '=': 'equals', '.': 'dot' }[ch], text: ch, offset: i });
112
+ }
113
+ else {
114
+ tokens.push({ type: 'operator', op: ch, text: ch, offset: i });
115
+ }
116
+ i++;
117
+ continue;
118
+ }
119
+ throw new Error(`Unexpected character '${ch}' in expression at position ${i}`);
120
+ }
121
+ tokens.push({ type: 'eof' });
122
+ return tokens;
123
+ }
124
+ function findStringEnd(text, start, source) {
125
+ const quote = text[start];
126
+ for (let index = start + 1; index < text.length; index++) {
127
+ const character = text[index];
128
+ if (character === '\r' || character === '\n') {
129
+ syntaxError('Raw strings must remain on one line', locationAt(text, index, source));
130
+ }
131
+ if (character === '\\') {
132
+ const escaped = text[index + 1];
133
+ if (escaped === undefined) {
134
+ syntaxError('Incomplete string escape', locationAt(text, index, source));
135
+ }
136
+ if (escaped === '\r' || escaped === '\n') {
137
+ syntaxError('Raw strings must remain on one line', locationAt(text, index + 1, source));
138
+ }
139
+ index++;
140
+ continue;
141
+ }
142
+ if (character === quote)
143
+ return index;
144
+ if (quote === '"' && text.startsWith('${', index)) {
145
+ const close = findInterpolationClose(text, index + 2);
146
+ if (close === undefined)
147
+ syntaxError('Unclosed string interpolation', locationAt(text, index, source));
148
+ index = close;
149
+ }
150
+ }
151
+ syntaxError('Unterminated string literal', locationAt(text, start, source));
152
+ }
153
+ function parseStringToken(raw, source) {
154
+ const quote = raw[0];
155
+ const end = raw.length - 1;
156
+ const parts = [];
157
+ let literal = '';
158
+ let hasInterpolation = false;
159
+ const flushLiteral = () => {
160
+ if (literal)
161
+ parts.push(literal);
162
+ literal = '';
163
+ };
164
+ for (let index = 1; index < end;) {
165
+ const character = raw[index];
166
+ if (character === '\\') {
167
+ const escape = raw[index + 1];
168
+ const decoded = {
169
+ '"': '"',
170
+ "'": "'",
171
+ '\\': '\\',
172
+ n: '\n',
173
+ r: '\r',
174
+ t: '\t'
175
+ };
176
+ if (escape === '$' && raw[index + 2] === '{') {
177
+ literal += '${';
178
+ index += 3;
179
+ continue;
180
+ }
181
+ if (escape === undefined || decoded[escape] === undefined) {
182
+ syntaxError(`Unknown or incomplete string escape '\\${escape ?? ''}'`, locationAt(raw, index, source));
183
+ }
184
+ literal += decoded[escape];
185
+ index += 2;
186
+ continue;
187
+ }
188
+ if (quote === '"' && raw.startsWith('${', index)) {
189
+ const close = findInterpolationClose(raw, index + 2);
190
+ if (close === undefined)
191
+ syntaxError('Unclosed string interpolation', locationAt(raw, index, source));
192
+ const expressionText = raw.slice(index + 2, close);
193
+ const leading = expressionText.length - expressionText.trimStart().length;
194
+ const trimmed = expressionText.trim();
195
+ if (!trimmed)
196
+ syntaxError('String interpolation requires an expression', locationAt(raw, index, source));
197
+ flushLiteral();
198
+ try {
199
+ parts.push(parseExpression(trimmed, locationAt(raw, index + 2 + leading, source)));
200
+ }
201
+ catch (error) {
202
+ if (error instanceof AmxError)
203
+ throw error;
204
+ syntaxError(`Invalid string interpolation expression: ${error instanceof Error ? error.message : String(error)}`, locationAt(raw, index, source));
205
+ }
206
+ hasInterpolation = true;
207
+ index = close + 1;
208
+ continue;
209
+ }
210
+ literal += character;
211
+ index++;
212
+ }
213
+ flushLiteral();
214
+ if (!hasInterpolation) {
215
+ return { type: 'stringLiteral', value: parts.join(''), source };
216
+ }
217
+ return { type: 'stringInterpolation', parts, source };
218
+ }
219
+ function findForExpressionEnd(text, start, source) {
220
+ let open = -1;
221
+ let depth = 0;
222
+ for (let index = start; index < text.length; index++) {
223
+ const character = text[index];
224
+ if (character === '"' || character === "'") {
225
+ const end = findStringLiteralEnd(text, index);
226
+ if (end === undefined)
227
+ syntaxError('Invalid or incomplete string in for expression', locationAt(text, index, source));
228
+ index = end;
229
+ continue;
230
+ }
231
+ if (character === '{') {
232
+ if (open === -1)
233
+ open = index;
234
+ depth++;
235
+ }
236
+ else if (character === '}' && open !== -1) {
237
+ depth--;
238
+ if (depth === 0)
239
+ return index;
240
+ }
241
+ }
242
+ throw new Error(`Unclosed braced expression`);
243
+ }
244
+ function findMatchExpressionEnd(text, start, source) {
245
+ const braces = [];
246
+ let parentheses = 0;
247
+ let pendingMatches = 0;
248
+ let pendingFor = false;
249
+ for (let index = start; index < text.length; index++) {
250
+ const character = text[index];
251
+ if (character === '"' || character === "'") {
252
+ const end = findStringLiteralEnd(text, index);
253
+ if (end === undefined)
254
+ syntaxError('Invalid or incomplete string in match expression', locationAt(text, index, source));
255
+ index = end;
256
+ continue;
257
+ }
258
+ if (character === '(')
259
+ parentheses++;
260
+ else if (character === ')')
261
+ parentheses--;
262
+ else if (text.startsWith('match', index)
263
+ && !/[A-Za-z0-9_]/.test(text[index - 1] ?? '')
264
+ && !/[A-Za-z0-9_]/.test(text[index + 5] ?? '')) {
265
+ pendingMatches++;
266
+ index += 4;
267
+ }
268
+ else if (text.startsWith('for', index)
269
+ && !/[A-Za-z0-9_]/.test(text[index - 1] ?? '')
270
+ && !/[A-Za-z0-9_]/.test(text[index + 3] ?? '')) {
271
+ pendingFor = true;
272
+ index += 2;
273
+ }
274
+ else if (character === '{') {
275
+ const activeMatches = braces.filter(Boolean).length;
276
+ braces.push(!pendingFor && pendingMatches > activeMatches);
277
+ pendingFor = false;
278
+ }
279
+ else if (character === '}') {
280
+ if (braces.pop())
281
+ pendingMatches--;
282
+ if (braces.length === 0 && pendingMatches === 0 && parentheses === 0)
283
+ return index;
284
+ }
285
+ }
286
+ const position = locationAt(text, start, source);
287
+ throw new Error(`Unclosed match expression at ${position.line}:${position.column}`);
288
+ }
289
+ function locationAt(text, offset, source) {
290
+ const before = text.slice(0, offset).split(/\r?\n/);
291
+ return {
292
+ line: (source?.line ?? 1) + before.length - 1,
293
+ column: (before.length === 1 ? source?.column ?? 1 : 1) + before[before.length - 1].length
294
+ };
295
+ }
296
+ function tokenOffset(token, fallback) {
297
+ return 'offset' in token ? token.offset ?? fallback : fallback;
298
+ }
299
+ function parseMatchExpression(text, source) {
300
+ let open = -1;
301
+ let depth = 0;
302
+ for (let index = 0; index < text.length; index++) {
303
+ const character = text[index];
304
+ if (character === '"' || character === "'") {
305
+ const end = findStringLiteralEnd(text, index);
306
+ if (end === undefined)
307
+ syntaxError('Invalid or incomplete string in match expression', locationAt(text, index, source));
308
+ index = end;
309
+ continue;
310
+ }
311
+ if (character === '{') {
312
+ if (depth === 0)
313
+ open = index;
314
+ depth++;
315
+ }
316
+ else if (character === '}') {
317
+ depth--;
318
+ }
319
+ }
320
+ const fail = (message, offset) => {
321
+ const position = locationAt(text, offset, source);
322
+ throw new Error(`${message} at ${position.line}:${position.column}`);
323
+ };
324
+ if (open < 0 || depth !== 0)
325
+ fail('Malformed match braces', 0);
326
+ const scrutineeText = text.slice(5, open).trim();
327
+ if (!scrutineeText)
328
+ fail('Missing match scrutinee', 5);
329
+ const scrutineeOffset = text.indexOf(scrutineeText, 5);
330
+ const expression = parseExpression(scrutineeText, locationAt(text, scrutineeOffset, source));
331
+ const body = text.slice(open + 1, -1);
332
+ if (!/^[ \t]*\r?\n/.test(body) || !/\r?\n[ \t]*$/.test(body))
333
+ fail('Match arms require newlines', open + 1);
334
+ const arms = [];
335
+ let armStart = open + 1;
336
+ depth = 0;
337
+ for (let index = armStart; index < text.length - 1; index++) {
338
+ const character = text[index];
339
+ if (character === '"' || character === "'") {
340
+ const end = findStringLiteralEnd(text, index);
341
+ if (end === undefined)
342
+ syntaxError('Invalid or incomplete string in match expression', locationAt(text, index, source));
343
+ index = end;
344
+ continue;
345
+ }
346
+ if (character === '{')
347
+ depth++;
348
+ else if (character === '}')
349
+ depth--;
350
+ else if (character === '\n' && depth === 0) {
351
+ if (text.slice(armStart, index).trim())
352
+ arms.push({ text: text.slice(armStart, index), offset: armStart });
353
+ armStart = index + 1;
354
+ }
355
+ }
356
+ if (text.slice(armStart, -1).trim())
357
+ fail('Match arm must end with a newline', armStart);
358
+ const cases = [];
359
+ let defaultExpression;
360
+ let defaultSource;
361
+ const parseBranch = (branch, offset) => {
362
+ try {
363
+ return parseExpression(branch, locationAt(text, offset, source));
364
+ }
365
+ catch (error) {
366
+ if (error instanceof AmxError)
367
+ throw error;
368
+ return fail(`Invalid match arm expression: ${error instanceof Error ? error.message : String(error)}`, offset);
369
+ }
370
+ };
371
+ for (const arm of arms) {
372
+ const leading = arm.text.length - arm.text.trimStart().length;
373
+ const armOffset = arm.offset + leading;
374
+ const armText = arm.text.trim();
375
+ const armSource = locationAt(text, armOffset, source);
376
+ const arrow = armText.indexOf('=>');
377
+ if (arrow < 0)
378
+ fail('Expected => in match arm', armOffset);
379
+ const pattern = armText.slice(0, arrow).trim();
380
+ const branch = armText.slice(arrow + 2).trim();
381
+ if (!branch)
382
+ fail('Missing match arm expression', armOffset + arrow + 2);
383
+ const branchOffset = armOffset + armText.indexOf(branch, arrow + 2);
384
+ if (pattern === 'default') {
385
+ if (defaultExpression)
386
+ fail('Duplicate default match arm', armOffset);
387
+ defaultSource = armSource;
388
+ defaultExpression = parseBranch(branch, branchOffset);
389
+ }
390
+ else {
391
+ const literal = pattern.match(/^case\s+(-?(?:\d+(?:\.\d*)?)|"(?:\\.|[^"\\\r\n])*"|'(?:\\.|[^'\\\r\n])*'|true|false)$/);
392
+ if (!literal)
393
+ return fail('Match case requires a number, string, or boolean literal', armOffset);
394
+ const valueOffset = armOffset + armText.indexOf(literal[1]);
395
+ const valueSource = locationAt(text, valueOffset, source);
396
+ let value;
397
+ if (/^-?\d/.test(literal[1])) {
398
+ value = { type: 'numberLiteral', value: Number(literal[1]), source: valueSource };
399
+ }
400
+ else if (literal[1] === 'true' || literal[1] === 'false') {
401
+ value = { type: 'booleanLiteral', value: literal[1] === 'true', source: valueSource };
402
+ }
403
+ else {
404
+ const parsedString = parseStringToken(literal[1], valueSource);
405
+ if (parsedString.type !== 'stringLiteral') {
406
+ syntaxError('Match case requires a literal string without interpolation', valueSource);
407
+ }
408
+ value = parsedString;
409
+ }
410
+ cases.push({ value, expression: parseBranch(branch, branchOffset), source: armSource });
411
+ }
412
+ }
413
+ if (!defaultExpression)
414
+ return fail('Match requires exactly one default arm', 0);
415
+ return { type: 'matchExpression', expression, cases, defaultExpression, defaultSource, source };
416
+ }
417
+ export function parseExpression(text, source) {
418
+ const tokens = tokenize(text, source);
419
+ let pos = 0;
420
+ function current() {
421
+ return tokens[pos];
422
+ }
423
+ function advance() {
424
+ pos++;
425
+ }
426
+ function consumeRParen() {
427
+ const t = current();
428
+ if (t.type !== 'rparen') {
429
+ throw new Error(`Expected ')' but got ${t.type}`);
430
+ }
431
+ advance();
432
+ }
433
+ // Full precedence (highest to lowest) per Sprint 004 / language-spec-v0.1.md:
434
+ // parentheses, function calls (handled in primary)
435
+ // unary: - not
436
+ // power: ^ (right-assoc)
437
+ // * / %
438
+ // + -
439
+ // comparison: == != > >= < <=
440
+ // logical and
441
+ // logical or
442
+ // conditional if/then/else (lowest)
443
+ const PREC = {
444
+ // comparisons
445
+ '==': 2,
446
+ '!=': 2,
447
+ '>': 2,
448
+ '>=': 2,
449
+ '<': 2,
450
+ '<=': 2,
451
+ // Measurement conversion binds below arithmetic and above comparisons.
452
+ 'in': 2.5,
453
+ // arithmetic
454
+ '^': 5,
455
+ '*': 4,
456
+ '/': 4,
457
+ '%': 4,
458
+ '+': 3,
459
+ '-': 3,
460
+ // logicals (lower than comparisons)
461
+ 'and': 1,
462
+ 'or': 0
463
+ };
464
+ function isRightAssociative(op) {
465
+ return op === '^';
466
+ }
467
+ function parsePrimary() {
468
+ const t = current();
469
+ const attach = (value) => {
470
+ const unit = current();
471
+ if (unit.type !== 'identifier' || unit.name === 'in' || unit.name === 'to')
472
+ return value;
473
+ advance();
474
+ return {
475
+ type: 'measurementAttachment',
476
+ value,
477
+ unit: unit.name,
478
+ unitSource: locationAt(text, unit.offset, source),
479
+ source: value.source
480
+ };
481
+ };
482
+ if (t.type === 'matchExpression') {
483
+ advance();
484
+ return parseMatchExpression(t.value, locationAt(text, t.offset, source));
485
+ }
486
+ if (t.type === 'forExpression') {
487
+ advance();
488
+ return parseForExpression(t.value, source);
489
+ }
490
+ if (t.type === 'number') {
491
+ advance();
492
+ return attach({ type: 'numberLiteral', value: t.value, source: locationAt(text, t.offset, source) });
493
+ }
494
+ if (t.type === 'string') {
495
+ advance();
496
+ return parseStringToken(t.text, locationAt(text, t.offset, source));
497
+ }
498
+ if (t.type === 'boolean') {
499
+ advance();
500
+ return { type: 'booleanLiteral', value: t.value, source: locationAt(text, t.offset, source) };
501
+ }
502
+ if (t.type === 'null') {
503
+ advance();
504
+ return { type: 'nullLiteral', source: locationAt(text, t.offset, source) };
505
+ }
506
+ if (t.type === 'identifier') {
507
+ const name = t.name;
508
+ advance();
509
+ if (current().type === 'lbrace') {
510
+ advance();
511
+ const fields = [];
512
+ while (current().type !== 'rbrace') {
513
+ const field = current();
514
+ if (field.type !== 'identifier') {
515
+ syntaxError('Expected record constructor field name', locationAt(text, tokenOffset(field, text.length), source));
516
+ }
517
+ advance();
518
+ if (current().type === 'colon') {
519
+ syntaxError('Record constructor fields use =, not :', locationAt(text, tokenOffset(current(), text.length), source));
520
+ }
521
+ if (current().type !== 'equals') {
522
+ syntaxError('Expected = after record constructor field', locationAt(text, tokenOffset(current(), text.length), source));
523
+ }
524
+ advance();
525
+ fields.push({ name: field.name, expression: parseExpr(0), source: locationAt(text, field.offset, source) });
526
+ if (current().type !== 'comma') {
527
+ if (current().type !== 'rbrace') {
528
+ syntaxError('Expected , or } after record constructor field', locationAt(text, tokenOffset(current(), text.length), source));
529
+ }
530
+ break;
531
+ }
532
+ advance();
533
+ if (current().type === 'rbrace')
534
+ break;
535
+ }
536
+ if (current().type !== 'rbrace')
537
+ throw new Error('Expected } after constructor fields');
538
+ advance();
539
+ return { type: 'recordConstructor', name, fields, source: locationAt(text, t.offset, source) };
540
+ }
541
+ // Function call: identifier followed by '('
542
+ if (current().type === 'lparen') {
543
+ advance(); // consume '('
544
+ const args = [];
545
+ if (current().type !== 'rparen') {
546
+ while (true) {
547
+ args.push(parseExpr(0));
548
+ if (current().type === 'comma') {
549
+ advance();
550
+ continue;
551
+ }
552
+ break;
553
+ }
554
+ }
555
+ if (current().type !== 'rparen') {
556
+ throw new Error(`Expected ')' after function call arguments`);
557
+ }
558
+ advance(); // consume ')'
559
+ return {
560
+ type: 'functionCall',
561
+ callee: name,
562
+ arguments: args,
563
+ source: locationAt(text, t.offset, source)
564
+ };
565
+ }
566
+ return attach({ type: 'identifier', name, source: locationAt(text, t.offset, source) });
567
+ }
568
+ if (t.type === 'lparen') {
569
+ advance();
570
+ const expr = parseExpr(0);
571
+ consumeRParen();
572
+ return attach(expr);
573
+ }
574
+ if (t.type === 'lbracket') {
575
+ advance();
576
+ if (current().type === 'rbracket') {
577
+ advance();
578
+ return { type: 'listLiteral', elements: [], source };
579
+ }
580
+ const first = parseExpr(0);
581
+ const rangeSeparator = current();
582
+ if (rangeSeparator.type === 'identifier' && rangeSeparator.name === 'to') {
583
+ advance();
584
+ const end = parseExpr(0);
585
+ if (current().type !== 'rbracket') {
586
+ throw new Error(`Expected ']' after range expression`);
587
+ }
588
+ advance();
589
+ return { type: 'rangeExpression', start: first, end, source };
590
+ }
591
+ const elements = [first];
592
+ while (current().type === 'comma') {
593
+ advance();
594
+ elements.push(parseExpr(0));
595
+ }
596
+ if (current().type !== 'rbracket') {
597
+ throw new Error(`Expected ',' or ']' after list expression`);
598
+ }
599
+ advance();
600
+ return { type: 'listLiteral', elements, source };
601
+ }
602
+ if (t.type === 'operator' && t.op === '-') {
603
+ // Unary minus (higher precedence than ^)
604
+ advance();
605
+ const argument = parsePrimary();
606
+ return {
607
+ type: 'unaryExpression',
608
+ operator: '-',
609
+ argument,
610
+ source
611
+ };
612
+ }
613
+ if (t.type === 'keyword' && t.word === 'not') {
614
+ // Unary not
615
+ advance();
616
+ const argument = parsePrimary();
617
+ return {
618
+ type: 'unaryExpression',
619
+ operator: 'not',
620
+ argument,
621
+ source
622
+ };
623
+ }
624
+ throw new Error(`Unexpected token in expression: ${t.type} ${t.op || t.name || t.word || ''}`);
625
+ }
626
+ function parseExpr(minPrec) {
627
+ // Handle leading conditional (lowest precedence) before calling parsePrimary.
628
+ // Conditionals only start at the top level of an expression (minPrec === 0).
629
+ const t0 = current();
630
+ if (minPrec === 0 && t0.type === 'keyword' && t0.word === 'if') {
631
+ advance(); // consume 'if'
632
+ const test = parseExpr(0);
633
+ if (current().type !== 'keyword' || current().word !== 'then') {
634
+ throw new Error(`Expected 'then' after if condition`);
635
+ }
636
+ advance(); // then
637
+ const consequent = parseExpr(0);
638
+ if (current().type !== 'keyword' || current().word !== 'else') {
639
+ throw new Error(`Expected 'else' after then branch`);
640
+ }
641
+ advance(); // else
642
+ const alternate = parseExpr(0);
643
+ return {
644
+ type: 'conditionalExpression',
645
+ test,
646
+ consequent,
647
+ alternate,
648
+ source
649
+ };
650
+ }
651
+ let left = parsePrimary();
652
+ while (true) {
653
+ const t = current();
654
+ if (t.type === 'identifier' && t.name === 'in') {
655
+ const prec = PREC.in;
656
+ if (prec < minPrec)
657
+ break;
658
+ advance();
659
+ const unit = current();
660
+ if (unit.type !== 'identifier' || unit.name === 'to' || unit.name === 'in') {
661
+ syntaxError("Conversion requires a visible unit name after 'in'", locationAt(text, tokenOffset(unit, text.length), source));
662
+ }
663
+ advance();
664
+ left = {
665
+ type: 'measurementConversion',
666
+ value: left,
667
+ unit: unit.name,
668
+ unitSource: locationAt(text, unit.offset, source),
669
+ source: locationAt(text, t.offset ?? 0, source)
670
+ };
671
+ continue;
672
+ }
673
+ if (t.type === 'dot') {
674
+ advance();
675
+ const field = current();
676
+ if (field.type !== 'identifier')
677
+ throw new Error('Expected field name after .');
678
+ advance();
679
+ left = { type: 'fieldAccess', receiver: left, field: field.name, source: locationAt(text, t.offset ?? 0, source) };
680
+ continue;
681
+ }
682
+ if (t.type === 'lbracket') {
683
+ advance();
684
+ if (current().type === 'rbracket') {
685
+ syntaxError('List index cannot be empty', locationAt(text, t.offset ?? 0, source));
686
+ }
687
+ const index = parseExpr(0);
688
+ if (current().type !== 'rbracket') {
689
+ syntaxError("Expected ']' after list index", locationAt(text, tokenOffset(current(), text.length), source));
690
+ }
691
+ advance();
692
+ left = { type: 'listAccess', receiver: left, index, source: locationAt(text, t.offset ?? 0, source) };
693
+ continue;
694
+ }
695
+ // Conditional appearing after a left-hand side (e.g. via lower-precedence context).
696
+ // Guarded so it only triggers at the true top level.
697
+ if (t.type === 'keyword' && t.word === 'if') {
698
+ if (0 < minPrec)
699
+ break;
700
+ advance(); // consume 'if'
701
+ const test = parseExpr(0);
702
+ if (current().type !== 'keyword' || current().word !== 'then') {
703
+ throw new Error(`Expected 'then' after if condition`);
704
+ }
705
+ advance(); // then
706
+ const consequent = parseExpr(0);
707
+ if (current().type !== 'keyword' || current().word !== 'else') {
708
+ throw new Error(`Expected 'else' after then branch`);
709
+ }
710
+ advance(); // else
711
+ const alternate = parseExpr(0);
712
+ return {
713
+ type: 'conditionalExpression',
714
+ test,
715
+ consequent,
716
+ alternate,
717
+ source
718
+ };
719
+ }
720
+ // Binary operators (arithmetic, comparison, logical keywords)
721
+ if (t.type === 'operator') {
722
+ const op = t.op;
723
+ const prec = PREC[op];
724
+ if (prec === undefined || prec < minPrec)
725
+ break;
726
+ advance(); // consume operator
727
+ const nextMinPrec = isRightAssociative(op) ? prec
728
+ : ['==', '!=', '>', '>=', '<', '<='].includes(op) ? 2.5
729
+ : prec + 1;
730
+ const right = parseExpr(nextMinPrec);
731
+ left = {
732
+ type: 'binaryExpression',
733
+ operator: op,
734
+ left,
735
+ right,
736
+ operatorSource: locationAt(text, t.offset, source),
737
+ source
738
+ };
739
+ continue;
740
+ }
741
+ if (t.type === 'keyword' && (t.word === 'and' || t.word === 'or')) {
742
+ const op = t.word;
743
+ const prec = PREC[op];
744
+ if (prec === undefined || prec < minPrec)
745
+ break;
746
+ advance(); // consume keyword operator
747
+ const nextMinPrec = prec + 1;
748
+ const right = parseExpr(nextMinPrec);
749
+ left = {
750
+ type: 'binaryExpression',
751
+ operator: op,
752
+ left,
753
+ right,
754
+ operatorSource: locationAt(text, tokenOffset(t, 0), source),
755
+ source
756
+ };
757
+ continue;
758
+ }
759
+ break;
760
+ }
761
+ return left;
762
+ }
763
+ const result = parseExpr(0);
764
+ if (current().type !== 'eof') {
765
+ throw new Error(`Unexpected input after expression at token ${current().type}`);
766
+ }
767
+ return result;
768
+ }