@nova-energy/openamx 0.0.0-stage → 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. package/COMMERCIAL-LICENSE.md +74 -0
  2. package/LICENSE.md +660 -0
  3. package/README.md +537 -3
  4. package/dist/ast/types.js +2 -0
  5. package/dist/cli.js +197 -0
  6. package/dist/diagnostics/errors.js +94 -0
  7. package/dist/editor/completion.js +313 -0
  8. package/dist/editor/highlighting.js +224 -0
  9. package/dist/editor/moduleAnalysis.js +206 -0
  10. package/dist/editor/refactoring.js +46 -0
  11. package/dist/editor/sourceRanges.js +50 -0
  12. package/dist/editor/symbols.js +203 -0
  13. package/dist/formatter/formatAmx.js +79 -0
  14. package/dist/index.js +10 -0
  15. package/dist/parser/parseDocument.js +114 -0
  16. package/dist/parser/parseExpression.js +768 -0
  17. package/dist/parser/parseFor.js +53 -0
  18. package/dist/parser/parseFrontMatter.js +65 -0
  19. package/dist/parser/parseStatements.js +667 -0
  20. package/dist/parser/stringScanner.js +71 -0
  21. package/dist/renderer/chartModel.js +476 -0
  22. package/dist/renderer/narrativeModel.js +561 -0
  23. package/dist/renderer/renderHtml.js +521 -0
  24. package/dist/renderer/reportDocx.js +725 -0
  25. package/dist/renderer/reportPaths.js +31 -0
  26. package/dist/renderer/reportPdf.js +314 -0
  27. package/dist/renderer/reportPreparation.js +196 -0
  28. package/dist/runtime/csvTextSerialization.js +8 -0
  29. package/dist/runtime/dataText.js +191 -0
  30. package/dist/runtime/docxDestination.js +55 -0
  31. package/dist/runtime/environment.js +105 -0
  32. package/dist/runtime/evaluateDocument.js +32 -0
  33. package/dist/runtime/evaluateExpression.js +888 -0
  34. package/dist/runtime/externalUnits.js +91 -0
  35. package/dist/runtime/inputData.js +508 -0
  36. package/dist/runtime/measurement.js +110 -0
  37. package/dist/runtime/moduleLoader.js +279 -0
  38. package/dist/runtime/outputData.js +303 -0
  39. package/dist/runtime/pdfDestination.js +57 -0
  40. package/dist/runtime/standardLibrary.js +145 -0
  41. package/dist/typechecker/checkDocument.js +1282 -0
  42. package/dist/typechecker/declarationRegistry.js +7 -0
  43. package/dist/typechecker/dimensionTypes.js +1 -0
  44. package/package.json +33 -4
