@nova-energy/openamx 0.0.0-stage → 0.10.1
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/COMMERCIAL-LICENSE.md +74 -0
- package/LICENSE.md +660 -0
- package/README.md +513 -2
- package/dist/ast/types.js +2 -0
- package/dist/cli.js +186 -0
- package/dist/diagnostics/errors.js +94 -0
- package/dist/editor/completion.js +313 -0
- package/dist/editor/highlighting.js +224 -0
- package/dist/editor/moduleAnalysis.js +206 -0
- package/dist/editor/refactoring.js +46 -0
- package/dist/editor/sourceRanges.js +50 -0
- package/dist/editor/symbols.js +203 -0
- package/dist/formatter/formatAmx.js +79 -0
- package/dist/index.js +10 -0
- package/dist/parser/parseDocument.js +114 -0
- package/dist/parser/parseExpression.js +768 -0
- package/dist/parser/parseFor.js +53 -0
- package/dist/parser/parseFrontMatter.js +65 -0
- package/dist/parser/parseStatements.js +667 -0
- package/dist/parser/stringScanner.js +71 -0
- package/dist/renderer/chartModel.js +476 -0
- package/dist/renderer/renderHtml.js +383 -0
- package/dist/renderer/reportDocx.js +163 -0
- package/dist/renderer/reportPdf.js +202 -0
- package/dist/renderer/reportPreparation.js +208 -0
- package/dist/runtime/csvTextSerialization.js +8 -0
- package/dist/runtime/dataText.js +191 -0
- package/dist/runtime/docxDestination.js +55 -0
- package/dist/runtime/environment.js +105 -0
- package/dist/runtime/evaluateDocument.js +32 -0
- package/dist/runtime/evaluateExpression.js +888 -0
- package/dist/runtime/externalUnits.js +91 -0
- package/dist/runtime/inputData.js +508 -0
- package/dist/runtime/measurement.js +110 -0
- package/dist/runtime/moduleLoader.js +279 -0
- package/dist/runtime/outputData.js +303 -0
- package/dist/runtime/pdfDestination.js +57 -0
- package/dist/runtime/standardLibrary.js +145 -0
- package/dist/typechecker/checkDocument.js +1282 -0
- package/dist/typechecker/declarationRegistry.js +7 -0
- package/dist/typechecker/dimensionTypes.js +1 -0
- package/package.json +33 -4
package/dist/cli.js
ADDED
|
@@ -0,0 +1,186 @@
|
|
|
1
|
+
#!/usr/bin/env bun
|
|
2
|
+
/**
|
|
3
|
+
* OpenAMX CLI entry point (Sprint 006).
|
|
4
|
+
*
|
|
5
|
+
* Implements `render <input> [--out <path>]` and `run <input>` using the
|
|
6
|
+
* existing parseDocument / evaluateDocument / renderHtml pipeline.
|
|
7
|
+
* Errors (including AMX1004 with location) are printed to stderr and cause
|
|
8
|
+
* non-zero exit. No changes to parser, runtime, renderer, AST, or diagnostics.
|
|
9
|
+
*/
|
|
10
|
+
import { cac } from "cac";
|
|
11
|
+
import { readFileSync } from "node:fs";
|
|
12
|
+
import { basename, relative, resolve, sep } from "node:path";
|
|
13
|
+
import { renderPreparedHtml } from "./renderer/renderHtml";
|
|
14
|
+
import { AmxError } from "./diagnostics/errors";
|
|
15
|
+
import { loadEntryModule } from "./runtime/moduleLoader";
|
|
16
|
+
import { serializeOutputs, writeOutputs } from "./runtime/outputData";
|
|
17
|
+
import { preparePdfReport, serializePdfReport } from "./renderer/reportPdf";
|
|
18
|
+
import { preparePdfDestination, writePdfAtomically } from "./runtime/pdfDestination";
|
|
19
|
+
import { prepareDocxReport, serializeDocxReport } from "./renderer/reportDocx";
|
|
20
|
+
import { prepareDocxDestination, writeDocxAtomically } from "./runtime/docxDestination";
|
|
21
|
+
import { prepareReport } from "./renderer/reportPreparation";
|
|
22
|
+
const cli = cac("openamx");
|
|
23
|
+
function suppliedMappings(options, name) {
|
|
24
|
+
const option = `--${name}`;
|
|
25
|
+
const supplied = process.argv.some(argument => argument === option || argument.startsWith(`${option}=`));
|
|
26
|
+
return supplied ? options[name] : undefined;
|
|
27
|
+
}
|
|
28
|
+
function reportAmxError(error) {
|
|
29
|
+
const diagnostics = error.diagnostics ?? [{
|
|
30
|
+
code: error.code, message: error.message, file: error.file, line: error.line, column: error.column
|
|
31
|
+
}];
|
|
32
|
+
for (const diagnostic of diagnostics) {
|
|
33
|
+
console.error(`${diagnostic.code}: ${displayDiagnosticMessage(diagnostic)}`);
|
|
34
|
+
if (diagnostic.file)
|
|
35
|
+
console.error(`File: ${displayDiagnosticPath(diagnostic.file)}`);
|
|
36
|
+
if (diagnostic.line !== undefined)
|
|
37
|
+
console.error(`Line: ${diagnostic.line}`);
|
|
38
|
+
if (diagnostic.column !== undefined)
|
|
39
|
+
console.error(`Column: ${diagnostic.column}`);
|
|
40
|
+
if (diagnostic.inputName)
|
|
41
|
+
console.error(`Input: ${diagnostic.inputName}`);
|
|
42
|
+
if (diagnostic.dataPath !== undefined)
|
|
43
|
+
console.error(`Data: ${diagnostic.dataPath || '/'}`);
|
|
44
|
+
if (diagnostic.dataLine !== undefined)
|
|
45
|
+
console.error(`Data line: ${diagnostic.dataLine}`);
|
|
46
|
+
if (diagnostic.dataColumn !== undefined)
|
|
47
|
+
console.error(`Data column: ${diagnostic.dataColumn}`);
|
|
48
|
+
if (diagnostic.recordNumber !== undefined)
|
|
49
|
+
console.error(`Record: ${diagnostic.recordNumber}`);
|
|
50
|
+
if (diagnostic.expected)
|
|
51
|
+
console.error(`Expected: ${diagnostic.expected}`);
|
|
52
|
+
if (diagnostic.actual)
|
|
53
|
+
console.error(`Actual: ${diagnostic.actual}`);
|
|
54
|
+
if (diagnostic.declarationSource) {
|
|
55
|
+
console.error(`Input declaration: ${diagnostic.declarationSource.line}:${diagnostic.declarationSource.column}`);
|
|
56
|
+
}
|
|
57
|
+
if (diagnostic.fieldSource) {
|
|
58
|
+
console.error(`Field declaration: ${diagnostic.fieldSource.line}:${diagnostic.fieldSource.column}`);
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
function displayDiagnosticMessage(diagnostic) {
|
|
63
|
+
let message = diagnostic.message;
|
|
64
|
+
for (const file of [diagnostic.file, diagnostic.dataFile]) {
|
|
65
|
+
if (file)
|
|
66
|
+
message = message.replaceAll(file, displayDiagnosticPath(file));
|
|
67
|
+
}
|
|
68
|
+
return message.replace(/(['"])((?:[A-Za-z]:[\\/]|\/)[^'"]*)\1/g, (_match, quote, file) => `${quote}${displayDiagnosticPath(file)}${quote}`);
|
|
69
|
+
}
|
|
70
|
+
function displayDiagnosticPath(file) {
|
|
71
|
+
const absolute = resolve(file);
|
|
72
|
+
const fromWorkingDirectory = relative(process.cwd(), absolute);
|
|
73
|
+
if (fromWorkingDirectory && fromWorkingDirectory !== '..' && !fromWorkingDirectory.startsWith(`..${sep}`)) {
|
|
74
|
+
return fromWorkingDirectory;
|
|
75
|
+
}
|
|
76
|
+
return basename(absolute);
|
|
77
|
+
}
|
|
78
|
+
cli
|
|
79
|
+
.command("export <format> <input>", "Export an .amx file to an offline report")
|
|
80
|
+
.option("--out <path>", "Output PDF or DOCX file path")
|
|
81
|
+
.option("--input <mapping>", "Map a logical input to a data file", { type: [String] })
|
|
82
|
+
.option("--validation <mode>", "Validation mode: aggregate or fail-fast")
|
|
83
|
+
.option("--project-root <path>", "Project root for report metadata and logo assets")
|
|
84
|
+
.action(async (format, input, options) => {
|
|
85
|
+
try {
|
|
86
|
+
const inputMappings = suppliedMappings(options, "input");
|
|
87
|
+
if (format === "docx") {
|
|
88
|
+
const destination = await prepareDocxDestination(options.out, input, inputMappings);
|
|
89
|
+
const { doc, env } = await loadEntryModule(input, {
|
|
90
|
+
inputMappings,
|
|
91
|
+
validation: options.validation
|
|
92
|
+
});
|
|
93
|
+
const report = await prepareReport(doc, env, { file: input, projectRoot: options.projectRoot });
|
|
94
|
+
const bytes = await serializeDocxReport(prepareDocxReport(report));
|
|
95
|
+
await writeDocxAtomically(destination, bytes);
|
|
96
|
+
console.log(`Exported DOCX to ${destination.path}`);
|
|
97
|
+
return;
|
|
98
|
+
}
|
|
99
|
+
if (format !== "pdf")
|
|
100
|
+
throw new AmxError({ code: "AMX6001", message: `Unsupported export format '${format}'; use 'pdf' or 'docx'` });
|
|
101
|
+
const destination = await preparePdfDestination(options.out, input, inputMappings);
|
|
102
|
+
const { doc, env } = await loadEntryModule(input, {
|
|
103
|
+
inputMappings,
|
|
104
|
+
validation: options.validation
|
|
105
|
+
});
|
|
106
|
+
const report = await prepareReport(doc, env, { file: input, projectRoot: options.projectRoot });
|
|
107
|
+
const bytes = await serializePdfReport(preparePdfReport(report));
|
|
108
|
+
await writePdfAtomically(destination, bytes);
|
|
109
|
+
console.log(`Exported PDF to ${destination.path}`);
|
|
110
|
+
}
|
|
111
|
+
catch (err) {
|
|
112
|
+
if (err instanceof AmxError) {
|
|
113
|
+
reportAmxError(err);
|
|
114
|
+
}
|
|
115
|
+
else {
|
|
116
|
+
reportAmxError(new AmxError({ code: "AMX6002", message: `PDF export failed: ${err instanceof Error ? err.message : String(err)}` }));
|
|
117
|
+
}
|
|
118
|
+
process.exit(1);
|
|
119
|
+
}
|
|
120
|
+
});
|
|
121
|
+
cli
|
|
122
|
+
.command("render <input>", "Render an .amx file to standalone HTML")
|
|
123
|
+
.option("--out <path>", "Output HTML file path (default: input with .html extension)")
|
|
124
|
+
.option("--input <mapping>", "Map a logical input to a data file", { type: [String] })
|
|
125
|
+
.option("--output <mapping>", "Write an exported value to a JSON or CSV file", { type: [String] })
|
|
126
|
+
.option("--validation <mode>", "Validation mode: aggregate or fail-fast")
|
|
127
|
+
.option("--project-root <path>", "Project root for report metadata and logo assets")
|
|
128
|
+
.action(async (input, options) => {
|
|
129
|
+
try {
|
|
130
|
+
const outPath = options.out || input.replace(/\.amx$/, ".html");
|
|
131
|
+
const inputMappings = suppliedMappings(options, "input");
|
|
132
|
+
const outputMappings = suppliedMappings(options, "output");
|
|
133
|
+
const { doc, env, outputs } = await loadEntryModule(input, {
|
|
134
|
+
inputMappings,
|
|
135
|
+
validation: options.validation,
|
|
136
|
+
outputMappings,
|
|
137
|
+
reservedOutputPath: outputMappings?.length ? outPath : undefined
|
|
138
|
+
});
|
|
139
|
+
const report = await prepareReport(doc, env, { file: input, projectRoot: options.projectRoot });
|
|
140
|
+
const html = renderPreparedHtml(report);
|
|
141
|
+
const serialized = serializeOutputs(outputs, env);
|
|
142
|
+
await writeOutputs([{ path: outPath, contents: html }, ...serialized]);
|
|
143
|
+
console.log(`Rendered to ${outPath}`);
|
|
144
|
+
}
|
|
145
|
+
catch (err) {
|
|
146
|
+
if (err instanceof AmxError) {
|
|
147
|
+
reportAmxError(err);
|
|
148
|
+
}
|
|
149
|
+
else {
|
|
150
|
+
console.error("Error:", err.message);
|
|
151
|
+
}
|
|
152
|
+
process.exit(1);
|
|
153
|
+
}
|
|
154
|
+
});
|
|
155
|
+
cli
|
|
156
|
+
.command("run <input>", "Run an .amx file and print evaluated context as JSON")
|
|
157
|
+
.option("--input <mapping>", "Map a logical input to a data file", { type: [String] })
|
|
158
|
+
.option("--output <mapping>", "Write an exported value to a JSON or CSV file", { type: [String] })
|
|
159
|
+
.option("--validation <mode>", "Validation mode: aggregate or fail-fast")
|
|
160
|
+
.action(async (input, options) => {
|
|
161
|
+
try {
|
|
162
|
+
const inputMappings = suppliedMappings(options, "input");
|
|
163
|
+
const outputMappings = suppliedMappings(options, "output");
|
|
164
|
+
const { env, outputs } = await loadEntryModule(input, {
|
|
165
|
+
inputMappings,
|
|
166
|
+
validation: options.validation,
|
|
167
|
+
outputMappings
|
|
168
|
+
});
|
|
169
|
+
const serialized = serializeOutputs(outputs, env);
|
|
170
|
+
await writeOutputs(serialized);
|
|
171
|
+
console.log(JSON.stringify(env.toObject(), null, 2));
|
|
172
|
+
}
|
|
173
|
+
catch (err) {
|
|
174
|
+
if (err instanceof AmxError) {
|
|
175
|
+
reportAmxError(err);
|
|
176
|
+
}
|
|
177
|
+
else {
|
|
178
|
+
console.error("Error:", err.message);
|
|
179
|
+
}
|
|
180
|
+
process.exit(1);
|
|
181
|
+
}
|
|
182
|
+
});
|
|
183
|
+
cli.help();
|
|
184
|
+
// src/ and dist/ both sit one level below the package manifest.
|
|
185
|
+
cli.version(JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8")).version);
|
|
186
|
+
cli.parse();
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Error subclass carrying AmxDiagnostic information.
|
|
3
|
+
*/
|
|
4
|
+
export class AmxError extends Error {
|
|
5
|
+
code;
|
|
6
|
+
file;
|
|
7
|
+
line;
|
|
8
|
+
column;
|
|
9
|
+
declarationSource;
|
|
10
|
+
fieldSource;
|
|
11
|
+
diagnostics;
|
|
12
|
+
constructor(diag, diagnostics) {
|
|
13
|
+
super(diag.message);
|
|
14
|
+
this.name = 'AmxError';
|
|
15
|
+
this.code = diag.code;
|
|
16
|
+
this.file = diag.file;
|
|
17
|
+
this.line = diag.line;
|
|
18
|
+
this.column = diag.column;
|
|
19
|
+
this.declarationSource = diag.declarationSource;
|
|
20
|
+
this.fieldSource = diag.fieldSource;
|
|
21
|
+
this.diagnostics = diagnostics;
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
export function inputError(code, message, context = {}) {
|
|
25
|
+
return { code, message, ...context };
|
|
26
|
+
}
|
|
27
|
+
export function throwInputErrors(diagnostics) {
|
|
28
|
+
const first = diagnostics[0] ?? inputError('AMX4001', 'Input validation failed');
|
|
29
|
+
throw new AmxError(first, diagnostics);
|
|
30
|
+
}
|
|
31
|
+
export function staticError(code, message, source, file, declarationSource) {
|
|
32
|
+
throw new AmxError({ code, message, file, line: source?.line, column: source?.column, declarationSource });
|
|
33
|
+
}
|
|
34
|
+
export function throwMeasurementDomainError(message, source, file) {
|
|
35
|
+
throw new AmxError({ code: 'AMX1009', message, file, line: source?.line, column: source?.column });
|
|
36
|
+
}
|
|
37
|
+
export function syntaxError(message, source, file) {
|
|
38
|
+
throw new AmxError({ code: 'AMX3006', message, file, line: source?.line, column: source?.column });
|
|
39
|
+
}
|
|
40
|
+
export function moduleError(code, message, source, file) {
|
|
41
|
+
throw new AmxError({ code, message, file, line: source?.line, column: source?.column });
|
|
42
|
+
}
|
|
43
|
+
export function outputError(code, message) {
|
|
44
|
+
throw new AmxError({ code, message });
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* Create an AMX1004 undefined identifier diagnostic.
|
|
48
|
+
*/
|
|
49
|
+
export function createUndefinedIdentifierDiagnostic(name, source, file) {
|
|
50
|
+
return {
|
|
51
|
+
code: 'AMX1004',
|
|
52
|
+
message: `Undefined identifier '${name}'`,
|
|
53
|
+
file,
|
|
54
|
+
line: source?.line,
|
|
55
|
+
column: source?.column
|
|
56
|
+
};
|
|
57
|
+
}
|
|
58
|
+
/**
|
|
59
|
+
* Throw an AMX1004 error for an undefined identifier.
|
|
60
|
+
*/
|
|
61
|
+
export function throwUndefinedIdentifier(name, source, file) {
|
|
62
|
+
const diag = createUndefinedIdentifierDiagnostic(name, source, file);
|
|
63
|
+
throw new AmxError(diag);
|
|
64
|
+
}
|
|
65
|
+
export function throwInvalidRangeBounds(source, file) {
|
|
66
|
+
throw new AmxError({
|
|
67
|
+
code: 'AMX1005',
|
|
68
|
+
message: 'Range bounds must be finite integers',
|
|
69
|
+
file,
|
|
70
|
+
line: source?.line,
|
|
71
|
+
column: source?.column
|
|
72
|
+
});
|
|
73
|
+
}
|
|
74
|
+
export function throwInvalidLoopIterable(source, file) {
|
|
75
|
+
throw new AmxError({
|
|
76
|
+
code: 'AMX1006',
|
|
77
|
+
message: 'For loops require a list or range value',
|
|
78
|
+
file,
|
|
79
|
+
line: source?.line,
|
|
80
|
+
column: source?.column
|
|
81
|
+
});
|
|
82
|
+
}
|
|
83
|
+
export function throwInvalidReturnContext(source, file) {
|
|
84
|
+
throw new AmxError({
|
|
85
|
+
code: 'AMX1007',
|
|
86
|
+
message: 'Return is only valid inside an expression-form for loop',
|
|
87
|
+
file,
|
|
88
|
+
line: source?.line,
|
|
89
|
+
column: source?.column
|
|
90
|
+
});
|
|
91
|
+
}
|
|
92
|
+
export function throwListOperationError(message, source, file) {
|
|
93
|
+
throw new AmxError({ code: 'AMX1008', message, file, line: source?.line, column: source?.column });
|
|
94
|
+
}
|
|
@@ -0,0 +1,313 @@
|
|
|
1
|
+
import { parseDocumentText } from "../parser/parseDocument";
|
|
2
|
+
import { parseFrontMatter } from "../parser/parseFrontMatter";
|
|
3
|
+
import { isExecutableBlockOffset } from "./highlighting";
|
|
4
|
+
import { sourceOffset } from "./sourceRanges";
|
|
5
|
+
import { findStringLiteralEnd } from "../parser/stringScanner";
|
|
6
|
+
const v02Keywords = ["let", "for", "in", "to", "return", "match", "case", "default", "if", "then", "else", "and", "or", "not", "true", "false"];
|
|
7
|
+
const v03Keywords = ["null", "type", "fn", "import", "from", "input", "export"];
|
|
8
|
+
const v04Keywords = ["table", "chart", "show", "title", "description", "column", "category", "x", "y", "group", "labels", "series", "as"];
|
|
9
|
+
const v09ListKeywords = ["add", "remove", "at"];
|
|
10
|
+
const v09UnitKeywords = ["dimension", "unit"];
|
|
11
|
+
const standardFunctions = ["sum", "min", "max", "mean", "round", "abs", "sqrt", "pow"];
|
|
12
|
+
const primitiveTypes = ["Number", "String", "Boolean", "DateTime"];
|
|
13
|
+
function cursorInsideOpenAmxFence(text, cursorOffset) {
|
|
14
|
+
const frontMatter = parseFrontMatter(text);
|
|
15
|
+
if (frontMatter.error)
|
|
16
|
+
return false;
|
|
17
|
+
const bodyOffset = text.length - frontMatter.body.length;
|
|
18
|
+
if (cursorOffset < bodyOffset)
|
|
19
|
+
return false;
|
|
20
|
+
const relativeCursor = cursorOffset - bodyOffset;
|
|
21
|
+
const cursorLine = text.slice(bodyOffset, bodyOffset + relativeCursor).split(/\r?\n/).length - 1;
|
|
22
|
+
const lines = frontMatter.body.split(/\r?\n/);
|
|
23
|
+
let open;
|
|
24
|
+
for (let index = 0; index < cursorLine; index++) {
|
|
25
|
+
const line = lines[index] ?? "";
|
|
26
|
+
if (!open) {
|
|
27
|
+
const match = line.match(/^ {0,3}(`{3,}|~{3,})(.*)$/);
|
|
28
|
+
if (match)
|
|
29
|
+
open = { marker: match[1], executable: match[1][0] === "`" && match[2].trim() === "amx" };
|
|
30
|
+
}
|
|
31
|
+
else {
|
|
32
|
+
const closing = line.match(/^ {0,3}(`+|~+)(\s*)$/);
|
|
33
|
+
if (closing && closing[1][0] === open.marker[0] && closing[1].length >= open.marker.length)
|
|
34
|
+
open = undefined;
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
const currentLine = lines[cursorLine] ?? "";
|
|
38
|
+
const currentCloser = currentLine.match(/^ {0,3}(`+|~+)(\s*)$/);
|
|
39
|
+
return !!open?.executable && !(currentCloser && currentCloser[1][0] === open.marker[0]
|
|
40
|
+
&& currentCloser[1].length >= open.marker.length);
|
|
41
|
+
}
|
|
42
|
+
/** Parse the complete buffer when possible, otherwise retain only proven prior statements inside an exact AMX fence. */
|
|
43
|
+
export function prepareEditorCompletion(text, cursorOffset) {
|
|
44
|
+
try {
|
|
45
|
+
const document = parseDocumentText(text);
|
|
46
|
+
if (!isExecutableBlockOffset(text, document, cursorOffset))
|
|
47
|
+
return undefined;
|
|
48
|
+
return { text, document };
|
|
49
|
+
}
|
|
50
|
+
catch {
|
|
51
|
+
if (!cursorInsideOpenAmxFence(text, cursorOffset))
|
|
52
|
+
return undefined;
|
|
53
|
+
const frontMatter = parseFrontMatter(text);
|
|
54
|
+
if (frontMatter.error)
|
|
55
|
+
return undefined;
|
|
56
|
+
const lineStart = text.lastIndexOf("\n", Math.max(0, cursorOffset - 1)) + 1;
|
|
57
|
+
const bodyOffset = text.length - frontMatter.body.length;
|
|
58
|
+
const cursorLine = text.slice(bodyOffset, bodyOffset + Math.max(0, cursorOffset - bodyOffset)).split(/\r?\n/).length - 1;
|
|
59
|
+
const lines = frontMatter.body.split(/\r?\n/);
|
|
60
|
+
let open;
|
|
61
|
+
for (let index = 0; index < cursorLine; index++) {
|
|
62
|
+
const match = (lines[index] ?? "").match(/^ {0,3}(`{3,}|~{3,})(.*)$/);
|
|
63
|
+
if (!open && match)
|
|
64
|
+
open = { marker: match[1], executable: match[1][0] === "`" && match[2].trim() === "amx" };
|
|
65
|
+
else if (open) {
|
|
66
|
+
const closing = (lines[index] ?? "").match(/^ {0,3}(`+|~+)(\s*)$/);
|
|
67
|
+
if (closing && closing[1][0] === open.marker[0] && closing[1].length >= open.marker.length)
|
|
68
|
+
open = undefined;
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
if (!open?.executable)
|
|
72
|
+
return undefined;
|
|
73
|
+
const closer = `${open.marker}\n`;
|
|
74
|
+
const candidates = [
|
|
75
|
+
`${text.slice(0, cursorOffset)}${text.slice(0, cursorOffset).endsWith("\n") ? "" : "\n"}${closer}${text.slice(cursorOffset)}`,
|
|
76
|
+
`${text.slice(0, lineStart)}${text.slice(0, lineStart).endsWith("\n") ? "" : "\n"}${closer}`
|
|
77
|
+
];
|
|
78
|
+
for (const candidate of candidates) {
|
|
79
|
+
try {
|
|
80
|
+
return { text: candidate, document: parseDocumentText(candidate) };
|
|
81
|
+
}
|
|
82
|
+
catch { /* Keep only parser-proven complete statements. */ }
|
|
83
|
+
}
|
|
84
|
+
return undefined;
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
function statementsOf(document) {
|
|
88
|
+
return document.nodes.flatMap(node => node.type === "executableCodeBlock" ? node.statements : []);
|
|
89
|
+
}
|
|
90
|
+
function statementEndOffset(text, statement) {
|
|
91
|
+
const start = sourceOffset(text, statement.source);
|
|
92
|
+
if (start === undefined)
|
|
93
|
+
return Number.MAX_SAFE_INTEGER;
|
|
94
|
+
let depth = 0;
|
|
95
|
+
for (let offset = start; offset < text.length; offset++) {
|
|
96
|
+
const character = text[offset];
|
|
97
|
+
if (character === '"' || character === "'") {
|
|
98
|
+
const end = findStringLiteralEnd(text, offset);
|
|
99
|
+
if (end === undefined)
|
|
100
|
+
break;
|
|
101
|
+
offset = end;
|
|
102
|
+
continue;
|
|
103
|
+
}
|
|
104
|
+
if (character === "{")
|
|
105
|
+
depth++;
|
|
106
|
+
else if (character === "}")
|
|
107
|
+
depth--;
|
|
108
|
+
else if (character === "\n" && depth <= 0)
|
|
109
|
+
return offset;
|
|
110
|
+
}
|
|
111
|
+
return text.length;
|
|
112
|
+
}
|
|
113
|
+
function loopBounds(text, loop) {
|
|
114
|
+
const start = sourceOffset(text, loop.source);
|
|
115
|
+
if (start === undefined)
|
|
116
|
+
return undefined;
|
|
117
|
+
const lineStart = text.lastIndexOf("\n", Math.max(0, start - 1)) + 1;
|
|
118
|
+
const lineEnd = text.indexOf("\n", start);
|
|
119
|
+
const line = text.slice(lineStart, lineEnd < 0 ? text.length : lineEnd);
|
|
120
|
+
const opening = line.lastIndexOf("{");
|
|
121
|
+
if (opening < 0 || line.slice(opening).trim() !== "{")
|
|
122
|
+
return undefined;
|
|
123
|
+
const open = lineStart + opening;
|
|
124
|
+
let depth = 0;
|
|
125
|
+
for (let offset = open; offset < text.length; offset++) {
|
|
126
|
+
const character = text[offset];
|
|
127
|
+
if (character === '"' || character === "'") {
|
|
128
|
+
const end = findStringLiteralEnd(text, offset);
|
|
129
|
+
if (end === undefined)
|
|
130
|
+
return undefined;
|
|
131
|
+
offset = end;
|
|
132
|
+
continue;
|
|
133
|
+
}
|
|
134
|
+
if (character === "{")
|
|
135
|
+
depth++;
|
|
136
|
+
else if (character === "}" && --depth === 0)
|
|
137
|
+
return { open, close: offset };
|
|
138
|
+
}
|
|
139
|
+
return undefined;
|
|
140
|
+
}
|
|
141
|
+
function visibleSymbols(text, parsed, cursorOffset, analysis) {
|
|
142
|
+
const variables = new Set();
|
|
143
|
+
const functions = new Set();
|
|
144
|
+
const types = new Set(primitiveTypes);
|
|
145
|
+
const views = new Set();
|
|
146
|
+
const recordTypes = new Map();
|
|
147
|
+
const localTypeDeclarations = new Map();
|
|
148
|
+
const localBindingTypes = new Map();
|
|
149
|
+
const activeIterators = new Set();
|
|
150
|
+
const collectStatements = (statements) => {
|
|
151
|
+
for (const statement of statements) {
|
|
152
|
+
const start = sourceOffset(text, statement.source);
|
|
153
|
+
if (start === undefined || start >= cursorOffset)
|
|
154
|
+
continue;
|
|
155
|
+
if (statement.type === "variableDeclaration") {
|
|
156
|
+
if (statementEndOffset(text, statement) <= cursorOffset) {
|
|
157
|
+
variables.add(statement.name);
|
|
158
|
+
const inferred = statement.annotation?.type === "namedType" ? statement.annotation.name
|
|
159
|
+
: statement.expression.type === "recordConstructor" ? statement.expression.name : undefined;
|
|
160
|
+
if (inferred)
|
|
161
|
+
localBindingTypes.set(statement.name, inferred);
|
|
162
|
+
}
|
|
163
|
+
collectExpression(statement.expression);
|
|
164
|
+
}
|
|
165
|
+
else if (statement.type === "inputDeclaration") {
|
|
166
|
+
if (statementEndOffset(text, statement) <= cursorOffset) {
|
|
167
|
+
variables.add(statement.name);
|
|
168
|
+
if (statement.annotation.type === "namedType" && statement.annotation.name)
|
|
169
|
+
localBindingTypes.set(statement.name, statement.annotation.name);
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
else if (statement.type === "typeDeclaration") {
|
|
173
|
+
if (statementEndOffset(text, statement) <= cursorOffset) {
|
|
174
|
+
types.add(statement.name);
|
|
175
|
+
localTypeDeclarations.set(statement.name, statement);
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
else if (statement.type === "functionDeclaration") {
|
|
179
|
+
if (statementEndOffset(text, statement) <= cursorOffset)
|
|
180
|
+
functions.add(statement.name);
|
|
181
|
+
}
|
|
182
|
+
else if (statement.type === "tableDeclaration" || statement.type === "chartDeclaration") {
|
|
183
|
+
if (statementEndOffset(text, statement) <= cursorOffset)
|
|
184
|
+
views.add(statement.name);
|
|
185
|
+
}
|
|
186
|
+
else if (statement.type === "importDeclaration") {
|
|
187
|
+
if (statementEndOffset(text, statement) <= cursorOffset) {
|
|
188
|
+
for (const item of statement.names) {
|
|
189
|
+
if (analysis?.importedTypes.has(item.name))
|
|
190
|
+
types.add(item.name);
|
|
191
|
+
if (analysis?.importedFunctions.has(item.name))
|
|
192
|
+
functions.add(item.name);
|
|
193
|
+
if (analysis?.importedBindings.has(item.name)) {
|
|
194
|
+
variables.add(item.name);
|
|
195
|
+
const type = analysis.importedBindings.get(item.name);
|
|
196
|
+
if (type?.kind === "named")
|
|
197
|
+
localBindingTypes.set(item.name, type.name);
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
else if (statement.type === "forStatement")
|
|
203
|
+
collectLoop(statement);
|
|
204
|
+
else if (statement.type === "assignmentStatement" || statement.type === "compoundAssignmentStatement")
|
|
205
|
+
collectExpression(statement.expression);
|
|
206
|
+
else if ("expression" in statement && statement.expression)
|
|
207
|
+
collectExpression(statement.expression);
|
|
208
|
+
}
|
|
209
|
+
};
|
|
210
|
+
const collectLoop = (loop) => {
|
|
211
|
+
const bounds = loopBounds(text, loop);
|
|
212
|
+
if (bounds && cursorOffset > bounds.open && cursorOffset <= bounds.close)
|
|
213
|
+
activeIterators.add(loop.variable);
|
|
214
|
+
collectExpression(loop.iterable);
|
|
215
|
+
collectStatements(loop.body);
|
|
216
|
+
};
|
|
217
|
+
const collectExpression = (expression) => {
|
|
218
|
+
switch (expression.type) {
|
|
219
|
+
case "forExpression":
|
|
220
|
+
collectLoop(expression);
|
|
221
|
+
break;
|
|
222
|
+
case "stringInterpolation":
|
|
223
|
+
expression.parts.forEach(part => { if (typeof part !== "string")
|
|
224
|
+
collectExpression(part); });
|
|
225
|
+
break;
|
|
226
|
+
case "binaryExpression":
|
|
227
|
+
collectExpression(expression.left);
|
|
228
|
+
collectExpression(expression.right);
|
|
229
|
+
break;
|
|
230
|
+
case "measurementAttachment":
|
|
231
|
+
case "measurementConversion":
|
|
232
|
+
collectExpression(expression.value);
|
|
233
|
+
break;
|
|
234
|
+
case "unaryExpression":
|
|
235
|
+
collectExpression(expression.argument);
|
|
236
|
+
break;
|
|
237
|
+
case "conditionalExpression":
|
|
238
|
+
collectExpression(expression.test);
|
|
239
|
+
collectExpression(expression.consequent);
|
|
240
|
+
collectExpression(expression.alternate);
|
|
241
|
+
break;
|
|
242
|
+
case "matchExpression":
|
|
243
|
+
collectMatch(expression);
|
|
244
|
+
break;
|
|
245
|
+
case "rangeExpression":
|
|
246
|
+
collectRange(expression);
|
|
247
|
+
break;
|
|
248
|
+
case "functionCall":
|
|
249
|
+
expression.arguments.forEach(collectExpression);
|
|
250
|
+
break;
|
|
251
|
+
case "listLiteral":
|
|
252
|
+
expression.elements.forEach(collectExpression);
|
|
253
|
+
break;
|
|
254
|
+
case "listAccess":
|
|
255
|
+
collectExpression(expression.receiver);
|
|
256
|
+
collectExpression(expression.index);
|
|
257
|
+
break;
|
|
258
|
+
default: break;
|
|
259
|
+
}
|
|
260
|
+
};
|
|
261
|
+
const collectMatch = (expression) => {
|
|
262
|
+
collectExpression(expression.expression);
|
|
263
|
+
expression.cases.forEach(arm => collectExpression(arm.expression));
|
|
264
|
+
collectExpression(expression.defaultExpression);
|
|
265
|
+
};
|
|
266
|
+
const collectRange = (expression) => { collectExpression(expression.start); collectExpression(expression.end); };
|
|
267
|
+
for (const node of parsed.nodes) {
|
|
268
|
+
if (node.type === "executableCodeBlock" && node.source && (sourceOffset(text, node.source) ?? Number.MAX_SAFE_INTEGER) < cursorOffset) {
|
|
269
|
+
collectStatements(node.statements);
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
for (const iterator of activeIterators)
|
|
273
|
+
variables.add(iterator);
|
|
274
|
+
for (const [name, typeName] of localBindingTypes) {
|
|
275
|
+
const declaration = localTypeDeclarations.get(typeName) ?? analysis?.importedTypes.get(typeName);
|
|
276
|
+
if (declaration)
|
|
277
|
+
recordTypes.set(name, declaration);
|
|
278
|
+
}
|
|
279
|
+
if (analysis)
|
|
280
|
+
for (const [name, declaration] of analysis.importedTypes)
|
|
281
|
+
if (types.has(name))
|
|
282
|
+
localTypeDeclarations.set(name, declaration);
|
|
283
|
+
return { variables, functions, types, views, recordTypes };
|
|
284
|
+
}
|
|
285
|
+
/** Return only candidates proven visible before the cursor in the parsed source order. */
|
|
286
|
+
export function editorCompletionFacts(text, cursorOffset, parsed, analysis, contextText = text) {
|
|
287
|
+
const cursor = Math.max(0, Math.min(cursorOffset, text.length));
|
|
288
|
+
const visible = visibleSymbols(text, parsed, cursor, analysis);
|
|
289
|
+
const contextCursor = Math.max(0, Math.min(cursorOffset, contextText.length));
|
|
290
|
+
const lineStart = contextText.lastIndexOf("\n", Math.max(0, contextCursor - 1)) + 1;
|
|
291
|
+
const prefix = contextText.slice(lineStart, contextCursor);
|
|
292
|
+
const fieldReceiver = prefix.match(/\b([A-Za-z][A-Za-z0-9_]*)\.\w*$/)?.[1];
|
|
293
|
+
const fields = fieldReceiver ? visible.recordTypes.get(fieldReceiver)?.fields.map(field => field.name) ?? [] : [];
|
|
294
|
+
const facts = [
|
|
295
|
+
...[...v02Keywords, ...v03Keywords, ...v04Keywords, ...v09ListKeywords, ...v09UnitKeywords].map(label => ({ label, kind: "keyword" })),
|
|
296
|
+
...standardFunctions.map(label => ({ label, kind: "function" })),
|
|
297
|
+
...[...visible.functions].map(label => ({ label, kind: "function" })),
|
|
298
|
+
...[...visible.types].map(label => ({ label, kind: "class" })),
|
|
299
|
+
...[...visible.variables].map(label => ({ label, kind: "variable" })),
|
|
300
|
+
...[...visible.views].map(label => ({ label, kind: "reference" })),
|
|
301
|
+
...fields.map(label => ({ label, kind: "field" }))
|
|
302
|
+
];
|
|
303
|
+
return facts;
|
|
304
|
+
}
|
|
305
|
+
export function executableBlockContentStart(text, node) {
|
|
306
|
+
if (!node.source)
|
|
307
|
+
return undefined;
|
|
308
|
+
const offset = sourceOffset(text, node.source);
|
|
309
|
+
if (offset === undefined)
|
|
310
|
+
return undefined;
|
|
311
|
+
const lineStart = text.lastIndexOf("\n", Math.max(0, offset - 1)) + 1;
|
|
312
|
+
return text.indexOf("\n", lineStart) + 1;
|
|
313
|
+
}
|