@nova-energy/openamx 0.15.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 CHANGED
@@ -21,10 +21,11 @@ not certified risk models or industry standards.
21
21
  results as JSON or CSV.
22
22
  - **Build visual explanations.** Create tables, charts, and formula-driven 2D
23
23
  diagrams alongside the narrative.
24
- - **Use the latest language additions.** V0.14 adds runtime type predicates,
25
- mathematical functions, text helpers, and bounded numeric formatting with
26
- `en-US`, `de-DE`, and `fr-FR` locales. Earlier additions include record
27
- inheritance, enums, and braced conditionals.
24
+ - **Use the latest language additions.** V0.16 adds statement-bodied
25
+ functions while preserving expression-bodied functions. V0.14 adds runtime
26
+ type predicates, mathematical functions, text helpers, and bounded numeric
27
+ formatting with `en-US`, `de-DE`, and `fr-FR` locales. Earlier additions
28
+ include record inheritance, enums, and braced conditionals.
28
29
  - **Publish reports in familiar formats.** Render standalone, offline HTML or
29
30
  export PDF and DOCX. Charts are interactive in HTML; PDF charts are static
30
31
  with their data retained in tables. DOCX charts are editable native charts
@@ -137,9 +138,9 @@ unified HTML/PDF/DOCX export workflow.
137
138
  - [Mapped data and validation](examples/06_Mapped_Data_and_Validation.amx)
138
139
  introduces explicit JSON/CSV input mappings.
139
140
  - [Complete asset screening report](examples/12_Complete_Asset_Screening_Report.amx)
140
- is the guided destination; [route measurements](examples/13_Route_Measurement_Report.amx)
141
- and the [battery-resistor circuit](examples/14_Battery_Resistor_Circuit.amx)
142
- are standalone references.
141
+ is the guided destination; [route measurements](examples/13_Route_Measurement_Report.amx),
142
+ the [battery-resistor circuit](examples/14_Battery_Resistor_Circuit.amx), and
143
+ [function bodies](examples/15_Function_Bodies.amx) are standalone references.
143
144
  - V0.12 features: [records and enums](examples/04_Typed_Records_Enums_and_Modules.amx)
144
145
  and [expressions and decisions](examples/02_Expressions_and_Decisions.amx).
145
146
  - V0.13 diagrams: [formula-driven diagrams](examples/08_Formula_Driven_Diagrams.amx)
@@ -152,7 +153,8 @@ Read the [V0.9 language specification](docs/language-spec-v0.9.md) and
152
153
  [V0.9 migration guide](docs/migrating-to-v0.9.md), then the additive
153
154
  [V0.12 language specification](docs/language-spec-v0.12.md),
154
155
  [V0.13 diagram specification](docs/language-spec-v0.13.md), and
155
- [V0.14 language specification](docs/language-spec-v0.14.md) for the current
156
+ [V0.14 language specification](docs/language-spec-v0.14.md) and
157
+ [V0.16 language specification](docs/language-spec-v0.16.md) for the current
156
158
  language contract. Browse the [examples](examples/) and [documentation](docs/). The
157
159
  [desktop guide](desktop-app/README.md) and
158
160
  [VS Code guide](vscode-extension/README.md) cover their respective tools.
@@ -89,6 +89,15 @@ export function throwInvalidReturnContext(source, file) {
89
89
  column: source?.column
90
90
  });
91
91
  }
92
+ export function throwFunctionFallthrough(source, file) {
93
+ throw new AmxError({
94
+ code: 'AMXF4002',
95
+ message: 'Function finished without returning a valid expression',
96
+ file,
97
+ line: source?.line,
98
+ column: source?.column
99
+ });
100
+ }
92
101
  export function throwListOperationError(message, source, file) {
93
102
  throw new AmxError({ code: 'AMX1008', message, file, line: source?.line, column: source?.column });
94
103
  }
@@ -127,6 +127,17 @@ function statementEndOffset(text, statement) {
127
127
  }
128
128
  return text.length;
129
129
  }
