@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.
Files changed (42) hide show
  1. package/COMMERCIAL-LICENSE.md +74 -0
  2. package/LICENSE.md +660 -0
  3. package/README.md +513 -2
  4. package/dist/ast/types.js +2 -0
  5. package/dist/cli.js +186 -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/renderHtml.js +383 -0
  23. package/dist/renderer/reportDocx.js +163 -0
  24. package/dist/renderer/reportPdf.js +202 -0
  25. package/dist/renderer/reportPreparation.js +208 -0
  26. package/dist/runtime/csvTextSerialization.js +8 -0
  27. package/dist/runtime/dataText.js +191 -0
  28. package/dist/runtime/docxDestination.js +55 -0
  29. package/dist/runtime/environment.js +105 -0
  30. package/dist/runtime/evaluateDocument.js +32 -0
  31. package/dist/runtime/evaluateExpression.js +888 -0
  32. package/dist/runtime/externalUnits.js +91 -0
  33. package/dist/runtime/inputData.js +508 -0
  34. package/dist/runtime/measurement.js +110 -0
  35. package/dist/runtime/moduleLoader.js +279 -0
  36. package/dist/runtime/outputData.js +303 -0
  37. package/dist/runtime/pdfDestination.js +57 -0
  38. package/dist/runtime/standardLibrary.js +145 -0
  39. package/dist/typechecker/checkDocument.js +1282 -0
  40. package/dist/typechecker/declarationRegistry.js +7 -0
  41. package/dist/typechecker/dimensionTypes.js +1 -0
  42. package/package.json +33 -4