@@ -0,0 +1,203 @@
1
+ import { declarationNameRange, sourceTokenRange } from "./sourceRanges";
2
+ function statementsOf(document) {
3
+ return document.nodes.flatMap(node => node.type === "executableCodeBlock" ? node.statements : []);
4
+ }
5
+ function typeText(type) {
6
+ if (type.kind === "named")
7
+ return type.name;
8
+ if (type.kind === "measurement")
9
+ return "measurement";
10
+ if (type.kind === "null")
11
+ return "null";
12
+ return `${typeText(type.element)}${type.kind === "list" ? "[]" : "?"}`;
13
+ }
14
+ function declaration(text, file, statement) {
15
+ if (!("name" in statement))
16
+ return undefined;
17
+ const range = declarationNameRange(text, statement);
18
+ if (!range)
19
+ return undefined;
20
+ const kind = statement.type === "variableDeclaration" ? "binding" : statement.type.replace("Declaration", "");
21
+ const detail = statement.type === "functionDeclaration"
22
+ ? `fn ${statement.name}(${statement.parameters.map(param => `${param.name}: ${param.annotation.name ?? param.annotation.type}`).join(", ")}): ${statement.returnType.name ?? statement.returnType.type}`
23
+ : statement.type === "variableDeclaration" || statement.type === "inputDeclaration"
24
+ ? `${kind} ${statement.name}${statement.annotation ? `: ${statement.annotation.name ?? statement.annotation.type}` : ""}`
25
+ : `${kind} ${statement.name}`;
26
+ return { ...range, file, name: statement.name, target: { file, ...range }, declaration: true, kind, detail };
27
+ }
28
+ function moduleRecord(analysis, file) {
29
+ return analysis?.modules?.get(file);
30
+ }
31
+ /** Build identity-bearing symbol occurrences; uncertain parser spans and duplicate declarations have no target. */
32
+ export function editorSymbolFacts(text, entryFile, entryDocument, analysis, moduleSources = new Map()) {
33
+ const documents = new Map();
34
+ if (analysis?.modules)
35
+ for (const [file, module] of analysis.modules)
36
+ documents.set(file, module.document);
37
+ documents.set(entryFile, entryDocument);
38
+ const result = [];
39
+ for (const [file, document] of documents) {
40
+ const moduleText = file === entryFile ? text : moduleSources.get(file);
41
+ if (moduleText === undefined)
42
+ continue;
43
+ const module = moduleRecord(analysis, file);
44
+ const statements = statementsOf(document);
45
+ const declarations = statements.filter(statement => "name" in statement && declarationNameRange(moduleText, statement));
46
+ const duplicates = new Set(declarations.filter((candidate, index) => declarations.some((other, otherIndex) => otherIndex !== index && "name" in other && "name" in candidate && other.name === candidate.name)).map(statement => "name" in statement ? statement.name : ""));
47
+ const visible = new Map();
48
+ const add = (source, name, target) => {
49
+ if (!target)
50
+ return;
51
+ const range = sourceTokenRange(moduleText, source, name);
52
+ if (range)
53
+ result.push({ ...target, ...range, file, declaration: false });
54
+ };
55
+ const expression = (node) => {
56
+ if (!analysis && statements.some(statement => statement.type === "importDeclaration"))
57
+ return;
58
+ switch (node.type) {
59
+ case "stringInterpolation":
60
+ node.parts.forEach(part => { if (typeof part !== "string")
61
+ expression(part); });
62
+ break;
63
+ case "identifier":
64
+ add(node.source, node.name, visible.get(node.name));
65
+ break;
66
+ case "functionCall":
67
+ add(node.source, node.callee, visible.get(node.callee));
68
+ node.arguments.forEach(expression);
69
+ break;
70
+ case "recordConstructor":
71
+ add(node.source, node.name, visible.get(node.name));
72
+ node.fields.forEach(field => expression(field.expression));
73
+ break;
74
+ case "binaryExpression":
75
+ expression(node.left);
76
+ expression(node.right);
77
+ break;
78
+ case "measurementAttachment":
79
+ case "measurementConversion":
80
+ add(node.unitSource, node.unit, visible.get(node.unit));
81
+ expression(node.value);
82
+ break;
83
+ case "unaryExpression":
84
+ expression(node.argument);
85
+ break;
86
+ case "conditionalExpression":
87
+ expression(node.test);
88
+ expression(node.consequent);
89
+ expression(node.alternate);
90
+ break;
91
+ case "listLiteral":
92
+ node.elements.forEach(expression);
93
+ break;
94
+ case "rangeExpression":
95
+ expression(node.start);
96
+ expression(node.end);
97
+ break;
98
+ case "matchExpression":
99
+ expression(node.expression);
100
+ node.cases.forEach(arm => expression(arm.expression));
101
+ expression(node.defaultExpression);
102
+ break;
103
+ case "fieldAccess":
104
+ expression(node.receiver);
105
+ break;
106
+ case "listAccess":
107
+ expression(node.receiver);
108
+ expression(node.index);
109
+ break;
110
+ case "forExpression":
111
+ expression(node.iterable);
112
+ break;
113
+ default: break;
114
+ }
115
+ };
116
+ for (const statement of statements) {
117
+ if (statement.type === "importDeclaration") {
118
+ for (const imported of statement.names) {
119
+ const targetFile = module?.importTargets.get(imported.name);
120
+ const targetModule = targetFile ? moduleRecord(analysis, targetFile) : undefined;
121
+ let targetStatement = targetModule && statementsOf(targetModule.document).find(candidate => "name" in candidate && candidate.name === imported.name && "exported" in candidate && candidate.exported);
122
+ let declarationFile = targetFile;
123
+ const targetMetadata = targetModule?.checkResult.exportedDimensions.get(imported.name)
124
+ ?? targetModule?.checkResult.exportedUnits.get(imported.name);
125
+ if (!targetStatement && targetMetadata) {
126
+ const originFile = targetMetadata.moduleIdentity;
127
+ declarationFile = originFile;
128
+ const originModule = moduleRecord(analysis, originFile);
129
+ targetStatement = originModule && statementsOf(originModule.document).find(candidate => (candidate.type === "dimensionDeclaration" || candidate.type === "unitDeclaration")
130
+ && candidate.name === targetMetadata.declarationName);
131
+ }
132
+ const targetText = declarationFile === entryFile ? text : declarationFile ? moduleSources.get(declarationFile) : undefined;
133
+ const importedTarget = targetStatement && targetText !== undefined ? declaration(targetText, declarationFile, targetStatement) : undefined;
134
+ if (importedTarget) {
135
+ const importedOccurrence = { ...importedTarget, origin: declarationFile };
136
+ visible.set(imported.name, importedOccurrence);
137
+ add(imported.source, imported.name, importedOccurrence);
138
+ }
139
+ }
140
+ }
141
+ else {
142
+ if (statement.type === "exportNamesDeclaration") {
143
+ for (const item of statement.names)
144
+ add(item.source, item.name, visible.get(item.name));
145
+ }
146
+ if (statement.type === "dimensionDeclaration" && statement.expression)
147
+ expression(statement.expression);
148
+ if (statement.type === "unitDeclaration") {
149
+ if (statement.dimension)
150
+ add(statement.dimensionSource, statement.dimension, visible.get(statement.dimension));
151
+ if (statement.expression)
152
+ expression(statement.expression);
153
+ }
154
+ if (statement.type === "variableDeclaration")
155
+ expression(statement.expression);
156
+ if (statement.type === "variableDeclaration" || statement.type === "inputDeclaration") {
157
+ const annotation = statement.annotation;
158
+ if (annotation?.type === "namedType" && annotation.name)
159
+ add(annotation.source, annotation.name, visible.get(annotation.name));
160
+ }
161
+ if (statement.type === "showStatement")
162
+ add(statement.nameSource, statement.name, visible.get(statement.name));
163
+ if (statement.type === "tableDeclaration" || statement.type === "chartDeclaration")
164
+ add(statement.bindingSource, statement.binding, visible.get(statement.binding));
165
+ if (statement.type === "assignmentStatement" || statement.type === "compoundAssignmentStatement") {
166
+ add(statement.source, statement.name, visible.get(statement.name));
167
+ expression(statement.expression);
168
+ }
169
+ if (statement.type === "addStatement") {
170
+ add(statement.targetSource, statement.name, visible.get(statement.name));
171
+ expression(statement.value);
172
+ if (statement.index)
173
+ expression(statement.index);
174
+ }
175
+ if (statement.type === "removeStatement") {
176
+ add(statement.targetSource, statement.name, visible.get(statement.name));
177
+ expression(statement.count);
178
+ if (statement.index)
179
+ expression(statement.index);
180
+ }
181
+ if (statement.type === "forStatement")
182
+ expression(statement.iterable);
183
+ const declared = declaration(moduleText, file, statement);
184
+ if (declared && "name" in statement && !duplicates.has(statement.name)) {
185
+ if (statement.type === "variableDeclaration") {
186
+ const inferred = module?.checkResult.bindingTypes.get(statement.name) ?? (file === entryFile ? analysis?.bindingTypes?.get(statement.name) : undefined);
187
+ if (inferred)
188
+ declared.detail = `binding ${statement.name}: ${typeText(inferred)}`;
189
+ }
190
+ visible.set(statement.name, declared);
191
+ result.push(declared);
192
+ if (statement.type === "typeDeclaration")
193
+ for (const field of statement.fields) {
194
+ const range = sourceTokenRange(moduleText, field.source, field.name);
195
+ if (range)
196
+ result.push({ ...range, file, name: field.name, target: { file, ...range }, declaration: true, kind: "field", detail: `field ${field.name}: ${field.annotation.name ?? field.annotation.type}` });
197
+ }
198
+ }
199
+ }
200
+ }
201
+ }
202
+ return result;
203
+ }
@@ -0,0 +1,79 @@
1
+ import { parseDocumentText } from '../parser/parseDocument';
2
+ import { parseStatements } from '../parser/parseStatements';
3
+ import { findStringLiteralEnd } from '../parser/stringScanner';
4
+ export function formatAmxDocument(source) {
5
+ const document = parseDocumentText(source);
6
+ const lineStarts = [0];
7
+ for (const newline of source.matchAll(/\n/g)) {
8
+ lineStarts.push(newline.index + 1);
9
+ }
10
+ const replacements = document.nodes.flatMap(node => {
11
+ if (node.type !== 'executableCodeBlock' || !node.source)
12
+ return [];
13
+ const start = lineStarts[node.source.line];
14
+ const opener = source.slice(lineStarts[node.source.line - 1], start);
15
+ const newline = node.content.match(/\r?\n/)?.[0] ?? (opener.endsWith('\r\n') ? '\r\n' : '\n');
16
+ const canonical = formatAmx(node.content);
17
+ const text = newline === '\r\n' ? canonical.replace(/\n/g, '\r\n') : canonical;
18
+ return [{ start, end: start + node.content.length, text }];
19
+ });
20
+ let formatted = source;
21
+ for (const replacement of replacements.reverse()) {
22
+ formatted = formatted.slice(0, replacement.start) + replacement.text + formatted.slice(replacement.end);
23
+ }
24
+ return formatted;
25
+ }
26
+ /** Format executable AMX block content without changing expression text. */
27
+ export function formatAmx(source) {
28
+ const normalized = source.replace(/\r\n?/g, '\n');
29
+ const lines = normalized.split('\n');
30
+ while (lines.length > 0 && lines[0].trim().length === 0)
31
+ lines.shift();
32
+ while (lines.length > 0 && lines[lines.length - 1].trim().length === 0)
33
+ lines.pop();
34
+ if (lines.length === 0)
35
+ return '';
36
+ parseStatements(lines.join('\n'));
37
+ let depth = 0;
38
+ const formatted = lines.map((rawLine) => {
39
+ const line = rawLine.replace(/[ \t]+$/, '');
40
+ if (line.trim().length === 0)
41
+ return '';
42
+ const content = line.trimStart();
43
+ const braces = scanBraces(content);
44
+ const lineDepth = Math.max(0, depth - braces.leadingClosures);
45
+ const result = `${' '.repeat(lineDepth)}${content}`;
46
+ depth = Math.max(0, depth + braces.opens - braces.closes);
47
+ return result;
48
+ });
49
+ return `${formatted.join('\n')}\n`;
50
+ }
51
+ function scanBraces(line) {
52
+ let opens = 0;
53
+ let closes = 0;
54
+ let leadingClosures = 0;
55
+ let leading = true;
56
+ for (let index = 0; index < line.length; index++) {
57
+ const character = line[index];
58
+ if (character === '"' || character === "'") {
59
+ leading = false;
60
+ const end = findStringLiteralEnd(line, index);
61
+ if (end !== undefined)
62
+ index = end;
63
+ }
64
+ else if (character === '{') {
65
+ leading = false;
66
+ opens++;
67
+ }
68
+ else if (character === '}') {
69
+ if (leading)
70
+ leadingClosures++;
71
+ closes++;
72
+ leading = false;
73
+ }
74
+ else if (!/\s/.test(character)) {
75
+ leading = false;
76
+ }
77
+ }
78
+ return { opens, closes, leadingClosures };
79
+ }
package/dist/index.js ADDED
@@ -0,0 +1,10 @@
1
+ /**
2
+ * OpenAMX public API entry point.
3
+ *
4
+ * This module will eventually re-export the main parser, evaluator,
5
+ * renderer, and CLI entry points.
6
+ *
7
+ * Currently a placeholder for Sprint 001 scaffolding.
8
+ */
9
+ // Placeholder export to ensure the module compiles
10
+ export const OPENAMX_VERSION = "0.1.0";
@@ -0,0 +1,114 @@
1
+ import { parseFrontMatter } from './parseFrontMatter';
2
+ import { parseStatements } from './parseStatements';
3
+ /**
4
+ * Parse an .amx document from disk.
5
+ *
6
+ * Steps (Sprint 002 scope):
7
+ * 1. Read UTF-8 text.
8
+ * 2. Extract optional YAML front matter (delegate to parseFrontMatter).
9
+ * 3. Preserve narrative and parse declarations only within exact `amx` fences.
10
+ * 4. Return OpenAmxDocument { metadata, nodes }.
11
+ *
12
+ * No evaluation or rendering is performed.
13
+ */
14
+ export async function parseDocument(filePath) {
15
+ const content = await Bun.file(filePath).text();
16
+ return parseDocumentText(content);
17
+ }
18
+ /** Parse an OpenAMX document from in-memory text without file-system access. */
19
+ export function parseDocumentText(content) {
20
+ const frontMatter = parseFrontMatter(content);
21
+ const { metadata, body, error } = frontMatter;
22
+ if (error) {
23
+ // Surface a clear error while still attempting to parse body (per frontmatter impl tolerance).
24
+ // For Sprint 002 we throw so tests can assert on malformed front matter.
25
+ throw new Error(error);
26
+ }
27
+ const nodes = parseDocumentBody(body, frontMatter.bodyStartLine);
28
+ return {
29
+ metadata,
30
+ nodes
31
+ };
32
+ }
33
+ function parseDocumentBody(body, startLine) {
34
+ const lines = sourceLines(body);
35
+ const nodes = [];
36
+ let narrativeStart = 0;
37
+ let index = 0;
38
+ function flushNarrative(end, startIndex) {
39
+ if (end <= narrativeStart)
40
+ return;
41
+ nodes.push({
42
+ type: 'narrative',
43
+ content: body.slice(narrativeStart, end),
44
+ source: { line: startLine + startIndex, column: 1 }
45
+ });
46
+ }
47
+ while (index < lines.length) {
48
+ const line = lines[index];
49
+ const opening = line.text.match(/^( {0,3})(`{3,}|~{3,})(.*)$/);
50
+ if (!opening) {
51
+ index++;
52
+ continue;
53
+ }
54
+ const fence = opening[2];
55
+ const isExecutable = fence[0] === '`' && opening[3].trim() === 'amx';
56
+ const closingIndex = findClosingFence(lines, index + 1, fence);
57
+ if (!isExecutable) {
58
+ index = closingIndex === -1 ? lines.length : closingIndex + 1;
59
+ continue;
60
+ }
61
+ const openerLocation = { line: startLine + index, column: opening[1].length + 1 };
62
+ if (closingIndex === -1) {
63
+ throw new Error(`Unclosed amx fence at ${openerLocation.line}:${openerLocation.column}`);
64
+ }
65
+ flushNarrative(line.start, index === 0 ? 0 : narrativeLineIndex(lines, narrativeStart));
66
+ const contentStart = line.nextStart;
67
+ const contentEnd = lines[closingIndex].start;
68
+ const content = body.slice(contentStart, contentEnd);
69
+ const statements = parseStatements(content, {
70
+ line: startLine + index + 1,
71
+ column: 1
72
+ });
73
+ nodes.push({
74
+ type: 'executableCodeBlock',
75
+ content,
76
+ statements,
77
+ source: openerLocation
78
+ });
79
+ index = closingIndex + 1;
80
+ narrativeStart = lines[closingIndex].nextStart;
81
+ }
82
+ if (narrativeStart < body.length) {
83
+ const narrativeStartLineIndex = narrativeLineIndex(lines, narrativeStart);
84
+ flushNarrative(body.length, narrativeStartLineIndex);
85
+ }
86
+ return nodes;
87
+ }
88
+ function sourceLines(text) {
89
+ const lines = [];
90
+ let start = 0;
91
+ while (start < text.length) {
92
+ const newline = text.indexOf('\n', start);
93
+ const nextStart = newline === -1 ? text.length : newline + 1;
94
+ const contentEnd = newline === -1
95
+ ? text.length
96
+ : newline > start && text[newline - 1] === '\r' ? newline - 1 : newline;
97
+ lines.push({ text: text.slice(start, contentEnd), start, contentEnd, nextStart });
98
+ start = nextStart;
99
+ }
100
+ return lines;
101
+ }
102
+ function findClosingFence(lines, from, opener) {
103
+ for (let i = from; i < lines.length; i++) {
104
+ const closing = lines[i].text.match(/^( {0,3})(`+|~+)(\s*)$/);
105
+ if (closing && closing[2][0] === opener[0] && closing[2].length >= opener.length) {
106
+ return i;
107
+ }
108
+ }
109
+ return -1;
110
+ }
111
+ function narrativeLineIndex(lines, offset) {
112
+ const index = lines.findIndex(line => line.start === offset);
113
+ return index === -1 ? Math.max(0, lines.length - 1) : index;
114
+ }