130
+ function expressionFunctionBodyBounds(text, fn) {
131
+ if (fn.body.kind !== "expression")
132
+ return undefined;
133
+ const start = sourceOffset(text, fn.source);
134
+ if (start === undefined)
135
+ return undefined;
136
+ const signature = text.slice(start).match(/^fn\s+[A-Za-z][A-Za-z0-9_]*\s*\([^)]*\)\s*:\s*[A-Za-z][A-Za-z0-9_]*(?:(?:\[\])|\?)*\s*=/);
137
+ if (!signature)
138
+ return undefined;
139
+ return { from: start + signature[0].length, to: statementEndOffset(text, fn) };
140
+ }
130
141
  function blockBounds(text, source) {
131
142
  const start = sourceOffset(text, source);
132
143
  if (start === undefined)
@@ -450,13 +461,97 @@ function visibleSymbols(text, parsed, cursorOffset, analysis) {
450
461
  collectExpression(expression.defaultExpression);
451
462
  };
452
463
  const collectRange = (expression) => { collectExpression(expression.start); collectExpression(expression.end); };
453
- for (const node of parsed.nodes) {
454
- if (node.type === "executableCodeBlock" && node.source && (sourceOffset(text, node.source) ?? Number.MAX_SAFE_INTEGER) < cursorOffset) {
455
- collectStatements(node.statements);
464
+ const functionDeclarations = statementsOf(parsed).filter((statement) => statement.type === "functionDeclaration");
465
+ const activeFunction = functionDeclarations.find(statement => {
466
+ if (statement.body.kind === "expression") {
467
+ const bounds = expressionFunctionBodyBounds(text, statement);
468
+ return !!bounds && cursorOffset >= bounds.from && cursorOffset <= bounds.to;
469
+ }
470
+ const opening = sourceOffset(text, statement.body.openingSource);
471
+ const closing = sourceOffset(text, statement.body.closingSource);
472
+ return opening !== undefined && closing !== undefined && cursorOffset > opening && cursorOffset <= closing;
473
+ });
474
+ if (activeFunction) {
475
+ const functionStart = sourceOffset(text, activeFunction.source) ?? Number.MAX_SAFE_INTEGER;
476
+ const moduleDeclarations = statementsOf(parsed).filter(statement => {
477
+ const start = sourceOffset(text, statement.source);
478
+ return start !== undefined && start < functionStart && [
479
+ "functionDeclaration", "typeDeclaration", "enumDeclaration", "dimensionDeclaration", "unitDeclaration"
480
+ ].includes(statement.type);
481
+ });
482
+ collectStatements(moduleDeclarations);
483
+ for (const imported of statementsOf(parsed).filter((statement) => statement.type === "importDeclaration" && (sourceOffset(text, statement.source) ?? Number.MAX_SAFE_INTEGER) < functionStart)) {
484
+ for (const item of imported.names) {
485
+ if (analysis?.importedTypes.has(item.name))
486
+ types.add(item.name);
487
+ if (analysis?.importedEnums.has(item.name)) {
488
+ types.add(item.name);
489
+ enums.set(item.name, analysis.importedEnums.get(item.name));
490
+ }
491
+ if (analysis?.importedFunctions.has(item.name))
492
+ functions.add(item.name);
493
+ }
494
+ }
495
+ const namedType = (type) => {
496
+ if (!type)
497
+ return undefined;
498
+ if (type.type === "namedType")
499
+ return type.name;
500
+ return namedType(type.element);
501
+ };
502
+ let functionScope = new Map(activeFunction.parameters.map(parameter => [parameter.name, namedType(parameter.annotation)]));
503
+ const collectFunctionScope = (statements, scope) => {
504
+ for (const statement of statements) {
505
+ const start = sourceOffset(text, statement.source);
506
+ if (start === undefined || start >= cursorOffset)
507
+ continue;
508
+ if (statement.type === "variableDeclaration") {
509
+ if (statementEndOffset(text, statement) <= cursorOffset) {
510
+ const inferred = namedType(statement.annotation)
511
+ ?? (statement.expression.type === "recordConstructor" ? statement.expression.name : undefined);
512
+ scope.set(statement.name, inferred);
513
+ }
514
+ }
515
+ else if (statement.type === "bracedIfStatement") {
516
+ if (insideIfBranch(text, statement, cursorOffset, false)) {
517
+ return collectFunctionScope(statement.consequent, new Map(scope));
518
+ }
519
+ if (statement.alternate && insideIfBranch(text, statement, cursorOffset, true)) {
520
+ return collectFunctionScope(statement.alternate, new Map(scope));
521
+ }
522
+ }
523
+ else if (statement.type === "forStatement") {
524
+ const bounds = loopBounds(text, statement);
525
+ if (bounds && cursorOffset > bounds.open && cursorOffset <= bounds.close) {
526
+ const loopScope = new Map(scope);
527
+ loopScope.set(statement.variable, undefined);
528
+ return collectFunctionScope(statement.body, loopScope);
529
+ }
530
+ }
531
+ }
532
+ return scope;
533
+ };
534
+ if (activeFunction.body.kind === "statements") {
535
+ functionScope = collectFunctionScope(activeFunction.body.statements, functionScope);
536
+ }
537
+ variables.clear();
538
+ localBindingTypes.clear();
539
+ for (const [name, typeName] of functionScope) {
540
+ variables.add(name);
541
+ if (typeName)
542
+ localBindingTypes.set(name, typeName);
543
+ }
544
+ }
545
+ else {
546
+ for (const node of parsed.nodes) {
547
+ if (node.type === "executableCodeBlock" && node.source && (sourceOffset(text, node.source) ?? Number.MAX_SAFE_INTEGER) < cursorOffset) {
548
+ collectStatements(node.statements);
549
+ }
456
550
  }
457
551
  }
458
- for (const iterator of activeIterators)
459
- variables.add(iterator);
552
+ if (!activeFunction)
553
+ for (const iterator of activeIterators)
554
+ variables.add(iterator);
460
555
  for (const [name, typeName] of localBindingTypes) {
461
556
  const declaration = localTypeDeclarations.get(typeName) ?? analysis?.importedTypes.get(typeName);
462
557
  if (declaration)
@@ -143,6 +143,18 @@ export function editorHighlightFacts(text, document) {
143
143
  if (node.element)
144
144
  typeReference(node.element);
145
145
  };
146
+ const loopVariable = (node) => {
147
+ const start = sourceOffset(text, node.source);
148
+ if (start === undefined)
149
+ return;
150
+ const lineEnd = text.indexOf("\n", start);
151
+ const header = text.slice(start, lineEnd < 0 ? text.length : lineEnd).replace(/\r$/, "");
152
+ const match = header.match(/^for\s+([A-Za-z][A-Za-z0-9_]*)\s+in\b/);
153
+ if (!match || match[1] !== node.variable)
154
+ return;
155
+ const from = start + match[0].indexOf(node.variable);
156
+ facts.push({ from, to: from + node.variable.length, kind: "declaration" });
157
+ };
146
158
  const statement = (node) => {
147
159
  const keyword = {
148
160
  variableDeclaration: "let", typeDeclaration: "type", enumDeclaration: "enum", functionDeclaration: "fn",
@@ -222,16 +234,26 @@ export function editorHighlightFacts(text, document) {
222
234
  expression(node.expression);
223
235
  }
224
236
  else if (node.type === "functionDeclaration") {
225
- node.parameters.forEach(param => typeReference(param.annotation));
237
+ node.parameters.forEach(param => {
238
+ const range = sourceTokenRange(text, param.source, param.name);
239
+ if (range)
240
+ facts.push({ ...range, kind: "declaration" });
241
+ typeReference(param.annotation);
242
+ });
226
243
  typeReference(node.returnType);
227
- expression(node.body);
244
+ if (node.body.kind === "expression")
245
+ expression(node.body.expression);
246
+ else
247
+ node.body.statements.forEach(statement);
228
248
  }
229
249
  else if (node.type === "tableDeclaration" || node.type === "chartDeclaration")
230
250
  add(node.bindingSource, node.binding, "reference");
231
251
  else if (node.type === "showStatement")
232
252
  add(node.nameSource, node.name, "reference");
233
- else if (node.type === "assignmentStatement" || node.type === "compoundAssignmentStatement")
253
+ else if (node.type === "assignmentStatement" || node.type === "compoundAssignmentStatement") {
254
+ add(node.source, node.name, "reference");
234
255
  expression(node.expression);
256
+ }
235
257
  else if (node.type === "addStatement") {
236
258
  add(node.targetSource, node.name, "reference");
237
259
  expression(node.value);
@@ -245,6 +267,7 @@ export function editorHighlightFacts(text, document) {
245
267
  expression(node.index);
246
268
  }
247
269
  else if (node.type === "forStatement") {
270
+ loopVariable(node);
248
271
  expression(node.iterable);
249
272
  node.body.forEach(statement);
250
273
  }
@@ -35,6 +35,18 @@ function enumMemberSource(text, source) {
35
35
  const whitespace = text.slice(dot + 1).match(/^\s*/)?.[0].length ?? 0;
36
36
  return { line: source.line, column: source.column + 1 + whitespace };
37
37
  }
38
+ function loopVariableRange(text, loop) {
39
+ const start = sourceOffset(text, loop.source);
40
+ if (start === undefined)
41
+ return undefined;
42
+ const lineEnd = text.indexOf("\n", start);
43
+ const header = text.slice(start, lineEnd < 0 ? text.length : lineEnd).replace(/\r$/, "");
44
+ const match = header.match(/^for\s+([A-Za-z][A-Za-z0-9_]*)\s+in\b/);
45
+ if (!match || match[1] !== loop.variable)
46
+ return undefined;
47
+ const from = start + match[0].indexOf(loop.variable);
48
+ return { from, to: from + loop.variable.length };
49
+ }
38
50
  /** Build identity-bearing symbol occurrences; uncertain parser spans and duplicate declarations have no target. */
39
51
  export function editorSymbolFacts(text, entryFile, entryDocument, analysis, moduleSources = new Map()) {
40
52
  const documents = new Map();
@@ -342,8 +354,116 @@ export function editorSymbolFacts(text, entryFile, entryDocument, analysis, modu
342
354
  statement.consequent.forEach(item => nestedStatement(item));
343
355
  statement.alternate?.forEach(item => nestedStatement(item));
344
356
  }
345
- if (statement.type === "functionDeclaration")
346
- expression(statement.body);
357
+ if (statement.type === "functionDeclaration") {
358
+ const functionDeclaration = declaration(moduleText, file, statement);
359
+ const functionParent = functionDeclaration && !duplicates.has(statement.name) ? functionDeclaration.target : undefined;
360
+ const functionScope = new Map([...visible].filter(([, fact]) => !["binding", "input", "table", "chart", "diagram"].includes(fact.kind)));
361
+ const declarationsInScope = new Set();
362
+ for (const parameter of statement.parameters) {
363
+ typeReference(parameter.annotation, visible);
364
+ const range = sourceTokenRange(moduleText, parameter.source, parameter.name);
365
+ if (!range || !functionParent)
366
+ continue;
367
+ const parameterFact = {
368
+ ...range,
369
+ file,
370
+ name: parameter.name,
371
+ target: { file, ...range },
372
+ parent: functionParent,
373
+ declaration: true,
374
+ kind: "parameter",
375
+ detail: `parameter ${parameter.name}: ${parameter.annotation.name ?? parameter.annotation.type}`
376
+ };
377
+ result.push(parameterFact);
378
+ functionScope.set(parameter.name, parameterFact);
379
+ declarationsInScope.add(parameter.name);
380
+ }
381
+ typeReference(statement.returnType, visible);
382
+ const walkFunctionStatements = (items, scope, declared) => {
383
+ for (const item of items) {
384
+ if (item.type === "variableDeclaration") {
385
+ expression(item.expression, scope);
386
+ if (item.annotation)
387
+ typeReference(item.annotation, visible);
388
+ const range = declarationNameRange(moduleText, item);
389
+ if (!range)
390
+ continue;
391
+ const existing = declared.has(item.name) ? scope.get(item.name) : undefined;
392
+ if (existing) {
393
+ result.push({ ...existing, ...range, file, declaration: false });
394
+ continue;
395
+ }
396
+ if (!functionParent)
397
+ continue;
398
+ const localFact = {
399
+ ...range,
400
+ file,
401
+ name: item.name,
402
+ target: { file, ...range },
403
+ parent: functionParent,
404
+ declaration: true,
405
+ kind: "binding",
406
+ detail: `binding ${item.name}${item.annotation ? `: ${item.annotation.name ?? item.annotation.type}` : ""}`
407
+ };
408
+ result.push(localFact);
409
+ scope.set(item.name, localFact);
410
+ declared.add(item.name);
411
+ }
412
+ else if (item.type === "assignmentStatement" || item.type === "compoundAssignmentStatement") {
413
+ add(item.source, item.name, scope.get(item.name));
414
+ expression(item.expression, scope);
415
+ }
416
+ else if (item.type === "addStatement") {
417
+ add(item.targetSource, item.name, scope.get(item.name));
418
+ expression(item.value, scope);
419
+ if (item.index)
420
+ expression(item.index, scope);
421
+ }
422
+ else if (item.type === "removeStatement") {
423
+ add(item.targetSource, item.name, scope.get(item.name));
424
+ expression(item.count, scope);
425
+ if (item.index)
426
+ expression(item.index, scope);
427
+ }
428
+ else if (item.type === "forStatement") {
429
+ expression(item.iterable, scope);
430
+ const loopScope = new Map(scope);
431
+ const loopDeclared = new Set();
432
+ const range = loopVariableRange(moduleText, item);
433
+ if (range && functionParent) {
434
+ const iteratorFact = {
435
+ ...range,
436
+ file,
437
+ name: item.variable,
438
+ target: { file, ...range },
439
+ parent: functionParent,
440
+ declaration: true,
441
+ kind: "iterator",
442
+ detail: `loop variable ${item.variable}`
443
+ };
444
+ result.push(iteratorFact);
445
+ loopScope.set(item.variable, iteratorFact);
446
+ loopDeclared.add(item.variable);
447
+ }
448
+ walkFunctionStatements(item.body, loopScope, loopDeclared);
449
+ }
450
+ else if (item.type === "bracedIfStatement") {
451
+ expression(item.test, scope);
452
+ walkFunctionStatements(item.consequent, new Map(scope), new Set());
453
+ if (item.alternate)
454
+ walkFunctionStatements(item.alternate, new Map(scope), new Set());
455
+ }
456
+ else if (item.type === "returnStatement")
457
+ expression(item.expression, scope);
458
+ else
459
+ nestedStatement(item, scope);
460
+ }
461
+ };
462
+ if (statement.body.kind === "expression")
463
+ expression(statement.body.expression, functionScope);
464
+ else
465
+ walkFunctionStatements(statement.body.statements, functionScope, declarationsInScope);
466
+ }
347
467
  const declared = declaration(moduleText, file, statement);
348
468
  if (declared && "name" in statement && !duplicates.has(statement.name)) {
349
469
  if (statement.type === "variableDeclaration") {
@@ -137,11 +137,11 @@ function scanBraces(line) {
137
137
  if (end !== undefined)
138
138
  index = end;
139
139
  }
140
- else if (character === '{') {
140
+ else if (character === '{' || character === '[') {
141
141
  leading = false;
142
142
  opens++;
143
143
  }
144
- else if (character === '}') {
144
+ else if (character === '}' || character === ']') {
145
145
  if (leading)
146
146
  leadingClosures++;
147
147
  closes++;
@@ -19,12 +19,9 @@ function parseLoop(text, source) {
19
19
  bodySource: { line: (source?.line ?? 1) + 1, column: 1 }
20
20
  };
21
21
  }
22
- export function parseForStatement(text, source) {
22
+ export function parseForStatement(text, source, context = {}) {
23
23
  const loop = parseLoop(text, source);
24
- if (/^\s*return\b/m.test(loop.bodyText)) {
25
- throw new Error(`Statement-form for loops cannot contain return at ${source?.line ?? 1}:${source?.column ?? 1}`);
26
- }
27
- const body = parseStatements(loop.bodyText, loop.bodySource, { allowFor: false });
24
+ const body = parseStatements(loop.bodyText, loop.bodySource, { ...context, allowFor: false });
28
25
  return {
29
26
  type: 'forStatement',
30
27
  variable: loop.variable,
@@ -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++) {
@@ -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 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;
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
- else if (ch === '}')
730
- depth--;
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
- return index;
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*=\s*([\s\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, 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
- }
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 paramsRaw.split(',')) {
764
- const paramMatch = part.trim().match(/^([A-Za-z][A-Za-z0-9_]*)\s*:\s*([A-Za-z][A-Za-z0-9_]*(?:(?:\[\])|\?)*)$/);
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
- parameters.push({ name: paramMatch[1], annotation: parseTypeReference(paramMatch[2], source), source });
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 bodyTrimmed = bodyText.trim();
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
- try {
775
- body = parseExpression(bodyTrimmed, source);
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
- 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}`);
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 existing = new Set(Object.keys(env.toObject()));
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
- for (const name of Object.keys(env.toObject())) {
489
- if (!existing.has(name))
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
- validateRuntimeValue(args[index], checkedType(parameter.annotation, functionRegistry), env, node.arguments[index]?.source ?? node.source, file, `function ${node.callee}.${parameter.name}`);
550
- parameters[parameter.name] = args[index];
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
- const result = evaluateExpression(userFunction.body, frame, file);
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, () => evaluateStatements(node.body, env, file));
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
- const actual = infer(statement.body, returnType);
1577
- requireType(actual, returnType, statement.body.source ?? statement.source);
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.15.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.8.1",
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.0"
22
+ "yaml": "^2.9.1"
23
23
  },
24
24
  "engines": {
25
25
  "bun": ">=1.0.0"