@nova-energy/openamx 0.14.0 → 0.16.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +136 -513
- package/dist/diagnostics/errors.js +9 -0
- package/dist/editor/completion.js +100 -5
- package/dist/editor/highlighting.js +26 -3
- package/dist/editor/symbols.js +122 -2
- package/dist/formatter/formatAmx.js +2 -2
- package/dist/parser/parseFor.js +2 -5
- package/dist/parser/parseStatements.js +225 -66
- package/dist/runtime/evaluateExpression.js +69 -8
- package/dist/typechecker/checkDocument.js +68 -4
- package/package.json +3 -3
|
@@ -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
|
|
276
|
-
if (
|
|
277
|
-
|
|
278
|
-
|
|
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,
|
|
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 =
|
|
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 =
|
|
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 :
|
|
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,
|
|
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++) {
|
|
@@ -710,84 +769,184 @@ function parseImportDeclaration(rawLine, source) {
|
|
|
710
769
|
};
|
|
711
770
|
}
|
|
712
771
|
function findFunctionEnd(lines, startIndex, source) {
|
|
772
|
+
const firstLine = lines[startIndex] ?? '';
|
|
773
|
+
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*(.*)$/);
|
|
774
|
+
if (expressionBody?.[1]) {
|
|
775
|
+
try {
|
|
776
|
+
parseExpression(expressionBody[1], source);
|
|
777
|
+
return startIndex;
|
|
778
|
+
}
|
|
779
|
+
catch {
|
|
780
|
+
}
|
|
781
|
+
}
|
|
782
|
+
const text = lines.slice(startIndex).join('\n');
|
|
713
783
|
let depth = 0;
|
|
714
|
-
let
|
|
715
|
-
let
|
|
716
|
-
|
|
717
|
-
|
|
718
|
-
if (
|
|
719
|
-
if (
|
|
720
|
-
|
|
721
|
-
|
|
722
|
-
}
|
|
723
|
-
if (ch === '"' || ch === "'")
|
|
724
|
-
quote = ch;
|
|
725
|
-
else if (ch === '{') {
|
|
726
|
-
depth++;
|
|
727
|
-
sawOpen = true;
|
|
784
|
+
let openingOffset;
|
|
785
|
+
for (let offset = 0; offset < text.length; offset++) {
|
|
786
|
+
if (text[offset] === '"' || text[offset] === "'") {
|
|
787
|
+
const end = findStringLiteralEnd(text, offset);
|
|
788
|
+
if (end === undefined) {
|
|
789
|
+
if (openingOffset !== undefined)
|
|
790
|
+
syntaxError('Invalid syntax in function body', functionTextLocation(text, offset, source));
|
|
791
|
+
return startIndex;
|
|
728
792
|
}
|
|
729
|
-
|
|
730
|
-
|
|
793
|
+
offset = end;
|
|
794
|
+
continue;
|
|
795
|
+
}
|
|
796
|
+
if (text[offset] === '{') {
|
|
797
|
+
if (openingOffset === undefined)
|
|
798
|
+
openingOffset = offset;
|
|
799
|
+
depth++;
|
|
800
|
+
}
|
|
801
|
+
else if (text[offset] === '}' && openingOffset !== undefined) {
|
|
802
|
+
depth--;
|
|
803
|
+
if (depth === 0)
|
|
804
|
+
return startIndex + text.slice(0, offset).split('\n').length - 1;
|
|
731
805
|
}
|
|
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
806
|
}
|
|
743
|
-
|
|
807
|
+
if (openingOffset === undefined)
|
|
808
|
+
return startIndex;
|
|
809
|
+
syntaxError('Unclosed function body', functionTextLocation(text, openingOffset, source));
|
|
744
810
|
}
|
|
745
811
|
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
|
|
812
|
+
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
813
|
if (!match)
|
|
748
814
|
throw new Error(`Invalid function declaration at ${source.line}:${source.column}`);
|
|
749
|
-
const [, name, paramsText, returnTypeText,
|
|
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
|
-
}
|
|
815
|
+
const [, name, paramsText, returnTypeText, bodySuffix] = match;
|
|
760
816
|
const paramsRaw = paramsText.trim();
|
|
761
817
|
const parameters = [];
|
|
818
|
+
const functionKeywordOffset = text.indexOf('fn');
|
|
819
|
+
const functionNameOffset = text.indexOf(name, functionKeywordOffset + 'fn'.length);
|
|
820
|
+
const paramsOffset = text.indexOf('(', functionNameOffset + name.length) + 1;
|
|
821
|
+
let parameterCursor = 0;
|
|
762
822
|
if (paramsRaw) {
|
|
763
|
-
for (const part of
|
|
764
|
-
const
|
|
823
|
+
for (const part of paramsText.split(',')) {
|
|
824
|
+
const leadingWhitespace = part.length - part.trimStart().length;
|
|
825
|
+
const parameterText = part.trim();
|
|
826
|
+
const paramMatch = parameterText.match(/^([A-Za-z][A-Za-z0-9_]*)\s*:\s*([A-Za-z][A-Za-z0-9_]*(?:(?:\[\])|\?)*)$/);
|
|
765
827
|
if (!paramMatch)
|
|
766
828
|
throw new Error(`Invalid function parameter at ${source.line}:${source.column}`);
|
|
767
|
-
|
|
829
|
+
const nameOffset = paramsOffset + parameterCursor + leadingWhitespace + parameterText.indexOf(paramMatch[1]);
|
|
830
|
+
const typeOffset = paramsOffset + parameterCursor + leadingWhitespace
|
|
831
|
+
+ parameterText.indexOf(paramMatch[2], parameterText.indexOf(paramMatch[1]) + paramMatch[1].length);
|
|
832
|
+
parameters.push({
|
|
833
|
+
name: paramMatch[1],
|
|
834
|
+
annotation: parseTypeReference(paramMatch[2], functionTextLocation(text, typeOffset, source)),
|
|
835
|
+
source: functionTextLocation(text, nameOffset, source)
|
|
836
|
+
});
|
|
837
|
+
parameterCursor += part.length + 1;
|
|
768
838
|
}
|
|
769
839
|
}
|
|
770
|
-
const
|
|
840
|
+
const returnTypeOffset = text.indexOf(returnTypeText, text.indexOf(')') + 1);
|
|
841
|
+
const bodyOffset = text.length - bodySuffix.length;
|
|
842
|
+
const bodyTrimmed = bodySuffix.trim();
|
|
771
843
|
if (!bodyTrimmed)
|
|
772
844
|
throw new Error(`Missing function body at ${source.line}:${source.column}`);
|
|
773
845
|
let body;
|
|
774
|
-
|
|
775
|
-
|
|
846
|
+
if (bodyTrimmed.startsWith('=')) {
|
|
847
|
+
const expressionText = bodyTrimmed.slice(1).trim();
|
|
848
|
+
const nestedDeclaration = /^(?:\s*)(?:(?:export\s+)?(?:dimension|unit)\s+[A-Za-z][A-Za-z0-9_]*|export\s*\{)/m.exec(expressionText);
|
|
849
|
+
if (nestedDeclaration) {
|
|
850
|
+
const declarationOffset = bodyOffset + bodySuffix.indexOf(expressionText) + nestedDeclaration.index + nestedDeclaration[0].search(/\S/);
|
|
851
|
+
staticError('AMX3008', 'Dimension/unit declarations and re-exports may only occur at module scope', functionTextLocation(text, declarationOffset, source));
|
|
852
|
+
}
|
|
853
|
+
if (!expressionText)
|
|
854
|
+
throw new Error(`Missing function body at ${source.line}:${source.column}`);
|
|
855
|
+
let expression;
|
|
856
|
+
try {
|
|
857
|
+
expression = parseExpression(expressionText, source);
|
|
858
|
+
}
|
|
859
|
+
catch (error) {
|
|
860
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
861
|
+
throw new Error(`Invalid function body at ${source.line}:${source.column}: ${message}`);
|
|
862
|
+
}
|
|
863
|
+
body = { kind: 'expression', expression };
|
|
864
|
+
}
|
|
865
|
+
else if (bodyTrimmed.startsWith('{')) {
|
|
866
|
+
const openingOffset = bodyOffset + bodySuffix.indexOf('{');
|
|
867
|
+
const openingSource = functionTextLocation(text, openingOffset, source);
|
|
868
|
+
const closingOffset = matchingFunctionBrace(text, openingOffset, source);
|
|
869
|
+
if (closingOffset === undefined)
|
|
870
|
+
syntaxError('Unclosed function body', openingSource);
|
|
871
|
+
const trailingText = text.slice(closingOffset + 1);
|
|
872
|
+
if (trailingText.trim()) {
|
|
873
|
+
const trailingOffset = closingOffset + 1 + trailingText.search(/\S/);
|
|
874
|
+
syntaxError('Invalid syntax in function body', functionTextLocation(text, trailingOffset, source));
|
|
875
|
+
}
|
|
876
|
+
const statementText = text.slice(openingOffset + 1, closingOffset);
|
|
877
|
+
const statementsSource = functionTextLocation(text, openingOffset + 1, source);
|
|
878
|
+
const semicolonOffset = findUnquotedSemicolon(statementText);
|
|
879
|
+
if (semicolonOffset !== undefined) {
|
|
880
|
+
syntaxError('Invalid syntax in function body', functionTextLocation(text, openingOffset + 1 + semicolonOffset, source));
|
|
881
|
+
}
|
|
882
|
+
let statements;
|
|
883
|
+
try {
|
|
884
|
+
statements = parseStatements(statementText, statementsSource, {
|
|
885
|
+
allowFunctionReturn: true,
|
|
886
|
+
inFunctionBody: true
|
|
887
|
+
});
|
|
888
|
+
}
|
|
889
|
+
catch (error) {
|
|
890
|
+
if (error instanceof AmxError && (error.message === 'Invalid syntax in function body'
|
|
891
|
+
|| error.message === 'Return is only valid inside a function or expression-form loop'
|
|
892
|
+
|| /^The '.+' statement is not allowed in a function body\.$/.test(error.message)))
|
|
893
|
+
throw error;
|
|
894
|
+
if (error instanceof Error && /^(Nested loops are unsupported|Unsupported loop control statement)/.test(error.message)) {
|
|
895
|
+
throw error;
|
|
896
|
+
}
|
|
897
|
+
const location = error instanceof AmxError && error.line && error.column
|
|
898
|
+
? { line: error.line, column: error.column }
|
|
899
|
+
: error instanceof Error
|
|
900
|
+
? errorLocationFromMessage(error.message) ?? openingSource
|
|
901
|
+
: openingSource;
|
|
902
|
+
syntaxError('Invalid syntax in function body', location);
|
|
903
|
+
}
|
|
904
|
+
body = {
|
|
905
|
+
kind: 'statements',
|
|
906
|
+
statements,
|
|
907
|
+
source: openingSource,
|
|
908
|
+
openingSource,
|
|
909
|
+
closingSource: functionTextLocation(text, closingOffset, source)
|
|
910
|
+
};
|
|
776
911
|
}
|
|
777
|
-
|
|
778
|
-
|
|
779
|
-
throw new Error(`Invalid function body at ${source.line}:${source.column}: ${message}`);
|
|
912
|
+
else {
|
|
913
|
+
syntaxError('Invalid syntax in function body', functionTextLocation(text, bodyOffset, source));
|
|
780
914
|
}
|
|
781
915
|
return {
|
|
782
916
|
type: 'functionDeclaration',
|
|
783
917
|
name,
|
|
784
918
|
parameters,
|
|
785
|
-
returnType: parseTypeReference(returnTypeText, source),
|
|
919
|
+
returnType: parseTypeReference(returnTypeText, functionTextLocation(text, returnTypeOffset, source)),
|
|
786
920
|
body,
|
|
787
921
|
...(exported ? { exported } : {}),
|
|
788
922
|
source
|
|
789
923
|
};
|
|
790
924
|
}
|
|
925
|
+
function matchingFunctionBrace(text, openingOffset, source) {
|
|
926
|
+
let depth = 0;
|
|
927
|
+
for (let offset = openingOffset; offset < text.length; offset++) {
|
|
928
|
+
if (text[offset] === '"' || text[offset] === "'") {
|
|
929
|
+
const end = findStringLiteralEnd(text, offset);
|
|
930
|
+
if (end === undefined)
|
|
931
|
+
syntaxError('Invalid syntax in function body', functionTextLocation(text, offset, source));
|
|
932
|
+
offset = end;
|
|
933
|
+
continue;
|
|
934
|
+
}
|
|
935
|
+
if (text[offset] === '{')
|
|
936
|
+
depth++;
|
|
937
|
+
else if (text[offset] === '}' && --depth === 0)
|
|
938
|
+
return offset;
|
|
939
|
+
}
|
|
940
|
+
return undefined;
|
|
941
|
+
}
|
|
942
|
+
function functionTextLocation(text, offset, source) {
|
|
943
|
+
const functionOffset = text.indexOf('fn');
|
|
944
|
+
return locationAtOffset(text.slice(functionOffset), offset - functionOffset, source);
|
|
945
|
+
}
|
|
946
|
+
function errorLocationFromMessage(message) {
|
|
947
|
+
const match = message.match(/(?:at\s+)?(\d+):(\d+)\b/);
|
|
948
|
+
return match ? { line: Number(match[1]), column: Number(match[2]) } : undefined;
|
|
949
|
+
}
|
|
791
950
|
function findLoopEnd(lines, startIndex, source) {
|
|
792
951
|
const text = lines.slice(startIndex).join('\n');
|
|
793
952
|
let open = -1;
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { inputError, staticError, throwInputErrors, throwInvalidLoopIterable, throwInvalidRangeBounds, throwInvalidReturnContext, throwListOperationError, throwMeasurementDomainError } from '../diagnostics/errors';
|
|
1
|
+
import { inputError, staticError, throwInputErrors, throwInvalidLoopIterable, throwInvalidRangeBounds, throwInvalidReturnContext, throwFunctionFallthrough, throwListOperationError, throwMeasurementDomainError } from '../diagnostics/errors';
|
|
2
2
|
import { Environment } from './environment';
|
|
3
3
|
import { evaluateStandardLibraryCall, isMathematicalFunction } from './standardLibrary';
|
|
4
4
|
import { fieldRegistry } from '../typechecker/declarationRegistry';
|
|
@@ -464,8 +464,16 @@ class ForExpressionReturn {
|
|
|
464
464
|
this.value = value;
|
|
465
465
|
}
|
|
466
466
|
}
|
|
467
|
+
class FunctionBodyReturn {
|
|
468
|
+
value;
|
|
469
|
+
constructor(value) {
|
|
470
|
+
this.value = value;
|
|
471
|
+
}
|
|
472
|
+
}
|
|
467
473
|
const conditionalReturnDepth = new WeakMap();
|
|
468
474
|
const forExpressionDepth = new WeakMap();
|
|
475
|
+
const functionReturnDepth = new WeakMap();
|
|
476
|
+
const scopedBindings = new WeakMap();
|
|
469
477
|
function withDepth(depths, env, run) {
|
|
470
478
|
depths.set(env, (depths.get(env) ?? 0) + 1);
|
|
471
479
|
try {
|
|
@@ -479,16 +487,32 @@ function withDepth(depths, env, run) {
|
|
|
479
487
|
depths.delete(env);
|
|
480
488
|
}
|
|
481
489
|
}
|
|
490
|
+
function rememberScopedBinding(name, env) {
|
|
491
|
+
const scopes = scopedBindings.get(env);
|
|
492
|
+
const currentScope = scopes?.[scopes.length - 1];
|
|
493
|
+
if (!currentScope || currentScope.has(name))
|
|
494
|
+
return;
|
|
495
|
+
const existed = env.has(name);
|
|
496
|
+
currentScope.set(name, { existed, value: existed ? env.get(name) : undefined });
|
|
497
|
+
}
|
|
482
498
|
function evaluateScopedStatements(statements, env, file) {
|
|
483
|
-
const
|
|
499
|
+
const scopes = scopedBindings.get(env) ?? [];
|
|
500
|
+
const bindings = new Map();
|
|
501
|
+
scopes.push(bindings);
|
|
502
|
+
scopedBindings.set(env, scopes);
|
|
484
503
|
try {
|
|
485
504
|
evaluateStatements(statements, env, file);
|
|
486
505
|
}
|
|
487
506
|
finally {
|
|
488
|
-
|
|
489
|
-
|
|
507
|
+
scopes.pop();
|
|
508
|
+
for (const [name, previous] of bindings) {
|
|
509
|
+
if (previous.existed)
|
|
510
|
+
env.set(name, previous.value);
|
|
511
|
+
else
|
|
490
512
|
env.delete(name);
|
|
491
513
|
}
|
|
514
|
+
if (!scopes.length)
|
|
515
|
+
scopedBindings.delete(env);
|
|
492
516
|
}
|
|
493
517
|
}
|
|
494
518
|
function evalBracedIfExpression(node, env, file) {
|
|
@@ -539,6 +563,12 @@ function functionArgumentSource(expression, fallback) {
|
|
|
539
563
|
}
|
|
540
564
|
return expression.source ?? fallback;
|
|
541
565
|
}
|
|
566
|
+
function copyArrayTree(value) {
|
|
567
|
+
return Array.isArray(value) ? value.map(copyArrayTree) : value;
|
|
568
|
+
}
|
|
569
|
+
function isListParameter(type) {
|
|
570
|
+
return type.kind === 'list' || (type.kind === 'nullable' && type.element.kind === 'list');
|
|
571
|
+
}
|
|
542
572
|
function evalFunctionCall(node, env, file) {
|
|
543
573
|
const args = node.arguments.map(a => evaluateExpression(a, env, file));
|
|
544
574
|
const userFunction = env.functions.get(node.callee);
|
|
@@ -546,15 +576,37 @@ function evalFunctionCall(node, env, file) {
|
|
|
546
576
|
const functionRegistry = fieldRegistry(userFunction, env.dimensionRegistry);
|
|
547
577
|
const parameters = {};
|
|
548
578
|
userFunction.parameters.forEach((parameter, index) => {
|
|
549
|
-
|
|
550
|
-
|
|
579
|
+
const parameterType = checkedType(parameter.annotation, functionRegistry);
|
|
580
|
+
validateRuntimeValue(args[index], parameterType, env, node.arguments[index]?.source ?? node.source, file, `function ${node.callee}.${parameter.name}`);
|
|
581
|
+
const value = args[index];
|
|
582
|
+
parameters[parameter.name] = isListParameter(parameterType) && value !== null
|
|
583
|
+
? copyArrayTree(value)
|
|
584
|
+
: value;
|
|
551
585
|
});
|
|
552
586
|
const frame = env.createCallFrame(parameters);
|
|
553
587
|
frame.dimensionRegistry = functionRegistry;
|
|
554
588
|
userFunction.parameters.forEach(parameter => {
|
|
555
589
|
frame.bindingTypes.set(parameter.name, checkedType(parameter.annotation, functionRegistry));
|
|
556
590
|
});
|
|
557
|
-
|
|
591
|
+
let result;
|
|
592
|
+
const body = userFunction.body;
|
|
593
|
+
if (body.kind === 'expression') {
|
|
594
|
+
result = evaluateExpression(body.expression, frame, file);
|
|
595
|
+
}
|
|
596
|
+
else {
|
|
597
|
+
let returned = false;
|
|
598
|
+
try {
|
|
599
|
+
withDepth(functionReturnDepth, frame, () => evaluateStatements(body.statements, frame, file));
|
|
600
|
+
}
|
|
601
|
+
catch (error) {
|
|
602
|
+
if (!(error instanceof FunctionBodyReturn))
|
|
603
|
+
throw error;
|
|
604
|
+
returned = true;
|
|
605
|
+
result = error.value;
|
|
606
|
+
}
|
|
607
|
+
if (!returned)
|
|
608
|
+
throwFunctionFallthrough(body.closingSource, file);
|
|
609
|
+
}
|
|
558
610
|
validateRuntimeValue(result, checkedType(userFunction.returnType, functionRegistry), env, node.source, file, `function ${node.callee} return`);
|
|
559
611
|
return result;
|
|
560
612
|
}
|
|
@@ -899,6 +951,7 @@ function evaluateStatement(statement, env, file) {
|
|
|
899
951
|
return;
|
|
900
952
|
case 'variableDeclaration':
|
|
901
953
|
{
|
|
954
|
+
rememberScopedBinding(statement.name, env);
|
|
902
955
|
const value = evaluateExpression(statement.expression, env, file);
|
|
903
956
|
const type = env.bindingTypes.get(statement.name);
|
|
904
957
|
if (type)
|
|
@@ -947,6 +1000,9 @@ function evaluateStatement(statement, env, file) {
|
|
|
947
1000
|
if (forExpressionDepth.has(env)) {
|
|
948
1001
|
throw new ForExpressionReturn(evaluateExpression(statement.expression, env, file));
|
|
949
1002
|
}
|
|
1003
|
+
if (functionReturnDepth.has(env)) {
|
|
1004
|
+
throw new FunctionBodyReturn(evaluateExpression(statement.expression, env, file));
|
|
1005
|
+
}
|
|
950
1006
|
throwInvalidReturnContext(statement.source, file);
|
|
951
1007
|
}
|
|
952
1008
|
}
|
|
@@ -1023,7 +1079,12 @@ function evalRange(node, env, file) {
|
|
|
1023
1079
|
}
|
|
1024
1080
|
function evalForStatement(node, env, file) {
|
|
1025
1081
|
const values = evaluateLoopIterable(node.iterable, env, file);
|
|
1026
|
-
withLoopBinding(node.variable, values, env, () =>
|
|
1082
|
+
withLoopBinding(node.variable, values, env, () => {
|
|
1083
|
+
if (functionReturnDepth.has(env))
|
|
1084
|
+
evaluateScopedStatements(node.body, env, file);
|
|
1085
|
+
else
|
|
1086
|
+
evaluateStatements(node.body, env, file);
|
|
1087
|
+
});
|
|
1027
1088
|
}
|
|
1028
1089
|
function evalForExpression(node, env, file) {
|
|
1029
1090
|
const values = evaluateLoopIterable(node.iterable, env, file);
|
|
@@ -1097,6 +1097,60 @@ export function checkDocument(doc, file, context) {
|
|
|
1097
1097
|
fail('AMX3021', 'Every possible path in an if expression must return a value', closingSource ?? expressionSource);
|
|
1098
1098
|
return result;
|
|
1099
1099
|
}
|
|
1100
|
+
function checkFunctionSequence(statements, returnType) {
|
|
1101
|
+
let canFallThrough = true;
|
|
1102
|
+
for (const statement of statements) {
|
|
1103
|
+
const statementCanFallThrough = checkFunctionStatement(statement, returnType);
|
|
1104
|
+
if (canFallThrough)
|
|
1105
|
+
canFallThrough = statementCanFallThrough;
|
|
1106
|
+
}
|
|
1107
|
+
return canFallThrough;
|
|
1108
|
+
}
|
|
1109
|
+
function checkFunctionScopedSequence(statements, returnType) {
|
|
1110
|
+
const original = bindings;
|
|
1111
|
+
bindings = new Map(original);
|
|
1112
|
+
try {
|
|
1113
|
+
return checkFunctionSequence(statements, returnType);
|
|
1114
|
+
}
|
|
1115
|
+
finally {
|
|
1116
|
+
bindings = original;
|
|
1117
|
+
}
|
|
1118
|
+
}
|
|
1119
|
+
function checkFunctionStatement(statement, returnType) {
|
|
1120
|
+
switch (statement.type) {
|
|
1121
|
+
case 'returnStatement': {
|
|
1122
|
+
const actual = infer(statement.expression, returnType);
|
|
1123
|
+
requireType(actual, returnType, statement.expression.source ?? statement.source);
|
|
1124
|
+
return false;
|
|
1125
|
+
}
|
|
1126
|
+
case 'bracedIfStatement': {
|
|
1127
|
+
requireType(infer(statement.test), named('Boolean'), statement.test.source);
|
|
1128
|
+
const consequentCanFallThrough = checkFunctionScopedSequence(statement.consequent, returnType);
|
|
1129
|
+
if (!statement.alternate)
|
|
1130
|
+
return true;
|
|
1131
|
+
const alternateCanFallThrough = checkFunctionScopedSequence(statement.alternate, returnType);
|
|
1132
|
+
return consequentCanFallThrough || alternateCanFallThrough;
|
|
1133
|
+
}
|
|
1134
|
+
case 'forStatement': {
|
|
1135
|
+
const iterable = infer(statement.iterable);
|
|
1136
|
+
if (iterable.kind !== 'list')
|
|
1137
|
+
fail(iterable.kind === 'measurement' ? 'AMX3007' : 'AMX3003', 'For loop needs a list or range', statement.iterable.source ?? statement.source);
|
|
1138
|
+
const original = bindings;
|
|
1139
|
+
bindings = new Map(original);
|
|
1140
|
+
bindings.set(statement.variable, iterable.element);
|
|
1141
|
+
try {
|
|
1142
|
+
checkFunctionSequence(statement.body, returnType);
|
|
1143
|
+
}
|
|
1144
|
+
finally {
|
|
1145
|
+
bindings = original;
|
|
1146
|
+
}
|
|
1147
|
+
return true;
|
|
1148
|
+
}
|
|
1149
|
+
default:
|
|
1150
|
+
checkStatement(statement);
|
|
1151
|
+
return true;
|
|
1152
|
+
}
|
|
1153
|
+
}
|
|
1100
1154
|
function checkDefault(expression, target) {
|
|
1101
1155
|
if (expression.type === 'listLiteral') {
|
|
1102
1156
|
for (const item of expression.elements)
|
|
@@ -1568,13 +1622,23 @@ export function checkDocument(doc, file, context) {
|
|
|
1568
1622
|
paramScope.set(parameter.name, resolve(parameter.annotation));
|
|
1569
1623
|
}
|
|
1570
1624
|
const returnType = resolve(statement.returnType);
|
|
1571
|
-
if (bodyContainsForExpression(statement.body))
|
|
1572
|
-
fail('AMX3003', 'Function bodies cannot contain a for expression', statement.body.source ?? statement.source);
|
|
1573
1625
|
const outerBindings = bindings;
|
|
1574
1626
|
bindings = paramScope;
|
|
1575
1627
|
try {
|
|
1576
|
-
|
|
1577
|
-
|
|
1628
|
+
if (statement.body.kind === 'expression') {
|
|
1629
|
+
if (bodyContainsForExpression(statement.body.expression))
|
|
1630
|
+
fail('AMX3003', 'Function bodies cannot contain a for expression', statement.body.expression.source ?? statement.source);
|
|
1631
|
+
const actual = infer(statement.body.expression, returnType);
|
|
1632
|
+
requireType(actual, returnType, statement.body.expression.source ?? statement.source);
|
|
1633
|
+
}
|
|
1634
|
+
else {
|
|
1635
|
+
if (bodyContainsForStatements(statement.body.statements)) {
|
|
1636
|
+
fail('AMX3003', 'Function bodies cannot contain a for expression', statement.body.source ?? statement.source);
|
|
1637
|
+
}
|
|
1638
|
+
if (checkFunctionSequence(statement.body.statements, returnType)) {
|
|
1639
|
+
fail('AMXF4001', 'Missing return value from function', statement.body.closingSource);
|
|
1640
|
+
}
|
|
1641
|
+
}
|
|
1578
1642
|
}
|
|
1579
1643
|
finally {
|
|
1580
1644
|
bindings = outerBindings;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@nova-energy/openamx",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.16.0",
|
|
4
4
|
"description": "OpenAMX is an open-source, text-based, computable document format for engineering knowledge.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"bin": {
|
|
@@ -13,13 +13,13 @@
|
|
|
13
13
|
"dependencies": {
|
|
14
14
|
"cac": "^6.7.14",
|
|
15
15
|
"csv-parse": "^7.0.3",
|
|
16
|
-
"docx": "^9.
|
|
16
|
+
"docx": "^9.14.0",
|
|
17
17
|
"echarts": "6.1.0",
|
|
18
18
|
"marked": "^14.1.4",
|
|
19
19
|
"pdfmake": "0.3.11",
|
|
20
20
|
"sanitize-html": "2.17.0",
|
|
21
21
|
"sharp": "^0.35.5",
|
|
22
|
-
"yaml": "^2.9.
|
|
22
|
+
"yaml": "^2.9.1"
|
|
23
23
|
},
|
|
24
24
|
"engines": {
|
|
25
25
|
"bun": ">=1.0.0"
|