@nova-energy/openamx 0.15.0 → 0.18.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
1
  import { parseExpression } from './parseExpression';
2
2
  import { parseForStatement } from './parseFor';
3
- import { parseBracedIfStatement } from './parseIf';
3
+ import { parseBracedIfStatement, readIfBlocks } from './parseIf';
4
4
  import { AmxError, staticError, syntaxError } from '../diagnostics/errors';
5
5
  import { findStringLiteralEnd, withoutStringLiterals } from './stringScanner';
6
6
  /** Parse executable AMX statements while preserving original-document locations. */
@@ -16,6 +16,15 @@ export function parseStatements(body, start = { line: 1, column: 1 }, context =
16
16
  if (rawLine.trim().length === 0) {
17
17
  continue;
18
18
  }
19
+ if (context.inFunctionBody) {
20
+ const prohibited = functionBodyProhibitedStatement(rawLine);
21
+ if (prohibited) {
22
+ syntaxError(`The '${prohibited.keyword}' statement is not allowed in a function body.`, {
23
+ line: lineNumber,
24
+ column: i === 0 ? start.column + prohibited.column - 1 : prohibited.column
25
+ });
26
+ }
27
+ }
19
28
  const reExportMatch = rawLine.match(/^(\s*)export\s*\{\s*([^}]*)\s*\}\s*$/);
20
29
  if (reExportMatch) {
21
30
  const names = [];
@@ -265,23 +274,34 @@ export function parseStatements(body, start = { line: 1, column: 1 }, context =
265
274
  throw new Error(`Nested loops are unsupported at ${source.line}:${source.column}`);
266
275
  }
267
276
  const endIndex = findLoopEnd(lines, i, { line: lineNumber, column: source.column });
268
- statements.push(parseForStatement(lines.slice(i, endIndex + 1).join('\n'), source));
277
+ statements.push(parseForStatement(lines.slice(i, endIndex + 1).join('\n'), source, {
278
+ allowFunctionReturn: context.allowFunctionReturn,
279
+ inFunctionBody: context.inFunctionBody
280
+ }));
269
281
  i = endIndex;
270
282
  continue;
271
283
  }
272
284
  if (/^\s*(break|continue)\b/.test(rawLine)) {
273
285
  throw new Error(`Unsupported loop control statement at ${source.line}:${source.column}`);
274
286
  }
