@nova-energy/openamx 0.18.0 → 0.21.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +26 -15
- package/dist/cli.js +61 -0
- package/dist/editor/highlighting.js +11 -1
- package/dist/index.js +1 -0
- package/dist/parser/parseStatements.js +40 -0
- package/dist/renderer/chartModel.js +1 -0
- package/dist/renderer/diagramBrowserRuntime.js +1 -1
- package/dist/renderer/renderHtml.js +24 -7
- package/dist/renderer/reportDocx.js +13 -4
- package/dist/renderer/reportPdf.js +2 -0
- package/dist/runtime/evaluateExpression.js +169 -32
- package/dist/runtime/externalUnits.js +21 -6
- package/dist/runtime/inputData.js +80 -22
- package/dist/runtime/measurement.js +28 -1
- package/dist/runtime/moduleLoader.js +6 -3
- package/dist/runtime/outputData.js +5 -3
- package/dist/transpiler/emit.js +842 -0
- package/dist/transpiler/filesystemGraph.js +267 -0
- package/dist/transpiler/graph.js +200 -0
- package/dist/transpiler/index.js +52 -0
- package/dist/transpiler/outputWriter.js +378 -0
- package/dist/transpiler/source.js +16 -0
- package/dist/transpiler/types.js +1 -0
- package/dist/transpilerRuntime.js +684 -0
- package/dist/typechecker/checkDocument.js +153 -34
- package/package.json +1 -1
|
@@ -0,0 +1,267 @@
|
|
|
1
|
+
import { readFileSync, realpathSync, statSync } from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { AmxError, moduleError, staticError } from '../diagnostics/errors';
|
|
4
|
+
import { parseDocumentText } from '../parser/parseDocument';
|
|
5
|
+
import { normalizeParserLineSeparators } from './source';
|
|
6
|
+
function statementsOf(document) {
|
|
7
|
+
const statements = [];
|
|
8
|
+
for (const node of document.nodes) {
|
|
9
|
+
if (node.type === 'executableCodeBlock')
|
|
10
|
+
statements.push(...node.statements);
|
|
11
|
+
else if (node.type === 'variableDeclaration')
|
|
12
|
+
statements.push(node);
|
|
13
|
+
}
|
|
14
|
+
return statements;
|
|
15
|
+
}
|
|
16
|
+
function namedDeclaration(statement) {
|
|
17
|
+
switch (statement.type) {
|
|
18
|
+
case 'typeDeclaration':
|
|
19
|
+
return { name: statement.name, kind: 'type', exported: statement.exported === true };
|
|
20
|
+
case 'enumDeclaration':
|
|
21
|
+
return { name: statement.name, kind: 'enum', exported: statement.exported === true };
|
|
22
|
+
case 'functionDeclaration':
|
|
23
|
+
return { name: statement.name, kind: 'function', exported: statement.exported === true };
|
|
24
|
+
case 'dimensionDeclaration':
|
|
25
|
+
return { name: statement.name, kind: 'dimension', exported: statement.exported === true };
|
|
26
|
+
case 'unitDeclaration':
|
|
27
|
+
return { name: statement.name, kind: 'unit', exported: statement.exported === true };
|
|
28
|
+
case 'variableDeclaration':
|
|
29
|
+
case 'inputDeclaration':
|
|
30
|
+
case 'tableDeclaration':
|
|
31
|
+
case 'chartDeclaration':
|
|
32
|
+
return { name: statement.name, kind: 'binding', exported: 'exported' in statement && statement.exported === true };
|
|
33
|
+
default:
|
|
34
|
+
return undefined;
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
function isDimensionOrUnit(kind) {
|
|
38
|
+
return kind === 'dimension' || kind === 'unit';
|
|
39
|
+
}
|
|
40
|
+
function validateImportedNames(modules) {
|
|
41
|
+
const exportsByModule = new Map();
|
|
42
|
+
const statementsByModule = new Map();
|
|
43
|
+
for (const module of modules) {
|
|
44
|
+
const statements = statementsOf(parseSource(module.sourceText, module.sourcePath));
|
|
45
|
+
const declarations = new Map();
|
|
46
|
+
for (const statement of statements) {
|
|
47
|
+
const declaration = namedDeclaration(statement);
|
|
48
|
+
if (declaration)
|
|
49
|
+
declarations.set(declaration.name, declaration);
|
|
50
|
+
}
|
|
51
|
+
const exports = new Map();
|
|
52
|
+
for (const declaration of declarations.values()) {
|
|
53
|
+
if (declaration.exported)
|
|
54
|
+
exports.set(declaration.name, declaration.kind);
|
|
55
|
+
}
|
|
56
|
+
for (const statement of statements) {
|
|
57
|
+
if (statement.type !== 'exportNamesDeclaration')
|
|
58
|
+
continue;
|
|
59
|
+
for (const exported of statement.names) {
|
|
60
|
+
const declaration = declarations.get(exported.name);
|
|
61
|
+
if (declaration)
|
|
62
|
+
exports.set(exported.name, declaration.kind);
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
exportsByModule.set(module.moduleId, exports);
|
|
66
|
+
statementsByModule.set(module.moduleId, statements);
|
|
67
|
+
}
|
|
68
|
+
for (const module of modules) {
|
|
69
|
+
const declarations = new Map();
|
|
70
|
+
const statements = statementsByModule.get(module.moduleId);
|
|
71
|
+
for (const statement of statements) {
|
|
72
|
+
const declaration = namedDeclaration(statement);
|
|
73
|
+
if (declaration)
|
|
74
|
+
declarations.set(declaration.name, declaration);
|
|
75
|
+
}
|
|
76
|
+
const imported = new Map();
|
|
77
|
+
for (const statement of statements) {
|
|
78
|
+
if (statement.type !== 'importDeclaration')
|
|
79
|
+
continue;
|
|
80
|
+
const dependencyId = module.resolvedImports.find(mapping => mapping.importPath === statement.path)?.moduleId;
|
|
81
|
+
if (!dependencyId)
|
|
82
|
+
moduleError('AMX5001', `Import '${statement.path}' has no resolved module`, statement.pathSource, module.sourcePath);
|
|
83
|
+
const dependencyExports = exportsByModule.get(dependencyId);
|
|
84
|
+
if (!dependencyExports)
|
|
85
|
+
moduleError('AMX5001', `Resolved module '${dependencyId}' is missing`, statement.pathSource, module.sourcePath);
|
|
86
|
+
for (const importedName of statement.names) {
|
|
87
|
+
const kind = dependencyExports.get(importedName.name);
|
|
88
|
+
const dimensionOrUnit = isDimensionOrUnit(kind);
|
|
89
|
+
const previousDimensionOrUnit = imported.get(importedName.name) === true;
|
|
90
|
+
if (imported.has(importedName.name)) {
|
|
91
|
+
if (dimensionOrUnit || previousDimensionOrUnit) {
|
|
92
|
+
staticError('AMX3008', `Duplicate import of dimension/unit '${importedName.name}'`, importedName.source, module.sourcePath);
|
|
93
|
+
}
|
|
94
|
+
moduleError('AMX5002', `Duplicate import of '${importedName.name}'`, importedName.source, module.sourcePath);
|
|
95
|
+
}
|
|
96
|
+
const local = declarations.get(importedName.name);
|
|
97
|
+
if (local) {
|
|
98
|
+
if (dimensionOrUnit || isDimensionOrUnit(local.kind)) {
|
|
99
|
+
staticError('AMX3008', `Imported dimension/unit '${importedName.name}' collides with a local declaration`, importedName.source, module.sourcePath);
|
|
100
|
+
}
|
|
101
|
+
moduleError('AMX5002', `Imported name '${importedName.name}' collides with a local declaration`, importedName.source, module.sourcePath);
|
|
102
|
+
}
|
|
103
|
+
imported.set(importedName.name, dimensionOrUnit);
|
|
104
|
+
if (!kind) {
|
|
105
|
+
moduleError('AMX5002', `Module '${statement.path}' does not export '${importedName.name}'`, importedName.source, module.sourcePath);
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
function isWithinDirectory(root, candidate) {
|
|
112
|
+
const relativePath = path.relative(root, candidate);
|
|
113
|
+
return relativePath !== '' && relativePath !== '..'
|
|
114
|
+
&& !relativePath.startsWith(`..${path.sep}`) && !path.isAbsolute(relativePath);
|
|
115
|
+
}
|
|
116
|
+
function realpathOrFail(target, message, file, source) {
|
|
117
|
+
try {
|
|
118
|
+
return realpathSync(target);
|
|
119
|
+
}
|
|
120
|
+
catch {
|
|
121
|
+
return moduleError('AMX5001', message, source, file);
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
function outputPathFor(root, canonicalPath, sourcePath) {
|
|
125
|
+
const relativePath = path.relative(root, canonicalPath);
|
|
126
|
+
if (!relativePath || path.isAbsolute(relativePath) || relativePath === '..'
|
|
127
|
+
|| relativePath.startsWith(`..${path.sep}`) || !relativePath.endsWith('.amx')) {
|
|
128
|
+
return moduleError('AMX5001', `Invalid source-relative module path '${relativePath}'`, undefined, sourcePath);
|
|
129
|
+
}
|
|
130
|
+
return relativePath.split(path.sep).join('/').replace(/\.amx$/, '.ts');
|
|
131
|
+
}
|
|
132
|
+
function validateImportPath(declaration, file) {
|
|
133
|
+
const importPath = declaration.path;
|
|
134
|
+
if (!(importPath.startsWith('./') || importPath.startsWith('../'))) {
|
|
135
|
+
moduleError('AMX5001', `Import path '${importPath}' must be relative and start with './' or '../'`, declaration.pathSource, file);
|
|
136
|
+
}
|
|
137
|
+
if (importPath.includes('\\')) {
|
|
138
|
+
moduleError('AMX5001', `Import path '${importPath}' must use '/' separators`, declaration.pathSource, file);
|
|
139
|
+
}
|
|
140
|
+
if (!importPath.endsWith('.amx')) {
|
|
141
|
+
moduleError('AMX5001', `Import path '${importPath}' must end with the exact lowercase '.amx' suffix`, declaration.pathSource, file);
|
|
142
|
+
}
|
|
143
|
+
if (path.isAbsolute(importPath)) {
|
|
144
|
+
moduleError('AMX5001', `Import path '${importPath}' must be relative`, declaration.pathSource, file);
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
function parseSource(sourceText, sourcePath) {
|
|
148
|
+
try {
|
|
149
|
+
return parseDocumentText(normalizeParserLineSeparators(sourceText));
|
|
150
|
+
}
|
|
151
|
+
catch (error) {
|
|
152
|
+
if (error instanceof AmxError) {
|
|
153
|
+
error.file ??= sourcePath;
|
|
154
|
+
throw error;
|
|
155
|
+
}
|
|
156
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
157
|
+
return moduleError('AMX5001', `Failed to parse module '${sourcePath}': ${message}`, undefined, sourcePath);
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
export function resolveTranspileGraph(entryPath, options = {}) {
|
|
161
|
+
const absoluteEntry = path.resolve(entryPath);
|
|
162
|
+
const canonicalEntry = realpathOrFail(absoluteEntry, `Entry module '${entryPath}' could not be read`, entryPath);
|
|
163
|
+
if (!canonicalEntry.endsWith('.amx')) {
|
|
164
|
+
moduleError('AMX5001', `Entry module '${entryPath}' must have the exact lowercase '.amx' suffix`, undefined, entryPath);
|
|
165
|
+
}
|
|
166
|
+
let entryStats;
|
|
167
|
+
try {
|
|
168
|
+
entryStats = statSync(canonicalEntry);
|
|
169
|
+
}
|
|
170
|
+
catch {
|
|
171
|
+
moduleError('AMX5001', `Entry module '${entryPath}' could not be read`, undefined, entryPath);
|
|
172
|
+
}
|
|
173
|
+
if (!entryStats.isFile())
|
|
174
|
+
moduleError('AMX5001', 'Entry module must be a regular file', undefined, canonicalEntry);
|
|
175
|
+
const canonicalRoot = options.importRoot === undefined
|
|
176
|
+
? path.dirname(canonicalEntry)
|
|
177
|
+
: realpathOrFail(path.resolve(options.importRoot), `Import root '${options.importRoot}' could not be read`, entryPath);
|
|
178
|
+
let rootStats;
|
|
179
|
+
try {
|
|
180
|
+
rootStats = statSync(canonicalRoot);
|
|
181
|
+
}
|
|
182
|
+
catch {
|
|
183
|
+
moduleError('AMX5001', `Import root '${options.importRoot ?? canonicalRoot}' could not be read`, undefined, entryPath);
|
|
184
|
+
}
|
|
185
|
+
if (!rootStats.isDirectory())
|
|
186
|
+
moduleError('AMX5001', 'Import root must be a directory', undefined, entryPath);
|
|
187
|
+
if (canonicalEntry !== canonicalRoot && !isWithinDirectory(canonicalRoot, canonicalEntry)) {
|
|
188
|
+
moduleError('AMX5001', `Entry module '${entryPath}' resolves outside the import root directory tree`, undefined, entryPath);
|
|
189
|
+
}
|
|
190
|
+
const loaded = new Map();
|
|
191
|
+
const visiting = [];
|
|
192
|
+
const dependencyOrder = [];
|
|
193
|
+
const visit = (canonicalPath, viaImport) => {
|
|
194
|
+
const cycleIndex = visiting.indexOf(canonicalPath);
|
|
195
|
+
if (cycleIndex !== -1) {
|
|
196
|
+
const cycle = [...visiting.slice(cycleIndex), canonicalPath]
|
|
197
|
+
.map(item => path.relative(canonicalRoot, item).split(path.sep).join('/') || path.basename(item));
|
|
198
|
+
return moduleError('AMX5003', `Import cycle detected: ${cycle.join(' -> ')}`, viaImport?.declaration.pathSource, viaImport?.importingFile ?? canonicalPath);
|
|
199
|
+
}
|
|
200
|
+
const existing = loaded.get(canonicalPath);
|
|
201
|
+
if (existing)
|
|
202
|
+
return existing;
|
|
203
|
+
visiting.push(canonicalPath);
|
|
204
|
+
const sourcePath = canonicalPath;
|
|
205
|
+
const outputPath = outputPathFor(canonicalRoot, canonicalPath, sourcePath);
|
|
206
|
+
let sourceText;
|
|
207
|
+
const overlayText = canonicalPath === canonicalEntry && options.entryText !== undefined
|
|
208
|
+
? options.entryText
|
|
209
|
+
: options.sourceOverlay?.get(canonicalPath);
|
|
210
|
+
if (overlayText !== undefined) {
|
|
211
|
+
sourceText = overlayText;
|
|
212
|
+
}
|
|
213
|
+
else {
|
|
214
|
+
try {
|
|
215
|
+
sourceText = readFileSync(canonicalPath, 'utf8');
|
|
216
|
+
}
|
|
217
|
+
catch {
|
|
218
|
+
return moduleError('AMX5001', viaImport ? `Module '${viaImport.declaration.path}' could not be read` : `Entry module '${entryPath}' could not be read`, viaImport?.declaration.pathSource, viaImport?.importingFile ?? sourcePath);
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
const statements = statementsOf(parseSource(sourceText, sourcePath));
|
|
222
|
+
if (canonicalPath !== canonicalEntry) {
|
|
223
|
+
const input = statements.find(statement => statement.type === 'inputDeclaration');
|
|
224
|
+
if (input?.type === 'inputDeclaration') {
|
|
225
|
+
staticError('AMX3005', 'Inputs may only be declared in the entry module', input.source, sourcePath);
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
const imports = [];
|
|
229
|
+
let sawNonImport = false;
|
|
230
|
+
for (const statement of statements) {
|
|
231
|
+
if (statement.type === 'importDeclaration') {
|
|
232
|
+
if (sawNonImport) {
|
|
233
|
+
moduleError('AMX5001', 'Import declarations must precede all other executable items', statement.source, sourcePath);
|
|
234
|
+
}
|
|
235
|
+
imports.push(statement);
|
|
236
|
+
}
|
|
237
|
+
else {
|
|
238
|
+
sawNonImport = true;
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
const resolvedImports = [];
|
|
242
|
+
for (const declaration of imports) {
|
|
243
|
+
validateImportPath(declaration, sourcePath);
|
|
244
|
+
const target = path.resolve(path.dirname(canonicalPath), declaration.path);
|
|
245
|
+
const canonicalTarget = realpathOrFail(target, `Module '${declaration.path}' could not be found`, sourcePath, declaration.pathSource);
|
|
246
|
+
if (!isWithinDirectory(canonicalRoot, canonicalTarget)) {
|
|
247
|
+
moduleError('AMX5001', `Module '${declaration.path}' resolves outside the ${options.importRoot === undefined ? 'entry directory tree' : 'import root directory tree'}`, declaration.pathSource, sourcePath);
|
|
248
|
+
}
|
|
249
|
+
const dependency = visit(canonicalTarget, { declaration, importingFile: sourcePath });
|
|
250
|
+
resolvedImports.push({ importPath: declaration.path, moduleId: dependency.moduleId });
|
|
251
|
+
}
|
|
252
|
+
visiting.pop();
|
|
253
|
+
const module = {
|
|
254
|
+
moduleId: outputPath,
|
|
255
|
+
sourcePath,
|
|
256
|
+
outputPath,
|
|
257
|
+
sourceText,
|
|
258
|
+
resolvedImports
|
|
259
|
+
};
|
|
260
|
+
loaded.set(canonicalPath, module);
|
|
261
|
+
dependencyOrder.push(module);
|
|
262
|
+
return module;
|
|
263
|
+
};
|
|
264
|
+
const entry = visit(canonicalEntry);
|
|
265
|
+
validateImportedNames(dependencyOrder);
|
|
266
|
+
return { entryModuleId: entry.moduleId, modules: dependencyOrder };
|
|
267
|
+
}
|
|
@@ -0,0 +1,200 @@
|
|
|
1
|
+
import path from 'node:path';
|
|
2
|
+
import { AmxError, moduleError } from '../diagnostics/errors';
|
|
3
|
+
import { parseDocumentText } from '../parser/parseDocument';
|
|
4
|
+
import { checkDocument } from '../typechecker/checkDocument';
|
|
5
|
+
import { normalizeParserLineSeparators } from './source';
|
|
6
|
+
function statementsOf(document) {
|
|
7
|
+
const statements = [];
|
|
8
|
+
for (const node of document.nodes) {
|
|
9
|
+
if (node.type === 'executableCodeBlock')
|
|
10
|
+
statements.push(...node.statements);
|
|
11
|
+
else if (node.type === 'variableDeclaration')
|
|
12
|
+
statements.push(node);
|
|
13
|
+
}
|
|
14
|
+
return statements;
|
|
15
|
+
}
|
|
16
|
+
function validateOutputPath(module) {
|
|
17
|
+
const outputPath = module.outputPath;
|
|
18
|
+
if (!outputPath || outputPath.includes('\\') || path.posix.isAbsolute(outputPath)
|
|
19
|
+
|| outputPath.split('/').some(part => part === '..' || part === '')
|
|
20
|
+
|| path.posix.normalize(outputPath) !== outputPath || !outputPath.endsWith('.ts')) {
|
|
21
|
+
moduleError('AMX5001', `Invalid output-relative TypeScript path '${outputPath}'`, undefined, module.sourcePath);
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
function collectDocuments(input) {
|
|
25
|
+
const records = new Map();
|
|
26
|
+
const outputPaths = new Set();
|
|
27
|
+
for (const module of input) {
|
|
28
|
+
if (!module.moduleId || records.has(module.moduleId)) {
|
|
29
|
+
moduleError('AMX5001', `Duplicate or empty module identity '${module.moduleId}'`, undefined, module.sourcePath);
|
|
30
|
+
}
|
|
31
|
+
validateOutputPath(module);
|
|
32
|
+
if (outputPaths.has(module.outputPath)) {
|
|
33
|
+
moduleError('AMX5001', `Duplicate output path '${module.outputPath}'`, undefined, module.sourcePath);
|
|
34
|
+
}
|
|
35
|
+
outputPaths.add(module.outputPath);
|
|
36
|
+
const importMappings = new Map();
|
|
37
|
+
for (const mapping of module.resolvedImports) {
|
|
38
|
+
if (importMappings.has(mapping.importPath)) {
|
|
39
|
+
moduleError('AMX5002', `Duplicate resolved import mapping '${mapping.importPath}'`, undefined, module.sourcePath);
|
|
40
|
+
}
|
|
41
|
+
importMappings.set(mapping.importPath, mapping.moduleId);
|
|
42
|
+
}
|
|
43
|
+
let document;
|
|
44
|
+
try {
|
|
45
|
+
document = parseDocumentText(normalizeParserLineSeparators(module.sourceText));
|
|
46
|
+
}
|
|
47
|
+
catch (error) {
|
|
48
|
+
if (error instanceof AmxError) {
|
|
49
|
+
error.file ??= module.sourcePath;
|
|
50
|
+
throw error;
|
|
51
|
+
}
|
|
52
|
+
const parseError = error instanceof Error ? error : new Error(String(error));
|
|
53
|
+
Object.assign(parseError, { file: module.sourcePath });
|
|
54
|
+
throw parseError;
|
|
55
|
+
}
|
|
56
|
+
records.set(module.moduleId, {
|
|
57
|
+
input: module,
|
|
58
|
+
document,
|
|
59
|
+
statements: statementsOf(document),
|
|
60
|
+
importMappings
|
|
61
|
+
});
|
|
62
|
+
}
|
|
63
|
+
return records;
|
|
64
|
+
}
|
|
65
|
+
function importedContext(source, statements, dependencies) {
|
|
66
|
+
const context = {
|
|
67
|
+
types: new Map(),
|
|
68
|
+
enums: new Map(),
|
|
69
|
+
functions: new Map(),
|
|
70
|
+
bindings: new Map(),
|
|
71
|
+
dimensions: new Map(),
|
|
72
|
+
units: new Map()
|
|
73
|
+
};
|
|
74
|
+
for (const statement of statements) {
|
|
75
|
+
if (statement.type !== 'importDeclaration')
|
|
76
|
+
continue;
|
|
77
|
+
const dependency = dependencies.get(statement.path);
|
|
78
|
+
if (!dependency)
|
|
79
|
+
moduleError('AMX5001', `Import '${statement.path}' has no resolved module`, statement.pathSource, source.sourcePath);
|
|
80
|
+
for (const imported of statement.names) {
|
|
81
|
+
const name = imported.name;
|
|
82
|
+
const check = dependency.check;
|
|
83
|
+
if (check.exportedTypes.has(name))
|
|
84
|
+
context.types.set(name, check.exportedTypes.get(name));
|
|
85
|
+
else if (check.exportedEnums.has(name))
|
|
86
|
+
context.enums.set(name, check.exportedEnums.get(name));
|
|
87
|
+
else if (check.exportedFunctions.has(name))
|
|
88
|
+
context.functions.set(name, check.exportedFunctions.get(name));
|
|
89
|
+
else if (check.exportedBindings.has(name))
|
|
90
|
+
context.bindings.set(name, check.exportedBindings.get(name));
|
|
91
|
+
else if (check.exportedDimensions.has(name))
|
|
92
|
+
context.dimensions.set(name, check.exportedDimensions.get(name));
|
|
93
|
+
else if (check.exportedUnits.has(name))
|
|
94
|
+
context.units.set(name, check.exportedUnits.get(name));
|
|
95
|
+
else
|
|
96
|
+
moduleError('AMX5002', `Module '${statement.path}' does not export '${name}'`, imported.source, source.sourcePath);
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
return context;
|
|
100
|
+
}
|
|
101
|
+
export function prepareGraph(entryModuleId, modules) {
|
|
102
|
+
if (!modules.length)
|
|
103
|
+
moduleError('AMX5001', 'A transpile graph must contain at least one module');
|
|
104
|
+
const records = collectDocuments(modules);
|
|
105
|
+
const entryRecord = records.get(entryModuleId);
|
|
106
|
+
if (!entryRecord)
|
|
107
|
+
moduleError('AMX5001', `Entry module '${entryModuleId}' is missing`);
|
|
108
|
+
const states = new Map();
|
|
109
|
+
const ordered = [];
|
|
110
|
+
const prepared = new Map();
|
|
111
|
+
const sharedBaseUnits = new Map();
|
|
112
|
+
const visit = (moduleId, ancestry) => {
|
|
113
|
+
const state = states.get(moduleId);
|
|
114
|
+
if (state === 'visiting') {
|
|
115
|
+
const record = records.get(moduleId);
|
|
116
|
+
moduleError('AMX5003', `Import cycle detected: ${[...ancestry, moduleId].join(' -> ')}`, undefined, record.input.sourcePath);
|
|
117
|
+
}
|
|
118
|
+
const existing = prepared.get(moduleId);
|
|
119
|
+
if (existing)
|
|
120
|
+
return existing;
|
|
121
|
+
const record = records.get(moduleId);
|
|
122
|
+
if (!record)
|
|
123
|
+
moduleError('AMX5001', `Resolved module '${moduleId}' is missing`);
|
|
124
|
+
states.set(moduleId, 'visiting');
|
|
125
|
+
const dependencies = new Map();
|
|
126
|
+
const specifiers = new Map();
|
|
127
|
+
const usedImportPaths = new Set();
|
|
128
|
+
for (const statement of record.statements) {
|
|
129
|
+
if (statement.type !== 'importDeclaration')
|
|
130
|
+
continue;
|
|
131
|
+
const dependencyId = record.importMappings.get(statement.path);
|
|
132
|
+
if (!dependencyId) {
|
|
133
|
+
moduleError('AMX5001', `Import '${statement.path}' has no resolved module`, statement.pathSource, record.input.sourcePath);
|
|
134
|
+
}
|
|
135
|
+
if (!records.has(dependencyId)) {
|
|
136
|
+
moduleError('AMX5001', `Resolved module '${dependencyId}' is missing`, statement.pathSource, record.input.sourcePath);
|
|
137
|
+
}
|
|
138
|
+
usedImportPaths.add(statement.path);
|
|
139
|
+
const dependency = visit(dependencyId, [...ancestry, moduleId]);
|
|
140
|
+
dependencies.set(statement.path, dependency);
|
|
141
|
+
const relativePath = path.posix.relative(path.posix.dirname(record.input.outputPath), dependency.input.outputPath);
|
|
142
|
+
specifiers.set(statement.path, relativePath.startsWith('.') ? relativePath : `./${relativePath}`);
|
|
143
|
+
}
|
|
144
|
+
for (const importPath of record.importMappings.keys()) {
|
|
145
|
+
if (!usedImportPaths.has(importPath)) {
|
|
146
|
+
moduleError('AMX5001', `Resolved import '${importPath}' is not declared by the source`, undefined, record.input.sourcePath);
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
const imported = importedContext(record.input, record.statements, dependencies);
|
|
150
|
+
const check = checkDocument(record.document, record.input.sourcePath, {
|
|
151
|
+
...imported,
|
|
152
|
+
baseUnits: sharedBaseUnits,
|
|
153
|
+
moduleIdentity: record.input.outputPath,
|
|
154
|
+
isEntryModule: moduleId === entryModuleId
|
|
155
|
+
});
|
|
156
|
+
const module = {
|
|
157
|
+
input: record.input,
|
|
158
|
+
document: record.document,
|
|
159
|
+
statements: record.statements,
|
|
160
|
+
imports: dependencies,
|
|
161
|
+
importSpecifiers: specifiers,
|
|
162
|
+
check
|
|
163
|
+
};
|
|
164
|
+
prepared.set(moduleId, module);
|
|
165
|
+
states.set(moduleId, 'visited');
|
|
166
|
+
ordered.push(module);
|
|
167
|
+
return module;
|
|
168
|
+
};
|
|
169
|
+
const entry = visit(entryModuleId, []);
|
|
170
|
+
if (prepared.size !== records.size) {
|
|
171
|
+
const unreachable = [...records.keys()].filter(moduleId => !prepared.has(moduleId));
|
|
172
|
+
const firstUnreachable = records.get(unreachable[0]);
|
|
173
|
+
moduleError('AMX5001', `Unreachable modules in resolved graph: ${unreachable.join(', ')}`, undefined, firstUnreachable?.input.sourcePath);
|
|
174
|
+
}
|
|
175
|
+
return { entry, dependencyOrder: ordered };
|
|
176
|
+
}
|
|
177
|
+
export function sourceDiagnostic(error, fallbackFile) {
|
|
178
|
+
if (error instanceof AmxError) {
|
|
179
|
+
return {
|
|
180
|
+
code: error.code,
|
|
181
|
+
message: error.message,
|
|
182
|
+
file: error.file ?? fallbackFile,
|
|
183
|
+
...(error.line === undefined ? {} : { line: error.line }),
|
|
184
|
+
...(error.column === undefined ? {} : { column: error.column })
|
|
185
|
+
};
|
|
186
|
+
}
|
|
187
|
+
const sourceError = error instanceof Error
|
|
188
|
+
? error
|
|
189
|
+
: undefined;
|
|
190
|
+
return {
|
|
191
|
+
message: error instanceof Error ? error.message : String(error),
|
|
192
|
+
...(sourceError?.code === undefined ? {} : { code: sourceError.code }),
|
|
193
|
+
...((sourceError?.file ?? fallbackFile) ? { file: sourceError?.file ?? fallbackFile } : {}),
|
|
194
|
+
...(sourceError?.line === undefined ? {} : { line: sourceError.line }),
|
|
195
|
+
...(sourceError?.column === undefined ? {} : { column: sourceError.column })
|
|
196
|
+
};
|
|
197
|
+
}
|
|
198
|
+
export function importsOf(module) {
|
|
199
|
+
return module.statements.filter((statement) => statement.type === 'importDeclaration');
|
|
200
|
+
}
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
import { emitModule, LoweringFailure, measurementVectorKey } from './emit';
|
|
2
|
+
import { prepareGraph, sourceDiagnostic } from './graph';
|
|
3
|
+
function canonicalMeasurementDimensionIds(modules) {
|
|
4
|
+
const representatives = new Map();
|
|
5
|
+
for (const module of modules) {
|
|
6
|
+
for (const dimension of module.check.dimensions.values()) {
|
|
7
|
+
const key = measurementVectorKey(dimension.vector);
|
|
8
|
+
const current = representatives.get(key);
|
|
9
|
+
if (!current || dimension.moduleIdentity < current.moduleIdentity
|
|
10
|
+
|| dimension.moduleIdentity === current.moduleIdentity && dimension.declarationName < current.declarationName) {
|
|
11
|
+
representatives.set(key, dimension);
|
|
12
|
+
}
|
|
13
|
+
}
|
|
14
|
+
}
|
|
15
|
+
return new Map([...representatives].map(([key, dimension]) => [
|
|
16
|
+
key,
|
|
17
|
+
JSON.stringify([dimension.moduleIdentity, dimension.declarationName])
|
|
18
|
+
]));
|
|
19
|
+
}
|
|
20
|
+
export function transpileDocument(input) {
|
|
21
|
+
let graph;
|
|
22
|
+
try {
|
|
23
|
+
graph = prepareGraph(input.entryModuleId, input.modules);
|
|
24
|
+
}
|
|
25
|
+
catch (error) {
|
|
26
|
+
return { ok: false, diagnostics: [sourceDiagnostic(error)] };
|
|
27
|
+
}
|
|
28
|
+
const measurementDimensionIds = canonicalMeasurementDimensionIds(graph.dependencyOrder);
|
|
29
|
+
const generated = [];
|
|
30
|
+
for (const module of graph.dependencyOrder) {
|
|
31
|
+
try {
|
|
32
|
+
generated.push({
|
|
33
|
+
moduleId: module.input.moduleId,
|
|
34
|
+
sourcePath: module.input.sourcePath,
|
|
35
|
+
outputPath: module.input.outputPath,
|
|
36
|
+
code: emitModule(module, module === graph.entry, measurementDimensionIds)
|
|
37
|
+
});
|
|
38
|
+
}
|
|
39
|
+
catch (error) {
|
|
40
|
+
const diagnostic = error instanceof LoweringFailure
|
|
41
|
+
? {
|
|
42
|
+
message: error.message,
|
|
43
|
+
file: module.input.sourcePath,
|
|
44
|
+
...(error.line === undefined ? {} : { line: error.line }),
|
|
45
|
+
...(error.column === undefined ? {} : { column: error.column })
|
|
46
|
+
}
|
|
47
|
+
: sourceDiagnostic(error, module.input.sourcePath);
|
|
48
|
+
return { ok: false, diagnostics: [diagnostic] };
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
return { ok: true, entryModuleId: input.entryModuleId, modules: generated };
|
|
52
|
+
}
|