@@ -0,0 +1,224 @@
1
+ import { declarationNameRange, sourceOffset, sourceTokenRange } from "./sourceRanges";
2
+ import { findStringLiteralEnd } from "../parser/stringScanner";
3
+ function statementsOf(document) {
4
+ return document.nodes.flatMap(node => node.type === "executableCodeBlock" ? node.statements : []);
5
+ }
6
+ /** Return parser-proven tokens only; narrative and ordinary fences never enter the AST statement walk. */
7
+ export function editorHighlightFacts(text, document) {
8
+ const facts = [];
9
+ const add = (source, token, kind) => {
10
+ const range = sourceTokenRange(text, source, token);
11
+ if (range)
12
+ facts.push({ ...range, kind });
13
+ };
14
+ const expression = (node) => {
15
+ switch (node.type) {
16
+ case "numberLiteral": {
17
+ const from = sourceOffset(text, node.source);
18
+ const raw = from === undefined ? undefined : text.slice(from).match(/^-?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?/)?.[0];
19
+ if (raw)
20
+ add(node.source, raw, "literal");
21
+ break;
22
+ }
23
+ case "stringLiteral": {
24
+ const from = sourceOffset(text, node.source);
25
+ if (from !== undefined) {
26
+ const quote = text[from];
27
+ if (quote === '"' || quote === "'") {
28
+ let escaped = false;
29
+ for (let end = from + 1; end < text.length; end++) {
30
+ if (escaped)
31
+ escaped = false;
32
+ else if (text[end] === "\\")
33
+ escaped = true;
34
+ else if (text[end] === quote) {
35
+ facts.push({ from, to: end + 1, kind: "literal" });
36
+ break;
37
+ }
38
+ }
39
+ }
40
+ }
41
+ break;
42
+ }
43
+ case "stringInterpolation": {
44
+ const from = sourceOffset(text, node.source);
45
+ if (from !== undefined) {
46
+ const end = findStringLiteralEnd(text, from);
47
+ if (end !== undefined)
48
+ facts.push({ from, to: end + 1, kind: "literal" });
49
+ }
50
+ node.parts.forEach(part => { if (typeof part !== "string")
51
+ expression(part); });
52
+ break;
53
+ }
54
+ case "booleanLiteral":
55
+ add(node.source, String(node.value), "keyword");
56
+ break;
57
+ case "nullLiteral":
58
+ add(node.source, "null", "keyword");
59
+ break;
60
+ case "identifier":
61
+ add(node.source, node.name, "reference");
62
+ break;
63
+ case "measurementAttachment":
64
+ case "measurementConversion":
65
+ expression(node.value);
66
+ add(node.unitSource, node.unit, "reference");
67
+ break;
68
+ case "functionCall":
69
+ add(node.source, node.callee, "reference");
70
+ node.arguments.forEach(expression);
71
+ break;
72
+ case "recordConstructor":
73
+ add(node.source, node.name, "reference");
74
+ node.fields.forEach(field => expression(field.expression));
75
+ break;
76
+ case "fieldAccess": {
77
+ expression(node.receiver);
78
+ const dot = sourceOffset(text, node.source);
79
+ if (dot !== undefined && text[dot] === ".") {
80
+ const fieldStart = text.slice(dot + 1).match(/^\s*/)?.[0].length ?? 0;
81
+ const fieldSource = node.source && { line: node.source.line, column: node.source.column + 1 + fieldStart };
82
+ add(fieldSource, node.field, "field");
83
+ }
84
+ break;
85
+ }
86
+ case "listAccess":
87
+ expression(node.receiver);
88
+ expression(node.index);
89
+ break;
90
+ case "binaryExpression":
91
+ expression(node.left);
92
+ expression(node.right);
93
+ break;
94
+ case "unaryExpression":
95
+ expression(node.argument);
96
+ break;
97
+ case "conditionalExpression":
98
+ expression(node.test);
99
+ expression(node.consequent);
100
+ expression(node.alternate);
101
+ break;
102
+ case "forExpression":
103
+ expression(node.iterable);
104
+ node.body.forEach(statement);
105
+ break;
106
+ case "matchExpression":
107
+ add(node.source, "match", "keyword");
108
+ expression(node.expression);
109
+ node.cases.forEach(item => { add(item.source, "case", "keyword"); expression(item.expression); });
110
+ add(node.defaultSource, "default", "keyword");
111
+ expression(node.defaultExpression);
112
+ break;
113
+ case "rangeExpression":
114
+ expression(node.start);
115
+ expression(node.end);
116
+ break;
117
+ case "listLiteral":
118
+ node.elements.forEach(expression);
119
+ break;
120
+ default: break;
121
+ }
122
+ };
123
+ const typeReference = (node) => {
124
+ if (!node)
125
+ return;
126
+ if (node.type === "namedType" && node.name)
127
+ add(node.source, node.name, "type");
128
+ if (node.element)
129
+ typeReference(node.element);
130
+ };
131
+ const statement = (node) => {
132
+ const keyword = {
133
+ variableDeclaration: "let", typeDeclaration: "type", functionDeclaration: "fn",
134
+ dimensionDeclaration: "dimension", unitDeclaration: "unit",
135
+ inputDeclaration: "input", importDeclaration: "import", tableDeclaration: "table",
136
+ chartDeclaration: "chart", showStatement: "show", forStatement: "for",
137
+ assignmentStatement: "", compoundAssignmentStatement: "",
138
+ addStatement: "add", removeStatement: "remove"
139
+ };
140
+ const word = keyword[node.type];
141
+ if (word)
142
+ add(node.source, word, "keyword");
143
+ const start = sourceOffset(text, node.source);
144
+ if (start !== undefined) {
145
+ const lineStart = text.lastIndexOf("\n", Math.max(0, start - 1)) + 1;
146
+ const prefix = text.slice(lineStart, start);
147
+ if (/\bexport\s+$/.test(prefix)) {
148
+ const exportStart = lineStart + prefix.lastIndexOf("export");
149
+ const exportSource = node.source && { line: node.source.line, column: exportStart - lineStart + 1 };
150
+ add(exportSource, "export", "keyword");
151
+ }
152
+ }
153
+ if ("name" in node) {
154
+ const range = declarationNameRange(text, node);
155
+ if (range)
156
+ facts.push({ ...range, kind: "declaration" });
157
+ }
158
+ if (node.type === "importDeclaration")
159
+ for (const item of node.names)
160
+ add(item.source, item.name, "reference");
161
+ if (node.type === "inputDeclaration")
162
+ typeReference(node.annotation);
163
+ if (node.type === "typeDeclaration")
164
+ for (const field of node.fields) {
165
+ add(field.source, field.name, "field");
166
+ typeReference(field.annotation);
167
+ }
168
+ if (node.type === "variableDeclaration") {
169
+ typeReference(node.annotation);
170
+ expression(node.expression);
171
+ }
172
+ else if (node.type === "functionDeclaration") {
173
+ node.parameters.forEach(param => typeReference(param.annotation));
174
+ typeReference(node.returnType);
175
+ expression(node.body);
176
+ }
177
+ else if (node.type === "tableDeclaration" || node.type === "chartDeclaration")
178
+ add(node.bindingSource, node.binding, "reference");
179
+ else if (node.type === "showStatement")
180
+ add(node.nameSource, node.name, "reference");
181
+ else if (node.type === "assignmentStatement" || node.type === "compoundAssignmentStatement")
182
+ expression(node.expression);
183
+ else if (node.type === "addStatement") {
184
+ add(node.targetSource, node.name, "reference");
185
+ expression(node.value);
186
+ if (node.index)
187
+ expression(node.index);
188
+ }
189
+ else if (node.type === "removeStatement") {
190
+ add(node.targetSource, node.name, "reference");
191
+ expression(node.count);
192
+ if (node.index)
193
+ expression(node.index);
194
+ }
195
+ else if (node.type === "forStatement") {
196
+ expression(node.iterable);
197
+ node.body.forEach(statement);
198
+ }
199
+ else if ("expression" in node && node.expression)
200
+ expression(node.expression);
201
+ };
202
+ for (const node of document.nodes)
203
+ if (node.type === "executableCodeBlock")
204
+ node.statements.forEach(statement);
205
+ const unique = new Map();
206
+ for (const fact of facts)
207
+ unique.set(`${fact.from}:${fact.to}:${fact.kind}`, fact);
208
+ return [...unique.values()].sort((left, right) => left.from - right.from || left.to - right.to);
209
+ }
210
+ export function isExecutableBlockOffset(text, document, offset) {
211
+ return document.nodes.some(node => {
212
+ if (node.type !== "executableCodeBlock" || !node.source)
213
+ return false;
214
+ const source = sourceOffset(text, node.source);
215
+ if (source === undefined)
216
+ return false;
217
+ const lineStart = text.lastIndexOf("\n", Math.max(0, source - 1)) + 1;
218
+ const openingLineEnd = text.indexOf("\n", lineStart);
219
+ if (openingLineEnd < 0)
220
+ return false;
221
+ const contentStart = openingLineEnd + 1;
222
+ return offset >= contentStart && offset <= contentStart + node.content.length;
223
+ });
224
+ }
@@ -0,0 +1,206 @@
1
+ import path from "node:path";
2
+ import fs from "node:fs";
3
+ import { AmxError } from "../diagnostics/errors";
4
+ import { parseDocumentText } from "../parser/parseDocument";
5
+ import { checkDocument } from "../typechecker/checkDocument";
6
+ const MAX_EDITOR_MODULES = 101;
7
+ function statementsOf(document) {
8
+ return document.nodes.flatMap(node => node.type === "executableCodeBlock" ? node.statements : []);
9
+ }
10
+ function canonicalFile(file) {
11
+ const absolute = path.resolve(file);
12
+ try {
13
+ return fs.realpathSync(absolute);
14
+ }
15
+ catch {
16
+ return path.isAbsolute(file) ? file : absolute;
17
+ }
18
+ }
19
+ function moduleIssue(code, message, file, source) {
20
+ throw new AmxError({ code, message, file, line: source?.line, column: source?.column });
21
+ }
22
+ function locatedError(error, file) {
23
+ if (error instanceof AmxError) {
24
+ error.file ??= file;
25
+ return error;
26
+ }
27
+ const message = error instanceof Error ? error.message : String(error);
28
+ const location = message.match(/\bat (\d+):(\d+)/);
29
+ return new AmxError({ code: "AMX3001", message, file, line: location ? Number(location[1]) : undefined, column: location ? Number(location[2]) : undefined });
30
+ }
31
+ function validateImportPath(importNode, file, entryRoot) {
32
+ const importPath = importNode.path;
33
+ if (!(importPath.startsWith("./") || importPath.startsWith("../"))
34
+ || importPath.includes("\\") || !importPath.endsWith(".amx") || path.isAbsolute(importPath)) {
35
+ moduleIssue("AMX5001", `Invalid local module path '${importPath}'`, file, importNode.pathSource);
36
+ }
37
+ const target = path.resolve(path.dirname(file), importPath);
38
+ const relativeToRoot = path.relative(entryRoot, target);
39
+ if (relativeToRoot === ".." || relativeToRoot.startsWith(`..${path.sep}`) || path.isAbsolute(relativeToRoot)) {
40
+ moduleIssue("AMX5001", `Module '${importPath}' resolves outside the entry directory tree`, file, importNode.pathSource);
41
+ }
42
+ return target;
43
+ }
44
+ /** Parse and statically check a bounded reachable module graph without evaluating AMX or loading data. */
45
+ export function analyzeEditorModules(text, entryFile, resolveModule) {
46
+ let entryDocument;
47
+ try {
48
+ entryDocument = parseDocumentText(text);
49
+ }
50
+ catch (error) {
51
+ throw locatedError(error, entryFile);
52
+ }
53
+ const entryImports = statementsOf(entryDocument).filter((statement) => statement.type === "importDeclaration");
54
+ if (!entryImports.length) {
55
+ const file = entryFile ? canonicalFile(entryFile) : undefined;
56
+ const checkResult = checkDocument(entryDocument, file, { moduleIdentity: file });
57
+ return {
58
+ document: entryDocument,
59
+ importedTypes: new Map(),
60
+ importedFunctions: new Map(),
61
+ importedBindings: new Map(),
62
+ importedDimensions: new Map(),
63
+ importedUnits: new Map(),
64
+ ...checkResult
65
+ };
66
+ }
67
+ if (entryImports.length && (!entryFile || !path.isAbsolute(entryFile))) {
68
+ moduleIssue("AMX5001", "Local imports require a saved file in the workspace", entryFile ?? "", entryImports[0].pathSource);
69
+ }
70
+ if (entryImports.length && !resolveModule) {
71
+ moduleIssue("AMX5001", "Local imports are unavailable to this editor analysis", entryFile, entryImports[0].pathSource);
72
+ }
73
+ const entryPath = entryFile ? canonicalFile(entryFile) : "";
74
+ const entryRoot = entryPath ? path.dirname(entryPath) : "";
75
+ const records = new Map();
76
+ const visiting = [];
77
+ const baseUnits = new Map();
78
+ const visit = (file, document, viaImport) => {
79
+ file = canonicalFile(file);
80
+ const existing = records.get(file);
81
+ if (existing)
82
+ return existing;
83
+ const cycleIndex = visiting.indexOf(file);
84
+ if (cycleIndex >= 0) {
85
+ const cycle = [...visiting.slice(cycleIndex), file].map(item => path.relative(entryRoot, item) || path.basename(item)).join(" -> ");
86
+ moduleIssue("AMX5003", `Import cycle detected: ${cycle}`, viaImport?.file ?? file, viaImport?.source);
87
+ }
88
+ if (records.size + visiting.length >= MAX_EDITOR_MODULES) {
89
+ moduleIssue("AMX5001", `Editor module graph exceeds the ${MAX_EDITOR_MODULES}-module analysis limit`, viaImport?.file ?? file, viaImport?.source);
90
+ }
91
+ visiting.push(file);
92
+ const statements = statementsOf(document);
93
+ if (file !== entryPath) {
94
+ const input = statements.find((statement) => statement.type === "inputDeclaration");
95
+ if (input)
96
+ moduleIssue("AMX3005", "Inputs may only be declared in the entry module", file, input.source);
97
+ }
98
+ const imports = statements.filter((statement) => statement.type === "importDeclaration");
99
+ const localNames = new Set(statements.flatMap(statement => statement.type === "typeDeclaration" || statement.type === "functionDeclaration"
100
+ || statement.type === "variableDeclaration" || statement.type === "inputDeclaration"
101
+ || statement.type === "tableDeclaration" || statement.type === "chartDeclaration"
102
+ || statement.type === "dimensionDeclaration" || statement.type === "unitDeclaration" ? [statement.name] : []));
103
+ const localDimensionUnitNames = new Set(statements.flatMap(statement => statement.type === "dimensionDeclaration" || statement.type === "unitDeclaration" ? [statement.name] : []));
104
+ const importedTypes = new Map();
105
+ const importedFunctions = new Map();
106
+ const importedBindings = new Map();
107
+ const importedDimensions = new Map();
108
+ const importedUnits = new Map();
109
+ const importedNames = new Set();
110
+ const importedDimensionUnitNames = new Set();
111
+ const importTargets = new Map();
112
+ for (const importNode of imports) {
113
+ const targetPath = validateImportPath(importNode, file, entryRoot);
114
+ let resolved;
115
+ try {
116
+ resolved = resolveModule(file, targetPath, importNode);
117
+ }
118
+ catch (error) {
119
+ if (error instanceof AmxError)
120
+ throw error;
121
+ moduleIssue("AMX5001", `Module '${importNode.path}' could not be found`, file, importNode.pathSource);
122
+ }
123
+ const relativeToRoot = path.relative(entryRoot, resolved.file);
124
+ if (relativeToRoot === ".." || relativeToRoot.startsWith(`..${path.sep}`) || path.isAbsolute(relativeToRoot)) {
125
+ moduleIssue("AMX5001", `Module '${importNode.path}' resolves outside the entry directory tree`, file, importNode.pathSource);
126
+ }
127
+ let dependencyDocument;
128
+ try {
129
+ dependencyDocument = parseDocumentText(resolved.text);
130
+ }
131
+ catch (error) {
132
+ const nested = locatedError(error, resolved.file);
133
+ if (nested.code === "AMX3006") {
134
+ nested.file ??= resolved.file;
135
+ throw nested;
136
+ }
137
+ moduleIssue("AMX5001", `Failed to parse module '${importNode.path}': ${nested.message}`, file, importNode.pathSource);
138
+ }
139
+ const dependencyPath = canonicalFile(resolved.file);
140
+ const dependency = visit(dependencyPath, dependencyDocument, { file, source: importNode.pathSource });
141
+ for (const importedName of importNode.names) {
142
+ const isDimensionOrUnit = dependency.checkResult.exportedDimensions.has(importedName.name)
143
+ || dependency.checkResult.exportedUnits.has(importedName.name);
144
+ if (importedNames.has(importedName.name)) {
145
+ if (isDimensionOrUnit || importedDimensionUnitNames.has(importedName.name))
146
+ moduleIssue("AMX3008", `Duplicate import of dimension/unit '${importedName.name}'`, file, importedName.source);
147
+ moduleIssue("AMX5002", `Duplicate import of '${importedName.name}'`, file, importedName.source);
148
+ }
149
+ importedNames.add(importedName.name);
150
+ if (localNames.has(importedName.name)) {
151
+ if (isDimensionOrUnit || localDimensionUnitNames.has(importedName.name))
152
+ moduleIssue("AMX3008", `Imported dimension/unit '${importedName.name}' collides with a local declaration`, file, importedName.source);
153
+ moduleIssue("AMX5002", `Imported name '${importedName.name}' collides with a local declaration`, file, importedName.source);
154
+ }
155
+ if (dependency.checkResult.exportedTypes.has(importedName.name))
156
+ importedTypes.set(importedName.name, dependency.checkResult.exportedTypes.get(importedName.name));
157
+ else if (dependency.checkResult.exportedFunctions.has(importedName.name))
158
+ importedFunctions.set(importedName.name, dependency.checkResult.exportedFunctions.get(importedName.name));
159
+ else if (dependency.checkResult.exportedBindings.has(importedName.name))
160
+ importedBindings.set(importedName.name, dependency.checkResult.exportedBindings.get(importedName.name));
161
+ else if (dependency.checkResult.exportedDimensions.has(importedName.name)) {
162
+ importedDimensions.set(importedName.name, dependency.checkResult.exportedDimensions.get(importedName.name));
163
+ importedDimensionUnitNames.add(importedName.name);
164
+ }
165
+ else if (dependency.checkResult.exportedUnits.has(importedName.name)) {
166
+ importedUnits.set(importedName.name, dependency.checkResult.exportedUnits.get(importedName.name));
167
+ importedDimensionUnitNames.add(importedName.name);
168
+ }
169
+ else
170
+ moduleIssue("AMX5002", `Module '${importNode.path}' does not export '${importedName.name}'`, file, importedName.source);
171
+ importTargets.set(importedName.name, dependencyPath);
172
+ }
173
+ }
174
+ let checkResult;
175
+ try {
176
+ checkResult = checkDocument(document, file, {
177
+ types: importedTypes,
178
+ functions: importedFunctions,
179
+ bindings: importedBindings,
180
+ dimensions: importedDimensions,
181
+ units: importedUnits,
182
+ baseUnits,
183
+ moduleIdentity: file
184
+ });
185
+ }
186
+ catch (error) {
187
+ visiting.pop();
188
+ throw locatedError(error, file);
189
+ }
190
+ visiting.pop();
191
+ const record = { file, document, checkResult, importedTypes, importedFunctions, importedBindings, importedDimensions, importedUnits, importTargets };
192
+ records.set(file, record);
193
+ return record;
194
+ };
195
+ const result = visit(entryPath, entryDocument);
196
+ return {
197
+ document: result.document,
198
+ importedTypes: result.importedTypes,
199
+ importedFunctions: result.importedFunctions,
200
+ importedBindings: result.importedBindings,
201
+ importedDimensions: result.importedDimensions,
202
+ importedUnits: result.importedUnits,
203
+ bindingTypes: result.checkResult.bindingTypes,
204
+ modules: records
205
+ };
206
+ }
@@ -0,0 +1,46 @@
1
+ import { sourceTokenRange } from "./sourceRanges";
2
+ const reservedNames = new Set([
3
+ "let", "for", "in", "to", "return", "match", "case", "default", "if", "then", "else", "and", "or", "not", "dimension", "unit",
4
+ "true", "false", "null", "type", "fn", "import", "from", "input", "export", "table", "chart", "show",
5
+ "title", "description", "column", "category", "x", "y", "group", "labels", "series", "as",
6
+ "Number", "String", "Boolean", "DateTime"
7
+ ]);
8
+ export function isSafeRenameIdentifier(name) {
9
+ return /^[A-Za-z][A-Za-z0-9_]*$/.test(name) && !reservedNames.has(name);
10
+ }
11
+ function statementsOf(document) {
12
+ return document.nodes.flatMap(node => node.type === "executableCodeBlock" ? node.statements : []);
13
+ }
14
+ export function editorCodeActionFacts(text, document, diagnostics) {
15
+ const visibleViews = [];
16
+ const actions = [];
17
+ for (const statement of statementsOf(document)) {
18
+ if (statement.type === "tableDeclaration" || statement.type === "chartDeclaration")
19
+ visibleViews.push(statement.name);
20
+ if (statement.type !== "showStatement" || visibleViews.length !== 1 || !statement.nameSource)
21
+ continue;
22
+ const range = sourceTokenRange(text, statement.nameSource, statement.name);
23
+ if (!range)
24
+ continue;
25
+ const diagnostic = diagnostics.find(item => item.code === "AMX3001"
26
+ && item.message === `Unknown or not-yet-declared visualization '${statement.name}'`
27
+ && item.from <= range.from && item.to > range.from);
28
+ if (!diagnostic)
29
+ continue;
30
+ const replacement = visibleViews[0];
31
+ if (replacement !== statement.name)
32
+ actions.push({ ...range, title: `Use visible view '${replacement}'`, expected: statement.name, replacement, code: diagnostic.code });
33
+ }
34
+ return actions;
35
+ }
36
+ export function editorRenameFact(facts, file, offset) {
37
+ const selected = facts.find(fact => fact.file === file && fact.from <= offset && offset < fact.to);
38
+ if (!selected)
39
+ return undefined;
40
+ const identity = selected.target;
41
+ const edits = facts.filter(fact => fact.target.file === identity.file && fact.target.from === identity.from && fact.target.to === identity.to)
42
+ .map(fact => ({ file: fact.file, from: fact.from, to: fact.to }));
43
+ if (!edits.some(edit => edit.file === identity.file && edit.from === identity.from && edit.to === identity.to))
44
+ return undefined;
45
+ return { target: identity, name: selected.name, edits };
46
+ }
@@ -0,0 +1,50 @@
1
+ const declarationKeywords = {
2
+ typeDeclaration: "type",
3
+ dimensionDeclaration: "dimension",
4
+ unitDeclaration: "unit",
5
+ functionDeclaration: "fn",
6
+ inputDeclaration: "input",
7
+ variableDeclaration: "let",
8
+ tableDeclaration: "table",
9
+ chartDeclaration: "chart"
10
+ };
11
+ export function sourceOffset(text, source) {
12
+ if (!source || !Number.isSafeInteger(source.line) || !Number.isSafeInteger(source.column)
13
+ || source.line < 1 || source.column < 1)
14
+ return undefined;
15
+ let lineStart = 0;
16
+ for (let line = 1; line < source.line; line++) {
17
+ const newline = text.indexOf("\n", lineStart);
18
+ if (newline < 0)
19
+ return undefined;
20
+ lineStart = newline + 1;
21
+ }
22
+ const newline = text.indexOf("\n", lineStart);
23
+ const lineEnd = newline < 0 ? text.length : newline;
24
+ const contentEnd = lineEnd > lineStart && text[lineEnd - 1] === "\r" ? lineEnd - 1 : lineEnd;
25
+ const offset = lineStart + source.column - 1;
26
+ return offset <= contentEnd ? offset : undefined;
27
+ }
28
+ export function sourceTokenRange(text, source, token) {
29
+ const from = sourceOffset(text, source);
30
+ if (from === undefined || text.slice(from, from + token.length) !== token)
31
+ return undefined;
32
+ return { from, to: from + token.length };
33
+ }
34
+ export function declarationNameRange(text, statement) {
35
+ if (!("name" in statement) || !statement.source)
36
+ return undefined;
37
+ const keyword = declarationKeywords[statement.type];
38
+ if (!keyword)
39
+ return undefined;
40
+ const from = sourceOffset(text, statement.source);
41
+ if (from === undefined)
42
+ return undefined;
43
+ const lineEnd = text.indexOf("\n", from);
44
+ const line = text.slice(from, lineEnd < 0 ? text.length : lineEnd).replace(/\r$/, "");
45
+ const match = line.match(new RegExp(`^(?:export\\s+)?${keyword}\\s+([A-Za-z_][A-Za-z0-9_]*)\\b`));
46
+ if (!match || match[1] !== statement.name)
47
+ return undefined;
48
+ const nameOffset = from + match[0].indexOf(match[1]);
49
+ return sourceTokenRange(text, { line: statement.source.line, column: statement.source.column + nameOffset - from }, statement.name);
50
+ }