@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,110 @@
1
+ export function isMeasurement(value) {
2
+ return !!value && typeof value === 'object'
3
+ && value.__amxMeasurement === true
4
+ && typeof value.value === 'number'
5
+ && !!value.unit;
6
+ }
7
+ function vectorRecord(vector) {
8
+ return Object.freeze(Object.fromEntries(vector));
9
+ }
10
+ function formatFactors(factors) {
11
+ const sorted = [...factors].filter(factor => factor.exponent !== 0)
12
+ .sort((left, right) => left.identity < right.identity ? -1 : left.identity > right.identity ? 1 : 0);
13
+ const numerator = sorted.filter(factor => factor.exponent > 0)
14
+ .map(factor => `${factor.name}${factor.exponent === 1 ? '' : ` ^ ${factor.exponent}`}`);
15
+ const denominator = sorted.filter(factor => factor.exponent < 0)
16
+ .map(factor => `${factor.name}${factor.exponent === -1 ? '' : ` ^ ${-factor.exponent}`}`);
17
+ return `${numerator.length ? numerator.join(' * ') : '1'}${denominator.length ? ` / ${denominator.join(' * ')}` : ''}`;
18
+ }
19
+ export function unitFromMetadata(unit) {
20
+ const factors = [{ identity: unit.identity, name: unit.name, exponent: 1 }];
21
+ return Object.freeze({
22
+ scale: unit.scale,
23
+ vector: vectorRecord(unit.vector),
24
+ factors: Object.freeze(factors),
25
+ text: unit.name
26
+ });
27
+ }
28
+ function combineFactors(left, right, multiplier) {
29
+ const factors = new Map();
30
+ for (const factor of left.factors)
31
+ factors.set(factor.identity, { ...factor });
32
+ for (const factor of right.factors) {
33
+ const current = factors.get(factor.identity);
34
+ factors.set(factor.identity, {
35
+ identity: factor.identity,
36
+ name: factor.name,
37
+ exponent: (current?.exponent ?? 0) + factor.exponent * multiplier
38
+ });
39
+ }
40
+ return [...factors.values()].filter(factor => factor.exponent !== 0);
41
+ }
42
+ function combineVectorRecords(left, right, multiplier) {
43
+ const vector = { ...left.vector };
44
+ for (const [identity, exponent] of Object.entries(right.vector)) {
45
+ const next = (vector[identity] ?? 0) + exponent * multiplier;
46
+ if (next)
47
+ vector[identity] = next;
48
+ else
49
+ delete vector[identity];
50
+ }
51
+ return vector;
52
+ }
53
+ export function composeUnits(left, right, divide = false) {
54
+ const multiplier = divide ? -1 : 1;
55
+ const factors = combineFactors(left, right, multiplier);
56
+ return Object.freeze({
57
+ scale: divide ? left.scale / right.scale : left.scale * right.scale,
58
+ vector: Object.freeze(combineVectorRecords(left, right, multiplier)),
59
+ factors: Object.freeze(factors),
60
+ text: formatFactors(factors)
61
+ });
62
+ }
63
+ export function powerUnit(unit, exponent) {
64
+ const factors = unit.factors.map(factor => ({ ...factor, exponent: factor.exponent * exponent }))
65
+ .filter(factor => factor.exponent !== 0);
66
+ return Object.freeze({
67
+ scale: Math.pow(unit.scale, exponent),
68
+ vector: Object.freeze(Object.fromEntries(Object.entries(unit.vector)
69
+ .map(([identity, power]) => [identity, power * exponent]).filter(([, power]) => power !== 0))),
70
+ factors: Object.freeze(factors),
71
+ text: formatFactors(factors)
72
+ });
73
+ }
74
+ export function measurement(value, unit) {
75
+ return Object.freeze({ __amxMeasurement: true, value, unit });
76
+ }
77
+ export function canonicalUnit(vector, registry) {
78
+ const factors = [];
79
+ for (const [identity, exponent] of [...vector].sort(([left], [right]) => left < right ? -1 : left > right ? 1 : 0)) {
80
+ const base = registry.baseUnits.get(identity);
81
+ if (!base)
82
+ throw new Error(`No visible canonical base unit for dimension identity ${identity}`);
83
+ factors.push({ identity: base.identity, name: base.name, exponent });
84
+ }
85
+ return Object.freeze({
86
+ scale: 1,
87
+ vector: vectorRecord(vector),
88
+ factors: Object.freeze(factors),
89
+ text: formatFactors(factors)
90
+ });
91
+ }
92
+ export function sqrtMeasurement(value, registry) {
93
+ const vector = new Map();
94
+ for (const [identity, exponent] of Object.entries(value.unit.vector)) {
95
+ if (exponent % 2 !== 0)
96
+ throw new Error('sqrt requires integral measurement dimension exponents');
97
+ vector.set(identity, exponent / 2);
98
+ }
99
+ const physical = value.value * value.unit.scale;
100
+ const physicalRoot = Math.sqrt(physical);
101
+ if (!Number.isFinite(physicalRoot))
102
+ return measurement(physicalRoot, canonicalUnit(vector, registry));
103
+ const requestedScale = Math.sqrt(value.unit.scale);
104
+ const declared = [...registry.units.values()].find(unit => unit.scale === requestedScale && unit.vector.size === vector.size
105
+ && [...vector].every(([identity, exponent]) => unit.vector.get(identity) === exponent));
106
+ if (declared)
107
+ return measurement(physicalRoot / declared.scale, unitFromMetadata(declared));
108
+ const unit = canonicalUnit(vector, registry);
109
+ return measurement(physicalRoot, unit);
110
+ }
@@ -0,0 +1,279 @@
1
+ import * as path from 'path';
2
+ import * as fs from 'fs';
3
+ import { parseDocument, parseDocumentText } from '../parser/parseDocument';
4
+ import { checkDocument } from '../typechecker/checkDocument';
5
+ import { evaluateStatements } from './evaluateExpression';
6
+ import { Environment } from './environment';
7
+ import { AmxError, moduleError, staticError, throwInputErrors } from '../diagnostics/errors';
8
+ import { describeInputSchema, loadInputValues, validateInputText } from './inputData';
9
+ import { describeOutputSchemas, prepareOutputs } from './outputData';
10
+ function flattenStatements(doc) {
11
+ const statements = [];
12
+ for (const node of doc.nodes) {
13
+ if (node.type === 'executableCodeBlock')
14
+ statements.push(...node.statements);
15
+ }
16
+ return statements;
17
+ }
18
+ function validateImportPathSyntax(importNode, file) {
19
+ const importPath = importNode.path;
20
+ if (!(importPath.startsWith('./') || importPath.startsWith('../'))) {
21
+ moduleError('AMX5001', `Import path '${importPath}' must be relative and start with './' or '../'`, importNode.pathSource, file);
22
+ }
23
+ if (importPath.includes('\\')) {
24
+ moduleError('AMX5001', `Import path '${importPath}' must use '/' separators`, importNode.pathSource, file);
25
+ }
26
+ if (!importPath.endsWith('.amx')) {
27
+ moduleError('AMX5001', `Import path '${importPath}' must end with the exact lowercase '.amx' suffix`, importNode.pathSource, file);
28
+ }
29
+ if (path.isAbsolute(importPath)) {
30
+ moduleError('AMX5001', `Import path '${importPath}' must be relative`, importNode.pathSource, file);
31
+ }
32
+ }
33
+ function realpathOrFail(absolutePath, code, message, sourceFile) {
34
+ try {
35
+ return fs.realpathSync(absolutePath);
36
+ }
37
+ catch {
38
+ moduleError(code, message, undefined, sourceFile);
39
+ }
40
+ }
41
+ /**
42
+ * Resolve, check, and evaluate the complete module graph reachable from `entryPath`,
43
+ * returning the entry module's document and final evaluated environment.
44
+ */
45
+ export async function loadEntryModule(entryPath, options = {}) {
46
+ const absoluteEntry = path.resolve(entryPath);
47
+ const realEntry = realpathOrFail(absoluteEntry, 'AMX5001', `Entry module '${entryPath}' could not be read`, entryPath);
48
+ const entryRoot = path.dirname(realEntry);
49
+ if (options.sourceOverlay) {
50
+ if (options.sourceOverlay.size > 100) {
51
+ moduleError('AMX5001', 'Source overlay exceeds the 100-module limit', undefined, entryPath);
52
+ }
53
+ for (const overlayPath of options.sourceOverlay.keys()) {
54
+ if (!path.isAbsolute(overlayPath)) {
55
+ moduleError('AMX5001', 'Source overlay paths must be canonical absolute paths', undefined, entryPath);
56
+ }
57
+ const canonicalOverlayPath = realpathOrFail(overlayPath, 'AMX5001', 'Source overlay module could not be read', entryPath);
58
+ const relativeToRoot = path.relative(entryRoot, canonicalOverlayPath);
59
+ if (canonicalOverlayPath !== overlayPath || relativeToRoot === '' || relativeToRoot.startsWith('..') || path.isAbsolute(relativeToRoot)) {
60
+ moduleError('AMX5001', 'Source overlay paths must be canonical and contained by the entry directory tree', undefined, entryPath);
61
+ }
62
+ }
63
+ }
64
+ const resolved = new Map();
65
+ const visiting = [];
66
+ const evaluationOrder = [];
67
+ const baseUnits = new Map();
68
+ async function visit(canonicalPath, viaImportSource) {
69
+ const existing = resolved.get(canonicalPath);
70
+ if (existing)
71
+ return existing;
72
+ const cycleIndex = visiting.indexOf(canonicalPath);
73
+ if (cycleIndex !== -1) {
74
+ const cycle = [...visiting.slice(cycleIndex), canonicalPath].map(p => path.relative(entryRoot, p) || path.basename(p));
75
+ moduleError('AMX5003', `Import cycle detected: ${cycle.join(' -> ')}`, viaImportSource?.pathSource, viaImportSource?.file);
76
+ }
77
+ visiting.push(canonicalPath);
78
+ let doc;
79
+ try {
80
+ const overlayText = options.sourceOverlay?.get(canonicalPath);
81
+ doc = canonicalPath === realEntry && options.entryText !== undefined
82
+ ? parseDocumentText(options.entryText)
83
+ : overlayText !== undefined
84
+ ? parseDocumentText(overlayText)
85
+ : await parseDocument(canonicalPath);
86
+ }
87
+ catch (error) {
88
+ if (error instanceof AmxError && (error.code === 'AMX3006' || error.code === 'AMX3008')) {
89
+ error.file ??= canonicalPath;
90
+ throw error;
91
+ }
92
+ const message = error instanceof Error ? error.message : String(error);
93
+ visiting.pop();
94
+ return moduleError('AMX5001', `Failed to parse module '${canonicalPath}': ${message}`, undefined, canonicalPath);
95
+ }
96
+ const statements = flattenStatements(doc);
97
+ const localNames = new Set();
98
+ for (const statement of statements) {
99
+ if (statement.type === 'typeDeclaration' || statement.type === 'functionDeclaration' || statement.type === 'variableDeclaration' || statement.type === 'inputDeclaration'
100
+ || statement.type === 'tableDeclaration' || statement.type === 'chartDeclaration'
101
+ || statement.type === 'dimensionDeclaration' || statement.type === 'unitDeclaration') {
102
+ localNames.add(statement.name);
103
+ }
104
+ }
105
+ if (canonicalPath !== realEntry) {
106
+ const input = statements.find(statement => statement.type === 'inputDeclaration');
107
+ if (input?.type === 'inputDeclaration') {
108
+ staticError('AMX3005', 'Inputs may only be declared in the entry module', input.source, canonicalPath);
109
+ }
110
+ }
111
+ let sawNonImport = false;
112
+ for (const statement of statements) {
113
+ if (statement.type === 'importDeclaration') {
114
+ if (sawNonImport)
115
+ moduleError('AMX5001', 'Import declarations must precede all other executable items', statement.source, canonicalPath);
116
+ }
117
+ else {
118
+ sawNonImport = true;
119
+ }
120
+ }
121
+ const imports = statements.filter((s) => s.type === 'importDeclaration');
122
+ const localDimensionUnitNames = new Set(statements.flatMap(statement => statement.type === 'dimensionDeclaration' || statement.type === 'unitDeclaration' ? [statement.name] : []));
123
+ const importedTypes = new Map();
124
+ const importedFunctions = new Map();
125
+ const importedBindings = new Map();
126
+ const importedBindingSources = new Map();
127
+ const importedDimensions = new Map();
128
+ const importedUnits = new Map();
129
+ const importedNamesSeen = new Set();
130
+ const importedDimensionUnitNames = new Set();
131
+ for (const importNode of imports) {
132
+ validateImportPathSyntax(importNode, canonicalPath);
133
+ const importerDir = path.dirname(canonicalPath);
134
+ const targetAbsolute = path.resolve(importerDir, importNode.path);
135
+ const targetReal = realpathOrFail(targetAbsolute, 'AMX5001', `Module '${importNode.path}' could not be found`, canonicalPath);
136
+ const relativeToRoot = path.relative(entryRoot, targetReal);
137
+ if (relativeToRoot === '' || relativeToRoot.startsWith('..') || path.isAbsolute(relativeToRoot)) {
138
+ moduleError('AMX5001', `Module '${importNode.path}' resolves outside the entry directory tree`, importNode.pathSource, canonicalPath);
139
+ }
140
+ const dependency = await visit(targetReal, { pathSource: importNode.pathSource, file: canonicalPath });
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 (importedNamesSeen.has(importedName.name)) {
145
+ if (isDimensionOrUnit || importedDimensionUnitNames.has(importedName.name)) {
146
+ staticError('AMX3008', `Duplicate import of dimension/unit '${importedName.name}'`, importedName.source, canonicalPath);
147
+ }
148
+ moduleError('AMX5002', `Duplicate import of '${importedName.name}'`, importedName.source, canonicalPath);
149
+ }
150
+ importedNamesSeen.add(importedName.name);
151
+ if (localNames.has(importedName.name)) {
152
+ if (isDimensionOrUnit || localDimensionUnitNames.has(importedName.name)) {
153
+ staticError('AMX3008', `Imported dimension/unit '${importedName.name}' collides with a local declaration`, importedName.source, canonicalPath);
154
+ }
155
+ moduleError('AMX5002', `Imported name '${importedName.name}' collides with a local declaration`, importedName.source, canonicalPath);
156
+ }
157
+ if (dependency.checkResult.exportedTypes.has(importedName.name)) {
158
+ importedTypes.set(importedName.name, dependency.checkResult.exportedTypes.get(importedName.name));
159
+ }
160
+ else if (dependency.checkResult.exportedFunctions.has(importedName.name)) {
161
+ importedFunctions.set(importedName.name, dependency.checkResult.exportedFunctions.get(importedName.name));
162
+ }
163
+ else if (dependency.checkResult.exportedBindings.has(importedName.name)) {
164
+ importedBindings.set(importedName.name, dependency.checkResult.exportedBindings.get(importedName.name));
165
+ importedBindingSources.set(importedName.name, dependency.canonicalPath);
166
+ }
167
+ else if (dependency.checkResult.exportedDimensions.has(importedName.name)) {
168
+ importedDimensions.set(importedName.name, dependency.checkResult.exportedDimensions.get(importedName.name));
169
+ importedDimensionUnitNames.add(importedName.name);
170
+ }
171
+ else if (dependency.checkResult.exportedUnits.has(importedName.name)) {
172
+ importedUnits.set(importedName.name, dependency.checkResult.exportedUnits.get(importedName.name));
173
+ importedDimensionUnitNames.add(importedName.name);
174
+ }
175
+ else {
176
+ moduleError('AMX5002', `Module '${importNode.path}' does not export '${importedName.name}'`, importedName.source, canonicalPath);
177
+ }
178
+ }
179
+ }
180
+ const checkResult = checkDocument(doc, canonicalPath, {
181
+ types: importedTypes,
182
+ functions: importedFunctions,
183
+ bindings: importedBindings,
184
+ dimensions: importedDimensions,
185
+ units: importedUnits,
186
+ baseUnits,
187
+ moduleIdentity: canonicalPath,
188
+ isEntryModule: canonicalPath === realEntry
189
+ });
190
+ visiting.pop();
191
+ const record = { canonicalPath, doc, checkResult, importedTypes, importedFunctions, importedBindings, importedBindingSources, importedDimensions, importedUnits };
192
+ resolved.set(canonicalPath, record);
193
+ evaluationOrder.push(canonicalPath);
194
+ return record;
195
+ }
196
+ await visit(realEntry, undefined);
197
+ const entryRecord = resolved.get(realEntry);
198
+ const registry = {
199
+ dimensions: entryRecord.checkResult.dimensions,
200
+ units: entryRecord.checkResult.units,
201
+ baseUnits: entryRecord.checkResult.baseUnits
202
+ };
203
+ const entryStatements = flattenStatements(entryRecord.doc);
204
+ const inputDeclarations = entryStatements.filter(statement => statement.type === 'inputDeclaration');
205
+ const entryTypes = new Map(entryRecord.importedTypes);
206
+ for (const statement of entryStatements) {
207
+ if (statement.type === 'typeDeclaration')
208
+ entryTypes.set(statement.name, statement);
209
+ }
210
+ const outputs = prepareOutputs(options.outputMappings, entryRecord.checkResult.exportedBindings, entryTypes, options.reservedOutputPath, registry);
211
+ const outputSchemas = options.inputInspection || options.outputInspection
212
+ ? describeOutputSchemas(entryRecord.checkResult.exportedBindings, entryTypes, registry)
213
+ : undefined;
214
+ if (options.inputInspection) {
215
+ const declaration = inputDeclarations.find(input => input.name === options.inputInspection.name);
216
+ if (!declaration) {
217
+ throwInputErrors([{
218
+ code: 'AMX4001',
219
+ message: `Unknown logical input '${options.inputInspection.name}'`,
220
+ file: entryPath,
221
+ inputName: options.inputInspection.name
222
+ }]);
223
+ }
224
+ const validation = validateInputText(options.inputInspection.text, options.inputInspection.format, declaration, entryTypes, options.validation ?? 'aggregate', { file: entryPath }, registry);
225
+ return {
226
+ doc: entryRecord.doc,
227
+ env: new Environment(entryTypes, new Map(), registry),
228
+ outputs,
229
+ viewEmissions: [],
230
+ registry,
231
+ inputInspection: {
232
+ schema: describeInputSchema(declaration, entryTypes, registry),
233
+ valid: validation.diagnostics.length === 0,
234
+ diagnostics: validation.diagnostics,
235
+ outputs: outputSchemas ?? []
236
+ }
237
+ };
238
+ }
239
+ if (options.outputInspection) {
240
+ return { doc: entryRecord.doc, env: new Environment(entryTypes, new Map(), registry), outputs, viewEmissions: [], outputSchemas: outputSchemas ?? [], registry };
241
+ }
242
+ const inputValues = await loadInputValues(inputDeclarations, entryTypes, options.inputMappings, options.validation, entryPath, registry);
243
+ const evaluatedEnvironments = new Map();
244
+ for (const canonicalPath of evaluationOrder) {
245
+ const record = resolved.get(canonicalPath);
246
+ const env = new Environment(new Map(), new Map(), {
247
+ dimensions: record.checkResult.dimensions,
248
+ units: record.checkResult.units,
249
+ baseUnits: record.checkResult.baseUnits
250
+ });
251
+ env.validationMode = options.validation ?? 'aggregate';
252
+ for (const [name, typeDeclaration] of record.importedTypes)
253
+ env.recordTypes.set(name, typeDeclaration);
254
+ for (const [name, functionDeclaration] of record.importedFunctions)
255
+ env.functions.set(name, functionDeclaration);
256
+ for (const [name, bindingType] of record.checkResult.bindingTypes)
257
+ env.bindingTypes.set(name, bindingType);
258
+ for (const [name, sourcePath] of record.importedBindingSources) {
259
+ const dependencyEnv = evaluatedEnvironments.get(sourcePath);
260
+ const value = dependencyEnv.get(name);
261
+ env.set(name, value);
262
+ env.markImmutable(value);
263
+ }
264
+ if (canonicalPath === realEntry) {
265
+ for (const [name, value] of inputValues)
266
+ env.set(name, value);
267
+ }
268
+ for (let nodeIndex = 0; nodeIndex < record.doc.nodes.length; nodeIndex++) {
269
+ const node = record.doc.nodes[nodeIndex];
270
+ if (node.type === 'executableCodeBlock') {
271
+ env.currentDocumentNodeIndex = nodeIndex;
272
+ evaluateStatements(node.statements, env, canonicalPath);
273
+ }
274
+ }
275
+ evaluatedEnvironments.set(canonicalPath, env);
276
+ }
277
+ const entryEnv = evaluatedEnvironments.get(realEntry);
278
+ return { doc: resolved.get(realEntry).doc, env: entryEnv, outputs, viewEmissions: entryEnv.viewEmissions, registry };
279
+ }