@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.
@@ -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,