275
- const returnMatch = rawLine.match(/^\s*return\s+(.+)\s*$/);
276
- if (returnMatch) {
277
- if (context.allowReturn !== true) {
278
- throw new Error(`Return is only valid inside an expression-form for loop at ${source.line}:${source.column}`);
287
+ const returnKeyword = /^\s*return\b/.exec(rawLine);
288
+ if (returnKeyword) {
289
+ const returnMatch = rawLine.match(/^\s*return\s+(.+?)\s*$/);
290
+ if (context.allowReturn !== true && context.allowFunctionReturn !== true) {
291
+ syntaxError('Return is only valid inside a function or expression-form loop', source);
292
+ }
293
+ if (!returnMatch) {
294
+ syntaxError(context.inFunctionBody ? 'Invalid syntax in function body' : 'Invalid return statement', source);
279
295
  }
280
296
  const expressionText = collectExpressionLoop(lines, i, returnMatch[1], start);
297
+ const expressionSource = context.allowFunctionReturn === true
298
+ ? statementExpressionLocation(rawLine, rawLine.indexOf(returnMatch[1]), source)
299
+ : containsMatchExpression(expressionText.text)
300
+ ? { line: source.line, column: rawLine.indexOf(returnMatch[1]) + 1 }
301
+ : start;
281
302
  statements.push({
282
303
  type: 'returnStatement',
283
- expression: parseExpression(expressionText.text, containsMatchExpression(expressionText.text)
284
- ? { line: source.line, column: rawLine.indexOf(returnMatch[1]) + 1 } : source),
304
+ expression: parseExpression(expressionText.text, expressionSource),
285
305
  source
286
306
  });
287
307
  i += expressionText.lineCount - 1;
@@ -291,10 +311,7 @@ export function parseStatements(body, start = { line: 1, column: 1 }, context =
291
311
  if (addMatch) {
292
312
  const collected = collectDelimitedExpression(lines, i, addMatch[1]);
293
313
  const remainder = collected.text;
294
- const remainderSource = locationAtOffset(remainder, 0, {
295
- line: source.line,
296
- column: rawLine.length - addMatch[1].length + 1
297
- });
314
+ const remainderSource = statementExpressionLocation(rawLine, rawLine.lastIndexOf(addMatch[1]), source);
298
315
  const split = findTopLevelKeyword(remainder, 'to');
299
316
  if (!split)
300
317
  syntaxError('Invalid add statement', source);
@@ -325,10 +342,7 @@ export function parseStatements(body, start = { line: 1, column: 1 }, context =
325
342
  if (removeMatch) {
326
343
  const collected = collectDelimitedExpression(lines, i, removeMatch[1]);
327
344
  const remainder = collected.text;
328
- const remainderSource = locationAtOffset(remainder, 0, {
329
- line: source.line,
330
- column: rawLine.length - removeMatch[1].length + 1
331
- });
345
+ const remainderSource = statementExpressionLocation(rawLine, rawLine.lastIndexOf(removeMatch[1]), source);
332
346
  const split = findTopLevelKeyword(remainder, 'from');
333
347
  if (!split)
334
348
  syntaxError('Invalid remove statement', source);
@@ -361,8 +375,12 @@ export function parseStatements(body, start = { line: 1, column: 1 }, context =
361
375
  const expressionText = collectExpressionLoop(lines, i, letMatch[3], start);
362
376
  let expression;
363
377
  try {
378
+ const expressionOffset = rawLine.lastIndexOf(letMatch[3]);
379
+ const expressionSource = context.inFunctionBody
380
+ ? statementExpressionLocation(rawLine, expressionOffset, source)
381
+ : { line: source.line, column: expressionOffset + 1 };
364
382
  expression = parseExpression(expressionText.text, containsForExpression(expressionText.text) && !containsMatchExpression(expressionText.text)
365
- ? source : { line: source.line, column: rawLine.lastIndexOf(letMatch[3]) + 1 });
383
+ ? source : expressionSource);
366
384
  }
367
385
  catch (error) {
368
386
  if (error instanceof AmxError)
@@ -382,6 +400,13 @@ export function parseStatements(body, start = { line: 1, column: 1 }, context =
382
400
  i += expressionText.lineCount - 1;
383
401
  continue;
384
402
  }
403
+ if (context.inFunctionBody && /^\s*let\b/.test(rawLine)) {
404
+ const invalidToken = rawLine.indexOf('=') >= 0 ? rawLine.indexOf('=') : rawLine.search(/\S/);
405
+ syntaxError('Invalid syntax in function body', {
406
+ line: lineNumber,
407
+ column: i === 0 ? start.column + invalidToken : invalidToken + 1
408
+ });
409
+ }
385
410
  const compoundMatch = rawLine.match(/^\s*([A-Za-z][A-Za-z0-9_]*)\s*\+=\s*(.*)$/);
386
411
  const assignmentMatch = rawLine.match(/^\s*([A-Za-z][A-Za-z0-9_]*)\s*=(?!=)\s*(.*)$/);
387
412
  const assignment = compoundMatch ?? assignmentMatch;
@@ -392,7 +417,9 @@ export function parseStatements(body, start = { line: 1, column: 1 }, context =
392
417
  type: compoundMatch ? 'compoundAssignmentStatement' : 'assignmentStatement',
393
418
  name: assignment[1],
394
419
  ...(compoundMatch ? { operator: '+=' } : {}),
395
- expression: parseExpression(expressionText.text, { line: source.line, column: rawLine.lastIndexOf(assignment[2]) + 1 }),
420
+ expression: parseExpression(expressionText.text, context.inFunctionBody
421
+ ? statementExpressionLocation(rawLine, rawLine.lastIndexOf(assignment[2]), source)
422
+ : { line: source.line, column: rawLine.lastIndexOf(assignment[2]) + 1 }),
396
423
  source
397
424
  });
398
425
  }
@@ -405,6 +432,8 @@ export function parseStatements(body, start = { line: 1, column: 1 }, context =
405
432
  i += expressionText.lineCount - 1;
406
433
  continue;
407
434
  }
435
+ if (context.inFunctionBody)
436
+ syntaxError('Invalid syntax in function body', source);
408
437
  throw new Error(`Unsupported statement at ${source.line}:${source.column}`);
409
438
  }
410
439
  return statements;
@@ -416,6 +445,36 @@ function locationAtOffset(text, offset, source) {
416
445
  column: (before.length === 1 ? source.column : 1) + before[before.length - 1].length
417
446
  };
418
447
  }
448
+ function statementExpressionLocation(rawLine, offset, statementSource) {
449
+ const indentation = rawLine.length - rawLine.trimStart().length;
450
+ return locationAtOffset(rawLine, offset, {
451
+ line: statementSource.line,
452
+ column: statementSource.column - indentation
453
+ });
454
+ }
455
+ function functionBodyProhibitedStatement(rawLine) {
456
+ const prefix = rawLine.match(/^\s*(export)\b/);
457
+ if (prefix)
458
+ return { keyword: prefix[1], column: rawLine.indexOf(prefix[1]) + 1 };
459
+ const statement = rawLine.match(/^\s*(import|type|enum|dimension|unit|input|table|chart|diagram|show|fn)\b/);
460
+ if (!statement)
461
+ return undefined;
462
+ return { keyword: statement[1], column: rawLine.indexOf(statement[1]) + 1 };
463
+ }
464
+ function findUnquotedSemicolon(text) {
465
+ for (let offset = 0; offset < text.length; offset++) {
466
+ if (text[offset] === '"' || text[offset] === "'") {
467
+ const end = findStringLiteralEnd(text, offset);
468
+ if (end === undefined)
469
+ return undefined;
470
+ offset = end;
471
+ }
472
+ else if (text[offset] === ';') {
473
+ return offset;
474
+ }
475
+ }
476
+ return undefined;
477
+ }
419
478
  function findTopLevelKeyword(text, keyword) {
420
479
  let depth = 0;
421
480
  for (let index = 0; index < text.length; index++) {
@@ -533,7 +592,7 @@ function parseDiagramDeclaration(lines, startIndex, source) {
533
592
  nameSource: { line: source.line, column: headerLine.indexOf(name) + 1 },
534
593
  properties: [],
535
594
  times: [],
536
- elements: [],
595
+ content: [],
537
596
  source
538
597
  };
539
598
  let index = startIndex + 1;
@@ -590,46 +649,169 @@ function parseDiagramDeclaration(lines, startIndex, source) {
590
649
  index++;
591
650
  continue;
592
651
  }
593
- const elementHeader = line.match(/^\s*([A-Za-z][A-Za-z0-9_]*)\s+([A-Za-z][A-Za-z0-9_]*)\s*\{\s*$/);
594
- if (elementHeader) {
595
- const primitive = elementHeader[1];
596
- const elementName = elementHeader[2];
597
- const element = {
598
- type: 'diagramElement',
599
- primitive,
600
- name: elementName,
601
- nameSource: { line: lineSource.line, column: line.indexOf(elementName) + 1 },
602
- properties: [],
603
- source: { line: lineSource.line, column: lineSource.column }
604
- };
605
- index++;
606
- let elementClosed = false;
607
- while (index < lines.length) {
608
- const propertyLine = lines[index];
609
- if (/^\s*}\s*$/.test(propertyLine)) {
610
- elementClosed = true;
611
- index++;
612
- break;
613
- }
614
- if (!propertyLine.trim()) {
615
- index++;
616
- continue;
617
- }
618
- const property = parseDiagramProperty(lines, index, source.line + index - startIndex);
619
- element.properties.push(property.node);
620
- index += property.lineCount;
621
- }
622
- if (!elementClosed)
623
- syntaxError('Unclosed diagram element', element.source);
624
- statement.elements.push(element);
652
+ if (/^\s*(?:for|if)\b/.test(line) || /^\s*[A-Za-z][A-Za-z0-9_]*\s+[A-Za-z][A-Za-z0-9_]*\s*\{\s*$/.test(line)) {
653
+ const parsed = parseDiagramContentNodeAt(lines, index, lineSource, false);
654
+ statement.content.push(parsed.node);
655
+ index = parsed.endIndex + 1;
625
656
  continue;
626
657
  }
658
+ if (!/^\s*[A-Za-z][A-Za-z0-9_]*\s*:/.test(line)) {
659
+ syntaxError('Malformed for or if declaration', {
660
+ line: lineSource.line,
661
+ column: line.indexOf(line.trimStart()) + 1
662
+ });
663
+ }
627
664
  const property = parseDiagramProperty(lines, index, source.line + index - startIndex);
628
665
  statement.properties.push(property.node);
629
666
  index += property.lineCount;
630
667
  }
631
668
  syntaxError('Unclosed diagram declaration', source);
632
669
  }
670
+ function parseDiagramContentNodeAt(lines, index, source, insideFor) {
671
+ const line = lines[index];
672
+ if (/^\s*for\b/.test(line)) {
673
+ if (insideFor)
674
+ syntaxError('No nested loops are allowed inside a diagram', source);
675
+ const header = line.match(/^\s*for\s+([A-Za-z][A-Za-z0-9_]*)\s+in\s+(.+?)\s*\{\s*$/);
676
+ if (!header)
677
+ syntaxError('Malformed for or if declaration', source);
678
+ let endIndex;
679
+ try {
680
+ endIndex = findLoopEnd(lines, index, source);
681
+ }
682
+ catch (error) {
683
+ const diagnostic = error instanceof AmxError ? error : undefined;
684
+ syntaxError('Malformed for or if declaration', {
685
+ line: diagnostic?.line ?? source.line,
686
+ column: diagnostic?.column ?? source.column
687
+ });
688
+ }
689
+ const iterableText = header[2].trim();
690
+ const iterableSource = { line: source.line, column: line.indexOf(iterableText) + 1 };
691
+ const iterable = parseDiagramControlExpression(iterableText, iterableSource);
692
+ const bodyText = lines.slice(index + 1, endIndex).join('\n');
693
+ const variableSource = { line: source.line, column: line.indexOf(header[1]) + 1 };
694
+ const node = {
695
+ type: 'diagramForBlock',
696
+ variable: header[1],
697
+ variableSource,
698
+ iterable,
699
+ iterableText,
700
+ iterableSource,
701
+ content: parseDiagramContentSequence(bodyText, { line: source.line + 1, column: 1 }, true),
702
+ openSource: { line: source.line, column: line.lastIndexOf('{') + 1 },
703
+ closeSource: { line: source.line + endIndex - index, column: lines[endIndex].lastIndexOf('}') + 1 },
704
+ source
705
+ };
706
+ return { node, endIndex };
707
+ }
708
+ if (/^\s*if\b/.test(line)) {
709
+ const indentation = line.length - line.trimStart().length;
710
+ const controlText = lines.slice(index).join('\n').slice(indentation);
711
+ const controlSource = { line: source.line, column: source.column };
712
+ let blocks;
713
+ try {
714
+ blocks = readIfBlocks(controlText, controlSource);
715
+ }
716
+ catch (error) {
717
+ const diagnostic = error instanceof AmxError ? error : undefined;
718
+ syntaxError('Malformed for or if declaration', {
719
+ line: diagnostic?.line ?? source.line,
720
+ column: diagnostic?.column ?? source.column
721
+ });
722
+ }
723
+ const consumedLines = controlText.slice(0, blocks.endOffset).split('\n').length;
724
+ const endIndex = index + consumedLines - 1;
725
+ const testSource = locationAtOffset(controlText, controlText.indexOf(blocks.condition), controlSource);
726
+ const test = parseDiagramControlExpression(blocks.condition, testSource);
727
+ const node = {
728
+ type: 'diagramIfBlock',
729
+ test,
730
+ testText: blocks.condition,
731
+ testSource,
732
+ consequent: parseDiagramContentSequence(blocks.consequent, blocks.consequentSource, insideFor),
733
+ ...(blocks.alternate === undefined ? {} : {
734
+ alternate: parseDiagramContentSequence(blocks.alternate, blocks.alternateSource, insideFor)
735
+ }),
736
+ consequentOpenSource: blocks.consequentOpenSource,
737
+ consequentCloseSource: blocks.consequentClosingSource,
738
+ ...(blocks.alternate === undefined ? {} : {
739
+ elseSource: blocks.elseSource,
740
+ alternateOpenSource: blocks.alternateOpenSource,
741
+ alternateCloseSource: blocks.alternateClosingSource
742
+ }),
743
+ source
744
+ };
745
+ return { node, endIndex };
746
+ }
747
+ const elementHeader = line.match(/^\s*([A-Za-z][A-Za-z0-9_]*)\s+([A-Za-z][A-Za-z0-9_]*)\s*\{\s*$/);
748
+ if (!elementHeader)
749
+ syntaxError('Malformed for or if declaration', source);
750
+ const element = {
751
+ type: 'diagramElement',
752
+ primitive: elementHeader[1],
753
+ name: elementHeader[2],
754
+ nameSource: { line: source.line, column: line.indexOf(elementHeader[2]) + 1 },
755
+ properties: [],
756
+ source
757
+ };
758
+ let endIndex = index + 1;
759
+ let elementClosed = false;
760
+ while (endIndex < lines.length) {
761
+ const propertyLine = lines[endIndex];
762
+ if (/^\s*}\s*$/.test(propertyLine)) {
763
+ elementClosed = true;
764
+ break;
765
+ }
766
+ if (!propertyLine.trim()) {
767
+ endIndex++;
768
+ continue;
769
+ }
770
+ if (/^\s*(?:for|if)\b/.test(propertyLine)
771
+ || /^\s*[A-Za-z][A-Za-z0-9_]*\s+[A-Za-z][A-Za-z0-9_]*\s*\{\s*$/.test(propertyLine)) {
772
+ syntaxError('Malformed for or if declaration', {
773
+ line: source.line + endIndex - index,
774
+ column: propertyLine.indexOf(propertyLine.trimStart()) + 1
775
+ });
776
+ }
777
+ const property = parseDiagramProperty(lines, endIndex, source.line + endIndex - index);
778
+ element.properties.push(property.node);
779
+ endIndex += property.lineCount;
780
+ }
781
+ if (!elementClosed)
782
+ syntaxError('Unclosed diagram element', element.source);
783
+ return { node: element, endIndex };
784
+ }
785
+ function parseDiagramContentSequence(text, source, insideFor) {
786
+ const lines = text.split(/\r?\n/);
787
+ const content = [];
788
+ for (let index = 0; index < lines.length; index++) {
789
+ const line = lines[index];
790
+ if (!line.trim())
791
+ continue;
792
+ const indentation = line.length - line.trimStart().length;
793
+ const lineSource = {
794
+ line: source.line + index,
795
+ column: (index === 0 ? source.column : 1) + indentation
796
+ };
797
+ const parsed = parseDiagramContentNodeAt(lines, index, lineSource, insideFor);
798
+ content.push(parsed.node);
799
+ index = parsed.endIndex;
800
+ }
801
+ return content;
802
+ }
803
+ function parseDiagramControlExpression(text, source) {
804
+ try {
805
+ return parseExpression(text, source);
806
+ }
807
+ catch (error) {
808
+ const diagnostic = error instanceof AmxError ? error : undefined;
809
+ syntaxError('Malformed for or if declaration', {
810
+ line: diagnostic?.line ?? source.line,
811
+ column: diagnostic?.column ?? source.column
812
+ });
813
+ }
814
+ }
633
815
  function parseDiagramProperty(lines, index, lineNumber) {
634
816
  const line = lines[index];
635
817
  const match = line.match(/^\s*([A-Za-z][A-Za-z0-9_]*)\s*:\s*(.*)$/);
@@ -710,84 +892,184 @@ function parseImportDeclaration(rawLine, source) {
710
892
  };
711
893
  }
712
894
  function findFunctionEnd(lines, startIndex, source) {
895
+ const firstLine = lines[startIndex] ?? '';
896
+ const expressionBody = firstLine.match(/^\s*fn\s+[A-Za-z][A-Za-z0-9_]*\s*\([^)]*\)\s*:\s*[A-Za-z][A-Za-z0-9_]*(?:(?:\[\])|\?)*\s*=\s*(.*)$/);
897
+ if (expressionBody?.[1]) {
898
+ try {
899
+ parseExpression(expressionBody[1], source);
900
+ return startIndex;
901
+ }
902
+ catch {
903
+ }
904
+ }
905
+ const text = lines.slice(startIndex).join('\n');
713
906
  let depth = 0;
714
- let sawOpen = false;
715
- let quote;
716
- const scan = (line) => {
717
- for (const ch of line) {
718
- if (quote) {
719
- if (ch === quote)
720
- quote = undefined;
721
- continue;
722
- }
723
- if (ch === '"' || ch === "'")
724
- quote = ch;
725
- else if (ch === '{') {
726
- depth++;
727
- sawOpen = true;
907
+ let openingOffset;
908
+ for (let offset = 0; offset < text.length; offset++) {
909
+ if (text[offset] === '"' || text[offset] === "'") {
910
+ const end = findStringLiteralEnd(text, offset);
911
+ if (end === undefined) {
912
+ if (openingOffset !== undefined)
913
+ syntaxError('Invalid syntax in function body', functionTextLocation(text, offset, source));
914
+ return startIndex;
728
915
  }
729
- else if (ch === '}')
730
- depth--;
916
+ offset = end;
917
+ continue;
918
+ }
919
+ if (text[offset] === '{') {
920
+ if (openingOffset === undefined)
921
+ openingOffset = offset;
922
+ depth++;
923
+ }
924
+ else if (text[offset] === '}' && openingOffset !== undefined) {
925
+ depth--;
926
+ if (depth === 0)
927
+ return startIndex + text.slice(0, offset).split('\n').length - 1;
731
928
  }
732
- };
733
- scan(lines[startIndex]);
734
- if (!sawOpen)
735
- return startIndex; // single-line body with no braced constructs
736
- let index = startIndex;
737
- while (depth > 0) {
738
- index++;
739
- if (index >= lines.length)
740
- throw new Error(`Unclosed function body at ${source.line}:${source.column}`);
741
- scan(lines[index]);
742
929
  }
743
- return index;
930
+ if (openingOffset === undefined)
931
+ return startIndex;
932
+ syntaxError('Unclosed function body', functionTextLocation(text, openingOffset, source));
744
933
  }
745
934
  function parseFunctionDeclaration(text, source, exported) {
746
- 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]*)$/);
935
+ 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]*)$/);
747
936
  if (!match)
748
937
  throw new Error(`Invalid function declaration at ${source.line}:${source.column}`);
749
- const [, name, paramsText, returnTypeText, bodyText] = match;
750
- const bodyOffset = text.indexOf(bodyText, text.indexOf('='));
751
- const nestedDeclaration = /^(?:\s*)(?:(?:export\s+)?(?:dimension|unit)\s+[A-Za-z][A-Za-z0-9_]*|export\s*\{)/m.exec(bodyText);
752
- if (nestedDeclaration) {
753
- const declarationOffset = bodyOffset + nestedDeclaration.index + nestedDeclaration[0].search(/\S/);
754
- const before = text.slice(0, declarationOffset).split(/\r?\n/);
755
- staticError('AMX3008', 'Dimension/unit declarations and re-exports may only occur at module scope', {
756
- line: source.line + before.length - 1,
757
- column: before[before.length - 1].length + 1
758
- });
759
- }
938
+ const [, name, paramsText, returnTypeText, bodySuffix] = match;
760
939
  const paramsRaw = paramsText.trim();
761
940
  const parameters = [];
941
+ const functionKeywordOffset = text.indexOf('fn');
942
+ const functionNameOffset = text.indexOf(name, functionKeywordOffset + 'fn'.length);
943
+ const paramsOffset = text.indexOf('(', functionNameOffset + name.length) + 1;
944
+ let parameterCursor = 0;
762
945
  if (paramsRaw) {
763
- for (const part of paramsRaw.split(',')) {
764
- const paramMatch = part.trim().match(/^([A-Za-z][A-Za-z0-9_]*)\s*:\s*([A-Za-z][A-Za-z0-9_]*(?:(?:\[\])|\?)*)$/);
946
+ for (const part of paramsText.split(',')) {
947
+ const leadingWhitespace = part.length - part.trimStart().length;
948
+ const parameterText = part.trim();
949
+ const paramMatch = parameterText.match(/^([A-Za-z][A-Za-z0-9_]*)\s*:\s*([A-Za-z][A-Za-z0-9_]*(?:(?:\[\])|\?)*)$/);
765
950
  if (!paramMatch)
766
951
  throw new Error(`Invalid function parameter at ${source.line}:${source.column}`);
767
- parameters.push({ name: paramMatch[1], annotation: parseTypeReference(paramMatch[2], source), source });
952
+ const nameOffset = paramsOffset + parameterCursor + leadingWhitespace + parameterText.indexOf(paramMatch[1]);
953
+ const typeOffset = paramsOffset + parameterCursor + leadingWhitespace
954
+ + parameterText.indexOf(paramMatch[2], parameterText.indexOf(paramMatch[1]) + paramMatch[1].length);
955
+ parameters.push({
956
+ name: paramMatch[1],
957
+ annotation: parseTypeReference(paramMatch[2], functionTextLocation(text, typeOffset, source)),
958
+ source: functionTextLocation(text, nameOffset, source)
959
+ });
960
+ parameterCursor += part.length + 1;
768
961
  }
769
962
  }
770
- const bodyTrimmed = bodyText.trim();
963
+ const returnTypeOffset = text.indexOf(returnTypeText, text.indexOf(')') + 1);
964
+ const bodyOffset = text.length - bodySuffix.length;
965
+ const bodyTrimmed = bodySuffix.trim();
771
966
  if (!bodyTrimmed)
772
967
  throw new Error(`Missing function body at ${source.line}:${source.column}`);
773
968
  let body;
774
- try {
775
- body = parseExpression(bodyTrimmed, source);
969
+ if (bodyTrimmed.startsWith('=')) {
970
+ const expressionText = bodyTrimmed.slice(1).trim();
971
+ const nestedDeclaration = /^(?:\s*)(?:(?:export\s+)?(?:dimension|unit)\s+[A-Za-z][A-Za-z0-9_]*|export\s*\{)/m.exec(expressionText);
972
+ if (nestedDeclaration) {
973
+ const declarationOffset = bodyOffset + bodySuffix.indexOf(expressionText) + nestedDeclaration.index + nestedDeclaration[0].search(/\S/);
974
+ staticError('AMX3008', 'Dimension/unit declarations and re-exports may only occur at module scope', functionTextLocation(text, declarationOffset, source));
975
+ }
976
+ if (!expressionText)
977
+ throw new Error(`Missing function body at ${source.line}:${source.column}`);
978
+ let expression;
979
+ try {
980
+ expression = parseExpression(expressionText, source);
981
+ }
982
+ catch (error) {
983
+ const message = error instanceof Error ? error.message : String(error);
984
+ throw new Error(`Invalid function body at ${source.line}:${source.column}: ${message}`);
985
+ }
986
+ body = { kind: 'expression', expression };
776
987
  }
777
- catch (error) {
778
- const message = error instanceof Error ? error.message : String(error);
779
- throw new Error(`Invalid function body at ${source.line}:${source.column}: ${message}`);
988
+ else if (bodyTrimmed.startsWith('{')) {
989
+ const openingOffset = bodyOffset + bodySuffix.indexOf('{');
990
+ const openingSource = functionTextLocation(text, openingOffset, source);
991
+ const closingOffset = matchingFunctionBrace(text, openingOffset, source);
992
+ if (closingOffset === undefined)
993
+ syntaxError('Unclosed function body', openingSource);
994
+ const trailingText = text.slice(closingOffset + 1);
995
+ if (trailingText.trim()) {
996
+ const trailingOffset = closingOffset + 1 + trailingText.search(/\S/);
997
+ syntaxError('Invalid syntax in function body', functionTextLocation(text, trailingOffset, source));
998
+ }
999
+ const statementText = text.slice(openingOffset + 1, closingOffset);
1000
+ const statementsSource = functionTextLocation(text, openingOffset + 1, source);
1001
+ const semicolonOffset = findUnquotedSemicolon(statementText);
1002
+ if (semicolonOffset !== undefined) {
1003
+ syntaxError('Invalid syntax in function body', functionTextLocation(text, openingOffset + 1 + semicolonOffset, source));
1004
+ }
1005
+ let statements;
1006
+ try {
1007
+ statements = parseStatements(statementText, statementsSource, {
1008
+ allowFunctionReturn: true,
1009
+ inFunctionBody: true
1010
+ });
1011
+ }
1012
+ catch (error) {
1013
+ if (error instanceof AmxError && (error.message === 'Invalid syntax in function body'
1014
+ || error.message === 'Return is only valid inside a function or expression-form loop'
1015
+ || /^The '.+' statement is not allowed in a function body\.$/.test(error.message)))
1016
+ throw error;
1017
+ if (error instanceof Error && /^(Nested loops are unsupported|Unsupported loop control statement)/.test(error.message)) {
1018
+ throw error;
1019
+ }
1020
+ const location = error instanceof AmxError && error.line && error.column
1021
+ ? { line: error.line, column: error.column }
1022
+ : error instanceof Error
1023
+ ? errorLocationFromMessage(error.message) ?? openingSource
1024
+ : openingSource;
1025
+ syntaxError('Invalid syntax in function body', location);
1026
+ }
1027
+ body = {
1028
+ kind: 'statements',
1029
+ statements,
1030
+ source: openingSource,
1031
+ openingSource,
1032
+ closingSource: functionTextLocation(text, closingOffset, source)
1033
+ };
1034
+ }
1035
+ else {
1036
+ syntaxError('Invalid syntax in function body', functionTextLocation(text, bodyOffset, source));
780
1037
  }
781
1038
  return {
782
1039
  type: 'functionDeclaration',
783
1040
  name,
784
1041
  parameters,
785
- returnType: parseTypeReference(returnTypeText, source),
1042
+ returnType: parseTypeReference(returnTypeText, functionTextLocation(text, returnTypeOffset, source)),
786
1043
  body,
787
1044
  ...(exported ? { exported } : {}),
788
1045
  source
789
1046
  };
790
1047
  }
1048
+ function matchingFunctionBrace(text, openingOffset, source) {
1049
+ let depth = 0;
1050
+ for (let offset = openingOffset; offset < text.length; offset++) {
1051
+ if (text[offset] === '"' || text[offset] === "'") {
1052
+ const end = findStringLiteralEnd(text, offset);
1053
+ if (end === undefined)
1054
+ syntaxError('Invalid syntax in function body', functionTextLocation(text, offset, source));
1055
+ offset = end;
1056
+ continue;
1057
+ }
1058
+ if (text[offset] === '{')
1059
+ depth++;
1060
+ else if (text[offset] === '}' && --depth === 0)
1061
+ return offset;
1062
+ }
1063
+ return undefined;
1064
+ }
1065
+ function functionTextLocation(text, offset, source) {
1066
+ const functionOffset = text.indexOf('fn');
1067
+ return locationAtOffset(text.slice(functionOffset), offset - functionOffset, source);
1068
+ }
1069
+ function errorLocationFromMessage(message) {
1070
+ const match = message.match(/(?:at\s+)?(\d+):(\d+)\b/);
1071
+ return match ? { line: Number(match[1]), column: Number(match[2]) } : undefined;
1072
+ }
791
1073
  function findLoopEnd(lines, startIndex, source) {
792
1074
  const text = lines.slice(startIndex).join('\n');
793
1075
  let open = -1;
@@ -84,12 +84,13 @@ async function deserializePayload(payload) {
84
84
  }
85
85
  function syncControls(state) {
86
86
  const title = state.model.title;
87
+ const displayTime = state.time.toFixed(3).toString();
87
88
  state.playButton.textContent = state.running ? 'Pause' : 'Play';
88
89
  state.playButton.setAttribute('aria-label', `${state.running ? 'Pause' : 'Play'} ${title}`);
89
90
  state.scrubber.value = String(state.time);
90
- state.scrubber.setAttribute('aria-valuetext', String(state.time));
91
- state.timeOutput.value = String(state.time);
92
- state.timeOutput.textContent = String(state.time);
91
+ state.scrubber.setAttribute('aria-valuetext', displayTime);
92
+ state.timeOutput.value = displayTime;
93
+ state.timeOutput.textContent = displayTime;
93
94
  }
94
95
  function stop(state) {
95
96
  state.running = false;