@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,667 @@
1
+ import { parseExpression } from './parseExpression';
2
+ import { parseForStatement } from './parseFor';
3
+ import { AmxError, staticError, syntaxError } from '../diagnostics/errors';
4
+ import { findStringLiteralEnd, withoutStringLiterals } from './stringScanner';
5
+ /** Parse executable AMX statements while preserving original-document locations. */
6
+ export function parseStatements(body, start = { line: 1, column: 1 }, context = {}) {
7
+ if (!body || body.trim().length === 0) {
8
+ return [];
9
+ }
10
+ const lines = body.split(/\r?\n/);
11
+ const statements = [];
12
+ for (let i = 0; i < lines.length; i++) {
13
+ let rawLine = lines[i];
14
+ const lineNumber = start.line + i;
15
+ if (rawLine.trim().length === 0) {
16
+ continue;
17
+ }
18
+ const reExportMatch = rawLine.match(/^(\s*)export\s*\{\s*([^}]*)\s*\}\s*$/);
19
+ if (reExportMatch) {
20
+ const names = [];
21
+ let cursor = rawLine.indexOf('{') + 1;
22
+ for (const rawName of reExportMatch[2].split(',')) {
23
+ const name = rawName.trim();
24
+ if (!/^[A-Za-z][A-Za-z0-9_]*$/.test(name))
25
+ syntaxError(`Invalid re-exported name '${name}'`, { line: lineNumber, column: Math.max(1, cursor + 1) });
26
+ const nameStart = rawLine.indexOf(name, cursor);
27
+ names.push({ name, source: { line: lineNumber, column: nameStart + 1 } });
28
+ cursor = nameStart + name.length;
29
+ }
30
+ if (!names.length)
31
+ syntaxError('Re-export requires at least one name', { line: lineNumber, column: reExportMatch[1].length + 1 });
32
+ statements.push({ type: 'exportNamesDeclaration', names, source: { line: lineNumber, column: reExportMatch[1].length + 1 } });
33
+ continue;
34
+ }
35
+ let exported = false;
36
+ const exportMatch = rawLine.match(/^(\s*)export(\s+)(type|fn|let|table|chart|dimension|unit)\b/);
37
+ if (exportMatch) {
38
+ if (context.allowFor === false && exportMatch[3] !== 'table' && exportMatch[3] !== 'chart'
39
+ && exportMatch[3] !== 'dimension' && exportMatch[3] !== 'unit')
40
+ throw new Error(`Export declarations cannot occur in loops at ${lineNumber}:${exportMatch[1].length + 1}`);
41
+ exported = true;
42
+ const blankLength = exportMatch[0].length - exportMatch[3].length;
43
+ rawLine = ' '.repeat(blankLength) + rawLine.slice(blankLength);
44
+ lines[i] = rawLine;
45
+ }
46
+ const indentation = rawLine.length - rawLine.trimStart().length;
47
+ const source = {
48
+ line: lineNumber,
49
+ column: i === 0 ? start.column + indentation : indentation + 1
50
+ };
51
+ if (/^\s*import\b/.test(rawLine)) {
52
+ if (context.allowFor === false)
53
+ throw new Error(`Import declarations cannot occur in loops at ${source.line}:${source.column}`);
54
+ statements.push(parseImportDeclaration(rawLine, source));
55
+ continue;
56
+ }
57
+ const dimensionMatch = rawLine.match(/^\s*dimension\s+([A-Za-z][A-Za-z0-9_]*)(?:\s*=\s*(.+))?\s*$/);
58
+ if (/^\s*dimension\b/.test(rawLine)) {
59
+ if (!dimensionMatch)
60
+ syntaxError('Invalid dimension declaration', source);
61
+ const expressionText = dimensionMatch[2];
62
+ statements.push({
63
+ type: 'dimensionDeclaration',
64
+ name: dimensionMatch[1],
65
+ nameSource: { line: source.line, column: rawLine.indexOf(dimensionMatch[1]) + 1 },
66
+ ...(expressionText ? { expression: parseDeclarationExpression(rawLine, expressionText, source) } : {}),
67
+ ...(exported ? { exported: true } : {}),
68
+ source
69
+ });
70
+ continue;
71
+ }
72
+ const unitMatch = rawLine.match(/^\s*unit\s+([A-Za-z][A-Za-z0-9_]*)(?:\s*:\s*([A-Za-z][A-Za-z0-9_]*)|\s*=\s*(.+))\s*$/);
73
+ if (/^\s*unit\b/.test(rawLine)) {
74
+ if (!unitMatch)
75
+ syntaxError('Invalid unit declaration', source);
76
+ const dimensionName = unitMatch[2];
77
+ const expressionText = unitMatch[3];
78
+ const dimensionSource = dimensionName
79
+ ? { line: source.line, column: rawLine.lastIndexOf(dimensionName) + 1 }
80
+ : undefined;
81
+ statements.push({
82
+ type: 'unitDeclaration',
83
+ name: unitMatch[1],
84
+ nameSource: { line: source.line, column: rawLine.indexOf(unitMatch[1]) + 1 },
85
+ ...(dimensionName ? { dimension: dimensionName, dimensionSource } : {}),
86
+ ...(expressionText ? { expression: parseDeclarationExpression(rawLine, expressionText, source) } : {}),
87
+ ...(exported ? { exported: true } : {}),
88
+ source
89
+ });
90
+ continue;
91
+ }
92
+ if (/^\s*input\b/.test(rawLine)) {
93
+ if (context.allowFor === false)
94
+ throw new Error(`Input declarations cannot occur in loops at ${source.line}:${source.column}`);
95
+ const match = rawLine.match(/^\s*input\s+([A-Za-z][A-Za-z0-9_]*)\s*:\s*([A-Za-z][A-Za-z0-9_]*(?:(?:\[\])|\?)*)\s*$/);
96
+ if (!match)
97
+ throw new Error(`Invalid input declaration at ${source.line}:${source.column}`);
98
+ const input = {
99
+ type: 'inputDeclaration',
100
+ name: match[1],
101
+ annotation: parseTypeReference(match[2], { line: source.line, column: rawLine.indexOf(match[2]) + 1 }),
102
+ source
103
+ };
104
+ statements.push(input);
105
+ continue;
106
+ }
107
+ function parseDeclarationExpression(rawLine, expressionText, source) {
108
+ const offset = rawLine.indexOf(expressionText);
109
+ try {
110
+ return parseExpression(expressionText, { line: source.line, column: offset + 1 });
111
+ }
112
+ catch (error) {
113
+ if (error instanceof AmxError && error.code === 'AMX3006')
114
+ throw error;
115
+ syntaxError(`Invalid dimension/unit expression: ${error instanceof Error ? error.message : String(error)}`, {
116
+ line: source.line,
117
+ column: offset + 1
118
+ });
119
+ }
120
+ }
121
+ if (/^\s*(table|chart)\b/.test(rawLine)) {
122
+ const parsed = parseVisualization(lines, i, source, exported);
123
+ statements.push(parsed.statement);
124
+ i = parsed.endIndex;
125
+ continue;
126
+ }
127
+ if (/^\s*show\b/.test(rawLine)) {
128
+ const match = rawLine.match(/^\s*show\s+([A-Za-z][A-Za-z0-9_]*)\s*$/);
129
+ if (!match)
130
+ throw new Error(`Invalid show statement at ${source.line}:${source.column}`);
131
+ statements.push({
132
+ type: 'showStatement',
133
+ name: match[1],
134
+ nameSource: { line: source.line, column: rawLine.lastIndexOf(match[1]) + 1 },
135
+ source
136
+ });
137
+ continue;
138
+ }
139
+ if (/^\s*fn\b/.test(rawLine)) {
140
+ if (context.allowFor === false)
141
+ throw new Error(`Function declarations cannot occur in loops at ${source.line}:${source.column}`);
142
+ const endIndex = findFunctionEnd(lines, i, source);
143
+ const fnText = lines.slice(i, endIndex + 1).join('\n');
144
+ statements.push(parseFunctionDeclaration(fnText, source, exported));
145
+ i = endIndex;
146
+ continue;
147
+ }
148
+ if (/^\s*type\b/.test(rawLine)) {
149
+ if (context.allowFor === false)
150
+ throw new Error(`Type declarations cannot occur in loops at ${source.line}:${source.column}`);
151
+ const header = rawLine.match(/^\s*type\s+([A-Za-z][A-Za-z0-9_]*)\s*\{\s*$/);
152
+ if (!header)
153
+ throw new Error(`Invalid type declaration at ${source.line}:${source.column}`);
154
+ const fields = [];
155
+ let closed = false;
156
+ while (++i < lines.length) {
157
+ const fieldLine = lines[i];
158
+ if (/^\s*}\s*$/.test(fieldLine)) {
159
+ closed = true;
160
+ break;
161
+ }
162
+ if (!fieldLine.trim())
163
+ continue;
164
+ const match = fieldLine.match(/^\s*([A-Za-z][A-Za-z0-9_]*)(\?)?\s*:\s*([A-Za-z][A-Za-z0-9_]*(?:(?:\[\])|\?)*)\s*(?:=\s*(.+))?\s*$/);
165
+ const fieldSource = { line: start.line + i, column: fieldLine.length - fieldLine.trimStart().length + 1 };
166
+ if (!match)
167
+ throw new Error(`Invalid record field at ${fieldSource.line}:${fieldSource.column}`);
168
+ fields.push({ name: match[1], optional: !!match[2], annotation: parseTypeReference(match[3], fieldSource),
169
+ ...(match[4] ? { defaultExpression: parseExpression(match[4], { line: fieldSource.line, column: fieldLine.indexOf(match[4]) + 1 }) } : {}), source: fieldSource });
170
+ }
171
+ if (!closed)
172
+ throw new Error(`Unclosed type declaration at ${source.line}:${source.column}`);
173
+ statements.push({ type: 'typeDeclaration', name: header[1], fields, ...(exported ? { exported } : {}), source });
174
+ continue;
175
+ }
176
+ if (context.allowFor === false && containsForExpression(rawLine)) {
177
+ throw new Error(`Nested loops are unsupported at ${source.line}:${source.column}`);
178
+ }
179
+ if (/^\s*for\b/.test(rawLine)) {
180
+ if (context.allowFor === false) {
181
+ throw new Error(`Nested loops are unsupported at ${source.line}:${source.column}`);
182
+ }
183
+ const endIndex = findLoopEnd(lines, i, { line: lineNumber, column: source.column });
184
+ statements.push(parseForStatement(lines.slice(i, endIndex + 1).join('\n'), source));
185
+ i = endIndex;
186
+ continue;
187
+ }
188
+ if (/^\s*(break|continue)\b/.test(rawLine)) {
189
+ throw new Error(`Unsupported loop control statement at ${source.line}:${source.column}`);
190
+ }
191
+ const returnMatch = rawLine.match(/^\s*return\s+(.+)\s*$/);
192
+ if (returnMatch) {
193
+ if (context.allowReturn !== true) {
194
+ throw new Error(`Return is only valid inside an expression-form for loop at ${source.line}:${source.column}`);
195
+ }
196
+ const expressionText = collectExpressionLoop(lines, i, returnMatch[1], start);
197
+ statements.push({
198
+ type: 'returnStatement',
199
+ expression: parseExpression(expressionText.text, containsMatchExpression(expressionText.text)
200
+ ? { line: source.line, column: rawLine.indexOf(returnMatch[1]) + 1 } : source),
201
+ source
202
+ });
203
+ i += expressionText.lineCount - 1;
204
+ continue;
205
+ }
206
+ const addMatch = rawLine.match(/^\s*add\s+(.+)$/);
207
+ if (addMatch) {
208
+ const collected = collectDelimitedExpression(lines, i, addMatch[1]);
209
+ const remainder = collected.text;
210
+ const remainderSource = locationAtOffset(remainder, 0, {
211
+ line: source.line,
212
+ column: rawLine.length - addMatch[1].length + 1
213
+ });
214
+ const split = findTopLevelKeyword(remainder, 'to');
215
+ if (!split)
216
+ syntaxError('Invalid add statement', source);
217
+ const valueText = remainder.slice(0, split.start).trim();
218
+ const targetTail = remainder.slice(split.end);
219
+ const targetAndIndex = targetTail.trim();
220
+ const at = findTopLevelKeyword(targetAndIndex, 'at');
221
+ const name = (at ? targetAndIndex.slice(0, at.start) : targetAndIndex).trim();
222
+ const indexText = at ? targetAndIndex.slice(at.end).trim() : undefined;
223
+ if (!/^[A-Za-z][A-Za-z0-9_]*$/.test(name) || !valueText || (at && !indexText)) {
224
+ syntaxError('Invalid add statement', source);
225
+ }
226
+ const valueOffset = remainder.indexOf(valueText);
227
+ const targetOffset = split.end + targetTail.indexOf(targetAndIndex);
228
+ const indexOffset = at ? targetOffset + at.end + targetAndIndex.slice(at.end).length - targetAndIndex.slice(at.end).trimStart().length : undefined;
229
+ statements.push({
230
+ type: 'addStatement',
231
+ name,
232
+ targetSource: locationAtOffset(remainder, targetOffset, remainderSource),
233
+ value: parseExpression(valueText, locationAtOffset(remainder, valueOffset, remainderSource)),
234
+ ...(indexText ? { index: parseExpression(indexText, locationAtOffset(remainder, indexOffset, remainderSource)) } : {}),
235
+ source
236
+ });
237
+ i += collected.lineCount - 1;
238
+ continue;
239
+ }
240
+ const removeMatch = rawLine.match(/^\s*remove\s+(.+)$/);
241
+ if (removeMatch) {
242
+ const collected = collectDelimitedExpression(lines, i, removeMatch[1]);
243
+ const remainder = collected.text;
244
+ const remainderSource = locationAtOffset(remainder, 0, {
245
+ line: source.line,
246
+ column: rawLine.length - removeMatch[1].length + 1
247
+ });
248
+ const split = findTopLevelKeyword(remainder, 'from');
249
+ if (!split)
250
+ syntaxError('Invalid remove statement', source);
251
+ const countText = remainder.slice(0, split.start).trim();
252
+ const targetTail = remainder.slice(split.end);
253
+ const targetAndIndex = targetTail.trim();
254
+ const at = findTopLevelKeyword(targetAndIndex, 'at');
255
+ const name = (at ? targetAndIndex.slice(0, at.start) : targetAndIndex).trim();
256
+ const indexText = at ? targetAndIndex.slice(at.end).trim() : undefined;
257
+ if (!/^[A-Za-z][A-Za-z0-9_]*$/.test(name) || !countText || (at && !indexText)) {
258
+ syntaxError('Invalid remove statement', source);
259
+ }
260
+ const countOffset = remainder.indexOf(countText);
261
+ const targetOffset = split.end + targetTail.indexOf(targetAndIndex);
262
+ const indexOffset = at ? targetOffset + at.end + targetAndIndex.slice(at.end).length - targetAndIndex.slice(at.end).trimStart().length : undefined;
263
+ statements.push({
264
+ type: 'removeStatement',
265
+ name,
266
+ targetSource: locationAtOffset(remainder, targetOffset, remainderSource),
267
+ count: parseExpression(countText, locationAtOffset(remainder, countOffset, remainderSource)),
268
+ ...(indexText ? { index: parseExpression(indexText, locationAtOffset(remainder, indexOffset, remainderSource)) } : {}),
269
+ source
270
+ });
271
+ i += collected.lineCount - 1;
272
+ continue;
273
+ }
274
+ const letMatch = rawLine.match(/^\s*let\s+([A-Za-z][A-Za-z0-9_]*)(?:\s*:\s*([A-Za-z][A-Za-z0-9_]*(?:(?:\[\])|\?)*))?\s*=\s*(.*)$/);
275
+ if (letMatch) {
276
+ const name = letMatch[1];
277
+ const expressionText = collectExpressionLoop(lines, i, letMatch[3], start);
278
+ let expression;
279
+ try {
280
+ expression = parseExpression(expressionText.text, containsForExpression(expressionText.text) && !containsMatchExpression(expressionText.text)
281
+ ? source : { line: source.line, column: rawLine.lastIndexOf(letMatch[3]) + 1 });
282
+ }
283
+ catch (error) {
284
+ if (error instanceof AmxError)
285
+ throw error;
286
+ const message = error instanceof Error ? error.message : String(error);
287
+ throw new Error(`Invalid declaration at ${source.line}:${source.column}: ${message}`);
288
+ }
289
+ const decl = {
290
+ type: 'variableDeclaration',
291
+ name,
292
+ expression,
293
+ ...(letMatch[2] ? { annotation: parseTypeReference(letMatch[2], { line: source.line, column: rawLine.indexOf(letMatch[2]) + 1 }) } : {}),
294
+ ...(exported ? { exported } : {}),
295
+ source
296
+ };
297
+ statements.push(decl);
298
+ i += expressionText.lineCount - 1;
299
+ continue;
300
+ }
301
+ const compoundMatch = rawLine.match(/^\s*([A-Za-z][A-Za-z0-9_]*)\s*\+=\s*(.*)$/);
302
+ const assignmentMatch = rawLine.match(/^\s*([A-Za-z][A-Za-z0-9_]*)\s*=(?!=)\s*(.*)$/);
303
+ const assignment = compoundMatch ?? assignmentMatch;
304
+ if (assignment) {
305
+ const expressionText = collectExpressionLoop(lines, i, assignment[2], start);
306
+ try {
307
+ statements.push({
308
+ type: compoundMatch ? 'compoundAssignmentStatement' : 'assignmentStatement',
309
+ name: assignment[1],
310
+ ...(compoundMatch ? { operator: '+=' } : {}),
311
+ expression: parseExpression(expressionText.text, { line: source.line, column: rawLine.lastIndexOf(assignment[2]) + 1 }),
312
+ source
313
+ });
314
+ }
315
+ catch (error) {
316
+ if (error instanceof AmxError)
317
+ throw error;
318
+ const message = error instanceof Error ? error.message : String(error);
319
+ throw new Error(`Invalid assignment at ${source.line}:${source.column}: ${message}`);
320
+ }
321
+ i += expressionText.lineCount - 1;
322
+ continue;
323
+ }
324
+ throw new Error(`Unsupported statement at ${source.line}:${source.column}`);
325
+ }
326
+ return statements;
327
+ }
328
+ function locationAtOffset(text, offset, source) {
329
+ const before = text.slice(0, offset).split(/\r?\n/);
330
+ return {
331
+ line: source.line + before.length - 1,
332
+ column: (before.length === 1 ? source.column : 1) + before[before.length - 1].length
333
+ };
334
+ }
335
+ function findTopLevelKeyword(text, keyword) {
336
+ let depth = 0;
337
+ for (let index = 0; index < text.length; index++) {
338
+ const character = text[index];
339
+ if (character === '"' || character === "'") {
340
+ const end = findStringLiteralEnd(text, index);
341
+ if (end !== undefined)
342
+ index = end;
343
+ continue;
344
+ }
345
+ if ('([{'.includes(character)) {
346
+ depth++;
347
+ continue;
348
+ }
349
+ if (')]}'.includes(character)) {
350
+ depth--;
351
+ continue;
352
+ }
353
+ if (depth === 0 && text.startsWith(keyword, index)
354
+ && /\s/.test(text[index - 1] ?? '')
355
+ && /\s/.test(text[index + keyword.length] ?? '')) {
356
+ return { start: index, end: index + keyword.length };
357
+ }
358
+ }
359
+ return undefined;
360
+ }
361
+ function parseVisualization(lines, startIndex, source, exported) {
362
+ const header = lines[startIndex].match(/^\s*(table|chart)\s+([A-Za-z][A-Za-z0-9_]*)\s*=\s*(table|bar|column|line|scatter)\s*\(\s*([A-Za-z][A-Za-z0-9_]*)\s*\)\s*\{\s*$/);
363
+ const fail = (message, at) => {
364
+ throw new Error(`${message} at ${at.line}:${at.column}`);
365
+ };
366
+ if (!header || (header[1] === 'table') !== (header[3] === 'table')) {
367
+ return fail('Invalid visualization declaration', source);
368
+ }
369
+ const name = header[2];
370
+ const binding = header[4];
371
+ const bindingSource = { line: source.line, column: lines[startIndex].lastIndexOf(binding) + 1 };
372
+ const options = [];
373
+ let endIndex = startIndex + 1;
374
+ let closed = false;
375
+ for (; endIndex < lines.length; endIndex++) {
376
+ const line = lines[endIndex];
377
+ if (/^\s*}\s*$/.test(line)) {
378
+ closed = true;
379
+ break;
380
+ }
381
+ if (!line.trim())
382
+ continue;
383
+ const optionSource = {
384
+ line: source.line + endIndex - startIndex,
385
+ column: line.length - line.trimStart().length + 1
386
+ };
387
+ const quoted = `("[^"\\r\\n]*"|'[^'\\r\\n]*')`;
388
+ let match;
389
+ if ((match = line.match(new RegExp(`^\\s*title\\s*:\\s*${quoted}\\s*$`)))) {
390
+ options.push({ type: 'viewTitleOption', value: match[1].slice(1, -1), source: optionSource });
391
+ continue;
392
+ }
393
+ if (header[1] === 'chart' && (match = line.match(new RegExp(`^\\s*description\\s*:\\s*${quoted}\\s*$`)))) {
394
+ options.push({ type: 'viewDescriptionOption', value: match[1].slice(1, -1), source: optionSource });
395
+ continue;
396
+ }
397
+ if (header[1] === 'table' && (match = line.match(new RegExp(`^\\s*column\\s+([A-Za-z][A-Za-z0-9_]*)\\s+as\\s+${quoted}\\s*$`)))) {
398
+ const field = match[1];
399
+ options.push({
400
+ type: 'tableColumnOption', field, label: match[2].slice(1, -1),
401
+ fieldSource: { line: optionSource.line, column: line.indexOf(field) + 1 }, source: optionSource
402
+ });
403
+ continue;
404
+ }
405
+ if (header[1] === 'chart') {
406
+ match = line.match(/^\s*(category|x|y|group|labels)\s*:\s*([A-Za-z][A-Za-z0-9_]*)\s*$/);
407
+ if (match) {
408
+ const field = match[2];
409
+ options.push({
410
+ type: 'chartFieldOption', role: match[1], field,
411
+ fieldSource: { line: optionSource.line, column: line.lastIndexOf(field) + 1 }, source: optionSource
412
+ });
413
+ continue;
414
+ }
415
+ match = line.match(new RegExp(`^\\s*series\\s+(?:([A-Za-z][A-Za-z0-9_]*)\\s+as\\s+)?${quoted}\\s*$`));
416
+ if (match) {
417
+ const field = match[1];
418
+ options.push({
419
+ type: 'chartSeriesOption', ...(field ? { field, fieldSource: { line: optionSource.line, column: line.indexOf(field) + 1 } } : {}),
420
+ label: match[2].slice(1, -1), source: optionSource
421
+ });
422
+ continue;
423
+ }
424
+ }
425
+ return fail(`Invalid ${header[1]} option`, optionSource);
426
+ }
427
+ if (!closed)
428
+ return fail('Unclosed visualization declaration', source);
429
+ if (header[1] === 'table') {
430
+ return { statement: { type: 'tableDeclaration', name, binding, bindingSource, options, ...(exported ? { exported } : {}), source }, endIndex };
431
+ }
432
+ return {
433
+ statement: {
434
+ type: 'chartDeclaration', name, kind: header[3], binding,
435
+ bindingSource, options, ...(exported ? { exported } : {}), source
436
+ },
437
+ endIndex
438
+ };
439
+ }
440
+ export function parseTypeReference(text, source) {
441
+ const name = text.match(/^[A-Za-z][A-Za-z0-9_]*/)?.[0];
442
+ if (!name)
443
+ throw new Error(`Invalid type reference '${text}'`);
444
+ let result = { type: 'namedType', name, source };
445
+ let suffix = text.slice(name.length);
446
+ while (suffix) {
447
+ if (suffix.startsWith('[]')) {
448
+ result = { type: 'listType', element: result, source };
449
+ suffix = suffix.slice(2);
450
+ }
451
+ else if (suffix.startsWith('?') && result.type !== 'nullableType') {
452
+ result = { type: 'nullableType', element: result, source };
453
+ suffix = suffix.slice(1);
454
+ }
455
+ else
456
+ throw new Error(`Invalid type reference '${text}'`);
457
+ }
458
+ return result;
459
+ }
460
+ function parseImportDeclaration(rawLine, source) {
461
+ const match = rawLine.match(/^\s*import\s*\{\s*([^}]*)\}\s*from\s*"([^"]*)"\s*$/);
462
+ if (!match)
463
+ throw new Error(`Invalid import declaration at ${source.line}:${source.column}`);
464
+ const namesText = match[1];
465
+ const braceIndex = rawLine.indexOf('{');
466
+ const names = [];
467
+ let cursor = braceIndex + 1;
468
+ for (const rawName of namesText.split(',')) {
469
+ const name = rawName.trim();
470
+ if (!/^[A-Za-z][A-Za-z0-9_]*$/.test(name))
471
+ throw new Error(`Invalid imported name '${rawName.trim()}' at ${source.line}:${source.column}`);
472
+ const nameStart = rawLine.indexOf(name, cursor);
473
+ names.push({ name, source: { line: source.line, column: nameStart + 1 } });
474
+ cursor = nameStart + name.length;
475
+ }
476
+ if (!names.length)
477
+ throw new Error(`Import requires at least one name at ${source.line}:${source.column}`);
478
+ const pathIndex = rawLine.lastIndexOf(`"${match[2]}"`);
479
+ return {
480
+ type: 'importDeclaration',
481
+ names,
482
+ path: match[2],
483
+ pathSource: { line: source.line, column: pathIndex + 2 },
484
+ source
485
+ };
486
+ }
487
+ function findFunctionEnd(lines, startIndex, source) {
488
+ let depth = 0;
489
+ let sawOpen = false;
490
+ let quote;
491
+ const scan = (line) => {
492
+ for (const ch of line) {
493
+ if (quote) {
494
+ if (ch === quote)
495
+ quote = undefined;
496
+ continue;
497
+ }
498
+ if (ch === '"' || ch === "'")
499
+ quote = ch;
500
+ else if (ch === '{') {
501
+ depth++;
502
+ sawOpen = true;
503
+ }
504
+ else if (ch === '}')
505
+ depth--;
506
+ }
507
+ };
508
+ scan(lines[startIndex]);
509
+ if (!sawOpen)
510
+ return startIndex; // single-line body with no braced constructs
511
+ let index = startIndex;
512
+ while (depth > 0) {
513
+ index++;
514
+ if (index >= lines.length)
515
+ throw new Error(`Unclosed function body at ${source.line}:${source.column}`);
516
+ scan(lines[index]);
517
+ }
518
+ return index;
519
+ }
520
+ function parseFunctionDeclaration(text, source, exported) {
521
+ const match = text.match(/^\s*fn\s+([A-Za-z][A-Za-z0-9_]*)\s*\(([^)]*)\)\s*:\s*([A-Za-z][A-Za-z0-9_]*(?:(?:\[\])|\?)*)\s*=\s*([\s\S]*)$/);
522
+ if (!match)
523
+ throw new Error(`Invalid function declaration at ${source.line}:${source.column}`);
524
+ const [, name, paramsText, returnTypeText, bodyText] = match;
525
+ const bodyOffset = text.indexOf(bodyText, text.indexOf('='));
526
+ const nestedDeclaration = /^(?:\s*)(?:(?:export\s+)?(?:dimension|unit)\s+[A-Za-z][A-Za-z0-9_]*|export\s*\{)/m.exec(bodyText);
527
+ if (nestedDeclaration) {
528
+ const declarationOffset = bodyOffset + nestedDeclaration.index + nestedDeclaration[0].search(/\S/);
529
+ const before = text.slice(0, declarationOffset).split(/\r?\n/);
530
+ staticError('AMX3008', 'Dimension/unit declarations and re-exports may only occur at module scope', {
531
+ line: source.line + before.length - 1,
532
+ column: before[before.length - 1].length + 1
533
+ });
534
+ }
535
+ const paramsRaw = paramsText.trim();
536
+ const parameters = [];
537
+ if (paramsRaw) {
538
+ for (const part of paramsRaw.split(',')) {
539
+ const paramMatch = part.trim().match(/^([A-Za-z][A-Za-z0-9_]*)\s*:\s*([A-Za-z][A-Za-z0-9_]*(?:(?:\[\])|\?)*)$/);
540
+ if (!paramMatch)
541
+ throw new Error(`Invalid function parameter at ${source.line}:${source.column}`);
542
+ parameters.push({ name: paramMatch[1], annotation: parseTypeReference(paramMatch[2], source), source });
543
+ }
544
+ }
545
+ const bodyTrimmed = bodyText.trim();
546
+ if (!bodyTrimmed)
547
+ throw new Error(`Missing function body at ${source.line}:${source.column}`);
548
+ let body;
549
+ try {
550
+ body = parseExpression(bodyTrimmed, source);
551
+ }
552
+ catch (error) {
553
+ const message = error instanceof Error ? error.message : String(error);
554
+ throw new Error(`Invalid function body at ${source.line}:${source.column}: ${message}`);
555
+ }
556
+ return {
557
+ type: 'functionDeclaration',
558
+ name,
559
+ parameters,
560
+ returnType: parseTypeReference(returnTypeText, source),
561
+ body,
562
+ ...(exported ? { exported } : {}),
563
+ source
564
+ };
565
+ }
566
+ function findLoopEnd(lines, startIndex, source) {
567
+ const text = lines.slice(startIndex).join('\n');
568
+ let open = -1;
569
+ let depth = 0;
570
+ for (let offset = 0; offset < text.length; offset++) {
571
+ const character = text[offset];
572
+ if (character === '"' || character === "'") {
573
+ const end = findStringLiteralEnd(text, offset);
574
+ if (end === undefined) {
575
+ const before = text.slice(0, offset).split('\n');
576
+ syntaxError('Invalid or incomplete string in for loop', {
577
+ line: source.line + before.length - 1,
578
+ column: before[before.length - 1].length + 1
579
+ });
580
+ }
581
+ offset = end;
582
+ continue;
583
+ }
584
+ if (character === '{') {
585
+ if (open === -1)
586
+ open = offset;
587
+ depth++;
588
+ }
589
+ else if (character === '}' && open !== -1) {
590
+ depth--;
591
+ if (depth === 0) {
592
+ return startIndex + text.slice(0, offset).split('\n').length - 1;
593
+ }
594
+ }
595
+ }
596
+ throw new Error(`${open === -1 ? "Expected '{' to start" : 'Unclosed'} for loop at ${source.line}:${source.column}`);
597
+ }
598
+ function collectExpressionLoop(lines, lineIndex, expression, start) {
599
+ if (!containsForExpression(expression) && !containsMatchExpression(expression)) {
600
+ return collectDelimitedExpression(lines, lineIndex, expression);
601
+ }
602
+ if (containsMatchExpression(expression) && !containsForExpression(expression)) {
603
+ const end = findLoopEnd(lines, lineIndex, { line: start.line + lineIndex, column: start.column });
604
+ const expressionOffset = lines[lineIndex].lastIndexOf(expression);
605
+ return {
606
+ text: [lines[lineIndex].slice(expressionOffset), ...lines.slice(lineIndex + 1, end + 1)].join('\n'),
607
+ lineCount: end - lineIndex + 1
608
+ };
609
+ }
610
+ const loopEnd = findLoopEnd(lines, lineIndex, {
611
+ line: start.line + lineIndex,
612
+ column: start.column
613
+ });
614
+ const expressionOffset = lines[lineIndex].lastIndexOf(expression);
615
+ return {
616
+ text: [lines[lineIndex].slice(expressionOffset), ...lines.slice(lineIndex + 1, loopEnd + 1)].join('\n'),
617
+ lineCount: loopEnd - lineIndex + 1
618
+ };
619
+ }
620
+ function collectDelimitedExpression(lines, lineIndex, expression) {
621
+ const expressionOffset = lines[lineIndex].lastIndexOf(expression);
622
+ const parts = [lines[lineIndex].slice(expressionOffset)];
623
+ const delimiters = [];
624
+ const scan = (text) => {
625
+ for (let index = 0; index < text.length; index++) {
626
+ const character = text[index];
627
+ if (character === '"' || character === "'") {
628
+ const end = findStringLiteralEnd(text, index);
629
+ if (end === undefined)
630
+ break;
631
+ index = end;
632
+ continue;
633
+ }
634
+ if (character === '(' || character === '[' || character === '{')
635
+ delimiters.push(character);
636
+ else if (character === ')' || character === ']' || character === '}') {
637
+ const expected = character === ')' ? '(' : character === ']' ? '[' : '{';
638
+ if (delimiters[delimiters.length - 1] === expected)
639
+ delimiters.pop();
640
+ }
641
+ }
642
+ };
643
+ scan(parts[0]);
644
+ let lineCount = 1;
645
+ const statementIndent = lines[lineIndex].length - lines[lineIndex].trimStart().length;
646
+ while (delimiters.length > 0 && lineIndex + lineCount < lines.length) {
647
+ const nextLine = lines[lineIndex + lineCount];
648
+ if (nextLine.trim()) {
649
+ const indentation = nextLine.length - nextLine.trimStart().length;
650
+ const previous = parts[parts.length - 1].trimEnd();
651
+ const startsStatement = /^(?:export\s+)?(?:let|type|fn|import|input|table|chart|show|for|return|add|remove)\b/.test(nextLine.trimStart())
652
+ || /^[A-Za-z][A-Za-z0-9_]*\s*(?:\+=|=(?!=))/.test(nextLine.trimStart());
653
+ if (indentation <= statementIndent && startsStatement && !/[,([{+\-*/%^=]$/.test(previous))
654
+ break;
655
+ }
656
+ parts.push(nextLine);
657
+ scan(nextLine);
658
+ lineCount++;
659
+ }
660
+ return { text: parts.join('\n'), lineCount };
661
+ }
662
+ function containsForExpression(text) {
663
+ return /\bfor\s+[A-Za-z][A-Za-z0-9_]*\s+in\b/.test(withoutStringLiterals(text));
664
+ }
665
+ function containsMatchExpression(text) {
666
+ return /\bmatch\s+/.test(withoutStringLiterals(text));
667
+ }