@nova-energy/openamx 0.11.0 → 0.14.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.
@@ -0,0 +1,180 @@
1
+ import { syntaxError } from '../diagnostics/errors';
2
+ import { parseExpression } from './parseExpression';
3
+ import { parseStatements } from './parseStatements';
4
+ export function parseBracedIfExpression(text, source) {
5
+ const blocks = readIfBlocks(text, source);
6
+ if (!blocks.alternate)
7
+ syntaxError("Expression-form 'if' requires an 'else' block", source);
8
+ return {
9
+ type: 'bracedIfExpression',
10
+ test: parseExpression(blocks.condition, offsetLocation(text, text.indexOf(blocks.condition), source)),
11
+ consequent: parseStatements(blocks.consequent, blocks.consequentSource, { allowReturn: true }),
12
+ alternate: parseStatements(blocks.alternate, blocks.alternateSource, { allowReturn: true }),
13
+ consequentSource: blocks.consequentClosingSource,
14
+ alternateSource: blocks.alternateClosingSource,
15
+ source
16
+ };
17
+ }
18
+ export function parseBracedIfStatement(text, source, context = {}) {
19
+ const blocks = readIfBlocks(text, source);
20
+ const statementText = text.slice(0, blocks.endOffset);
21
+ return {
22
+ statement: {
23
+ type: 'bracedIfStatement',
24
+ test: parseExpression(blocks.condition, offsetLocation(text, text.indexOf(blocks.condition), source)),
25
+ consequent: parseStatements(blocks.consequent, blocks.consequentSource, context),
26
+ ...(blocks.alternate === undefined ? {} : { alternate: parseStatements(blocks.alternate, blocks.alternateSource, context) }),
27
+ consequentSource: blocks.consequentClosingSource,
28
+ ...(blocks.alternateClosingSource ? { alternateSource: blocks.alternateClosingSource } : {}),
29
+ source
30
+ },
31
+ lineCount: statementText.split(/\r?\n/).length
32
+ };
33
+ }
34
+ export function findBracedIfExpressionEnd(text, start) {
35
+ if (!/^if\b/.test(text.slice(start)))
36
+ return undefined;
37
+ const firstOpen = findFirstBlockOpen(text, start + 2);
38
+ if (firstOpen === undefined)
39
+ return undefined;
40
+ if (containsTopLevelWord(text, start + 2, firstOpen, 'then'))
41
+ return undefined;
42
+ const firstClose = matchingBrace(text, firstOpen);
43
+ if (firstClose === undefined)
44
+ return undefined;
45
+ let cursor = skipWhitespace(text, firstClose + 1);
46
+ if (!text.startsWith('else', cursor) || /[A-Za-z0-9_]/.test(text[cursor + 4] ?? ''))
47
+ return firstClose;
48
+ cursor = skipWhitespace(text, cursor + 4);
49
+ if (text[cursor] !== '{')
50
+ return firstClose;
51
+ return matchingBrace(text, cursor);
52
+ }
53
+ function containsTopLevelWord(text, start, end, word) {
54
+ let depth = 0;
55
+ for (let index = start; index < end; index++) {
56
+ const character = text[index];
57
+ if (character === '"' || character === "'") {
58
+ const close = quotedEnd(text, index);
59
+ if (close === undefined)
60
+ return false;
61
+ index = close;
62
+ }
63
+ else if (character === '(' || character === '[') {
64
+ depth++;
65
+ }
66
+ else if (character === ')' || character === ']') {
67
+ depth--;
68
+ }
69
+ else if (depth === 0 && text.startsWith(word, index)
70
+ && !/[A-Za-z0-9_]/.test(text[index - 1] ?? '')
71
+ && !/[A-Za-z0-9_]/.test(text[index + word.length] ?? '')) {
72
+ return true;
73
+ }
74
+ }
75
+ return false;
76
+ }
77
+ function readIfBlocks(text, source) {
78
+ const firstOpen = findFirstBlockOpen(text, 2);
79
+ if (firstOpen === undefined)
80
+ syntaxError("Expected '{' after braced 'if' condition", source);
81
+ const firstClose = matchingBrace(text, firstOpen);
82
+ if (firstClose === undefined)
83
+ syntaxError("Unclosed 'if' block", source);
84
+ const condition = text.slice(2, firstOpen).trim();
85
+ if (!condition)
86
+ syntaxError("Expected condition after 'if'", source);
87
+ const consequentBody = text.slice(firstOpen + 1, firstClose);
88
+ const consequentSource = offsetLocation(text, firstOpen + 1, source);
89
+ const consequentClosingSource = offsetLocation(text, firstClose, source);
90
+ let cursor = skipWhitespace(text, firstClose + 1);
91
+ if (!text.startsWith('else', cursor) || /[A-Za-z0-9_]/.test(text[cursor + 4] ?? '')) {
92
+ return {
93
+ condition,
94
+ consequent: consequentBody,
95
+ consequentSource,
96
+ consequentClosingSource,
97
+ endOffset: firstClose + 1
98
+ };
99
+ }
100
+ cursor = skipWhitespace(text, cursor + 4);
101
+ if (text[cursor] !== '{')
102
+ syntaxError("Expected '{' after 'else'", offsetLocation(text, cursor, source));
103
+ const alternateClose = matchingBrace(text, cursor);
104
+ if (alternateClose === undefined)
105
+ syntaxError("Unclosed 'else' block", offsetLocation(text, cursor, source));
106
+ return {
107
+ condition,
108
+ consequent: consequentBody,
109
+ alternate: text.slice(cursor + 1, alternateClose),
110
+ consequentSource,
111
+ alternateSource: offsetLocation(text, cursor + 1, source),
112
+ consequentClosingSource,
113
+ alternateClosingSource: offsetLocation(text, alternateClose, source),
114
+ endOffset: alternateClose + 1
115
+ };
116
+ }
117
+ function findFirstBlockOpen(text, start) {
118
+ let depth = 0;
119
+ for (let index = start; index < text.length; index++) {
120
+ const character = text[index];
121
+ if (character === '"' || character === "'") {
122
+ const close = quotedEnd(text, index);
123
+ if (close === undefined)
124
+ return undefined;
125
+ index = close;
126
+ }
127
+ else if (character === '(' || character === '[') {
128
+ depth++;
129
+ }
130
+ else if (character === ')' || character === ']') {
131
+ depth--;
132
+ }
133
+ else if (character === '{' && depth === 0) {
134
+ return index;
135
+ }
136
+ }
137
+ return undefined;
138
+ }
139
+ function matchingBrace(text, open) {
140
+ let depth = 0;
141
+ for (let index = open; index < text.length; index++) {
142
+ const character = text[index];
143
+ if (character === '"' || character === "'") {
144
+ const close = quotedEnd(text, index);
145
+ if (close === undefined)
146
+ return undefined;
147
+ index = close;
148
+ }
149
+ else if (character === '{') {
150
+ depth++;
151
+ }
152
+ else if (character === '}' && --depth === 0) {
153
+ return index;
154
+ }
155
+ }
156
+ return undefined;
157
+ }
158
+ function quotedEnd(text, start) {
159
+ const quote = text[start];
160
+ for (let index = start + 1; index < text.length; index++) {
161
+ if (text[index] === '\\')
162
+ index++;
163
+ else if (text[index] === quote)
164
+ return index;
165
+ }
166
+ return undefined;
167
+ }
168
+ function skipWhitespace(text, start) {
169
+ let index = start;
170
+ while (index < text.length && /\s/.test(text[index]))
171
+ index++;
172
+ return index;
173
+ }
174
+ function offsetLocation(text, offset, source) {
175
+ const before = text.slice(0, offset).split(/\r?\n/);
176
+ return {
177
+ line: (source?.line ?? 1) + before.length - 1,
178
+ column: before.length === 1 ? (source?.column ?? 1) + before[0].length : before.at(-1).length + 1
179
+ };
180
+ }
@@ -1,5 +1,6 @@
1
1
  import { parseExpression } from './parseExpression';
2
2
  import { parseForStatement } from './parseFor';
3
+ import { parseBracedIfStatement } from './parseIf';
3
4
  import { AmxError, staticError, syntaxError } from '../diagnostics/errors';
4
5
  import { findStringLiteralEnd, withoutStringLiterals } from './stringScanner';
5
6
  /** Parse executable AMX statements while preserving original-document locations. */
@@ -33,7 +34,7 @@ export function parseStatements(body, start = { line: 1, column: 1 }, context =
33
34
  continue;
34
35
  }
35
36
  let exported = false;
36
- const exportMatch = rawLine.match(/^(\s*)export(\s+)(type|fn|let|table|chart|dimension|unit)\b/);
37
+ const exportMatch = rawLine.match(/^(\s*)export(\s+)(type|enum|fn|let|table|chart|dimension|unit)\b/);
37
38
  if (exportMatch) {
38
39
  if (context.allowFor === false && exportMatch[3] !== 'table' && exportMatch[3] !== 'chart'
39
40
  && exportMatch[3] !== 'dimension' && exportMatch[3] !== 'unit')
@@ -104,6 +105,54 @@ export function parseStatements(body, start = { line: 1, column: 1 }, context =
104
105
  statements.push(input);
105
106
  continue;
106
107
  }
108
+ if (/^\s*enum\b/.test(rawLine)) {
109
+ if (context.allowFor === false)
110
+ throw new Error(`Enum declarations cannot occur in loops at ${source.line}:${source.column}`);
111
+ const header = rawLine.match(/^\s*enum\s+([A-Za-z][A-Za-z0-9_]*)\s*=\s*\{\s*$/);
112
+ if (!header)
113
+ syntaxError('Invalid enum declaration', source);
114
+ const members = [];
115
+ let closed = false;
116
+ let closingSource;
117
+ while (++i < lines.length) {
118
+ const memberLine = lines[i];
119
+ if (/^\s*}\s*$/.test(memberLine)) {
120
+ closed = true;
121
+ closingSource = { line: start.line + i, column: memberLine.indexOf('}') + 1 };
122
+ break;
123
+ }
124
+ if (!memberLine.trim())
125
+ continue;
126
+ const match = memberLine.match(/^\s*([A-Za-z][A-Za-z0-9_]*)(?:\s*=\s*(.+?))?\s*,?\s*$/);
127
+ const memberColumn = match
128
+ ? memberLine.indexOf(match[1]) + 1
129
+ : memberLine.length - memberLine.trimStart().length + 1;
130
+ const memberSource = { line: start.line + i, column: memberColumn };
131
+ if (!match)
132
+ syntaxError('Invalid enum member', memberSource);
133
+ let value;
134
+ let valueSource;
135
+ if (match[2]) {
136
+ const valueText = match[2].replace(/,\s*$/, '').trim();
137
+ const valueColumn = memberLine.indexOf(valueText, memberColumn - 1) + 1;
138
+ valueSource = { line: memberSource.line, column: valueColumn };
139
+ value = parseExpression(valueText, valueSource);
140
+ }
141
+ members.push({ name: match[1], nameSource: memberSource, ...(value ? { value, valueSource } : {}) });
142
+ }
143
+ if (!closed)
144
+ syntaxError('Unclosed enum declaration', source);
145
+ statements.push({
146
+ type: 'enumDeclaration',
147
+ name: header[1],
148
+ nameSource: { line: source.line, column: rawLine.indexOf(header[1]) + 1 },
149
+ members,
150
+ closingSource,
151
+ ...(exported ? { exported: true } : {}),
152
+ source
153
+ });
154
+ continue;
155
+ }
107
156
  function parseDeclarationExpression(rawLine, expressionText, source) {
108
157
  const offset = rawLine.indexOf(expressionText);
109
158
  try {
@@ -118,6 +167,12 @@ export function parseStatements(body, start = { line: 1, column: 1 }, context =
118
167
  });
119
168
  }
120
169
  }
170
+ if (/^\s*diagram\b/.test(rawLine)) {
171
+ const parsed = parseDiagramDeclaration(lines, i, source);
172
+ statements.push(parsed.statement);
173
+ i = parsed.endIndex;
174
+ continue;
175
+ }
121
176
  if (/^\s*(table|chart)\b/.test(rawLine)) {
122
177
  const parsed = parseVisualization(lines, i, source, exported);
123
178
  statements.push(parsed.statement);
@@ -148,9 +203,16 @@ export function parseStatements(body, start = { line: 1, column: 1 }, context =
148
203
  if (/^\s*type\b/.test(rawLine)) {
149
204
  if (context.allowFor === false)
150
205
  throw new Error(`Type declarations cannot occur in loops at ${source.line}:${source.column}`);
151
- const header = rawLine.match(/^\s*type\s+([A-Za-z][A-Za-z0-9_]*)\s*\{\s*$/);
206
+ const header = rawLine.match(/^\s*type\s+([A-Za-z][A-Za-z0-9_]*)(?:\s+extends\s+([A-Za-z][A-Za-z0-9_]*(?:\s*,\s*[A-Za-z][A-Za-z0-9_]*)*))?\s*\{\s*$/);
152
207
  if (!header)
153
208
  throw new Error(`Invalid type declaration at ${source.line}:${source.column}`);
209
+ let parentSearchFrom = rawLine.indexOf('extends') + 'extends'.length;
210
+ const parents = header[2] ? header[2].split(',').map(rawName => {
211
+ const name = rawName.trim();
212
+ const parentIndex = rawLine.indexOf(name, parentSearchFrom);
213
+ parentSearchFrom = parentIndex + name.length;
214
+ return { name, source: { line: source.line, column: parentIndex + 1 } };
215
+ }) : undefined;
154
216
  const fields = [];
155
217
  let closed = false;
156
218
  while (++i < lines.length) {
@@ -161,21 +223,43 @@ export function parseStatements(body, start = { line: 1, column: 1 }, context =
161
223
  }
162
224
  if (!fieldLine.trim())
163
225
  continue;
164
- const match = fieldLine.match(/^\s*([A-Za-z][A-Za-z0-9_]*)(\?)?\s*:\s*([A-Za-z][A-Za-z0-9_]*(?:(?:\[\])|\?)*)\s*(?:=\s*(.+))?\s*$/);
165
- const fieldSource = { line: start.line + i, column: fieldLine.length - fieldLine.trimStart().length + 1 };
226
+ const match = fieldLine.match(/^\s*(?:(override)\s+)?([A-Za-z][A-Za-z0-9_]*)(\?)?\s*:\s*([A-Za-z][A-Za-z0-9_]*(?:(?:\[\])|\?)*)\s*(?:=\s*(.+))?\s*$/);
227
+ const fieldColumn = match
228
+ ? fieldLine.indexOf(match[2], match[1] ? fieldLine.indexOf(match[1]) + match[1].length : 0) + 1
229
+ : fieldLine.length - fieldLine.trimStart().length + 1;
230
+ const fieldSource = { line: start.line + i, column: fieldColumn };
166
231
  if (!match)
167
232
  throw new Error(`Invalid record field at ${fieldSource.line}:${fieldSource.column}`);
168
- fields.push({ name: match[1], optional: !!match[2], annotation: parseTypeReference(match[3], fieldSource),
169
- ...(match[4] ? { defaultExpression: parseExpression(match[4], { line: fieldSource.line, column: fieldLine.indexOf(match[4]) + 1 }) } : {}), source: fieldSource });
233
+ const overrideSource = match[1]
234
+ ? { line: fieldSource.line, column: fieldLine.indexOf(match[1]) + 1 }
235
+ : undefined;
236
+ fields.push({ name: match[2], optional: !!match[3], annotation: parseTypeReference(match[4], fieldSource),
237
+ ...(match[1] ? { override: true, overrideSource } : {}),
238
+ ...(match[5] ? { defaultExpression: parseExpression(match[5], { line: fieldSource.line, column: fieldLine.indexOf(match[5]) + 1 }) } : {}), source: fieldSource });
170
239
  }
171
240
  if (!closed)
172
241
  throw new Error(`Unclosed type declaration at ${source.line}:${source.column}`);
173
- statements.push({ type: 'typeDeclaration', name: header[1], fields, ...(exported ? { exported } : {}), source });
242
+ statements.push({
243
+ type: 'typeDeclaration',
244
+ name: header[1],
245
+ nameSource: { line: source.line, column: rawLine.indexOf(header[1]) + 1 },
246
+ fields,
247
+ ...(parents ? { parents } : {}),
248
+ ...(exported ? { exported } : {}),
249
+ source
250
+ });
174
251
  continue;
175
252
  }
176
253
  if (context.allowFor === false && containsForExpression(rawLine)) {
177
254
  throw new Error(`Nested loops are unsupported at ${source.line}:${source.column}`);
178
255
  }
256
+ if (/^\s*if\b/.test(rawLine)) {
257
+ const collected = collectDelimitedExpression(lines, i, rawLine.trimStart());
258
+ const parsed = parseBracedIfStatement(collected.text, source, context);
259
+ statements.push(parsed.statement);
260
+ i += parsed.lineCount - 1;
261
+ continue;
262
+ }
179
263
  if (/^\s*for\b/.test(rawLine)) {
180
264
  if (context.allowFor === false) {
181
265
  throw new Error(`Nested loops are unsupported at ${source.line}:${source.column}`);
@@ -437,6 +521,147 @@ function parseVisualization(lines, startIndex, source, exported) {
437
521
  endIndex
438
522
  };
439
523
  }
524
+ function parseDiagramDeclaration(lines, startIndex, source) {
525
+ const headerLine = lines[startIndex];
526
+ const header = headerLine.match(/^\s*diagram\s+([A-Za-z][A-Za-z0-9_]*)\s*\{\s*$/);
527
+ if (!header)
528
+ syntaxError('Invalid diagram declaration', source);
529
+ const name = header[1];
530
+ const statement = {
531
+ type: 'diagramDeclaration',
532
+ name,
533
+ nameSource: { line: source.line, column: headerLine.indexOf(name) + 1 },
534
+ properties: [],
535
+ times: [],
536
+ elements: [],
537
+ source
538
+ };
539
+ let index = startIndex + 1;
540
+ while (index < lines.length) {
541
+ const line = lines[index];
542
+ if (/^\s*}\s*$/.test(line))
543
+ return { statement, endIndex: index };
544
+ if (!line.trim()) {
545
+ index++;
546
+ continue;
547
+ }
548
+ const lineSource = {
549
+ line: source.line + index - startIndex,
550
+ column: line.length - line.trimStart().length + 1
551
+ };
552
+ const timeHeader = line.match(/^\s*time\s+([A-Za-z][A-Za-z0-9_]*)\s+from\s+(.+)$/);
553
+ if (timeHeader) {
554
+ const tail = timeHeader[2];
555
+ const tailOffset = line.indexOf(tail);
556
+ const durationKeyword = findTopLevelKeyword(tail, 'duration');
557
+ if (!durationKeyword)
558
+ syntaxError('Invalid diagram time declaration', lineSource);
559
+ const bounds = tail.slice(0, durationKeyword.start).trim();
560
+ const toKeyword = findTopLevelKeyword(bounds, 'to');
561
+ if (!toKeyword)
562
+ syntaxError('Invalid diagram time declaration', lineSource);
563
+ const fromText = bounds.slice(0, toKeyword.start).trim();
564
+ const toText = bounds.slice(toKeyword.end).trim();
565
+ const durationText = tail.slice(durationKeyword.end).trim();
566
+ if (!fromText || !toText || !durationText)
567
+ syntaxError('Invalid diagram time declaration', lineSource);
568
+ const expressionSource = (offset) => locationAtOffset(tail, offset, {
569
+ line: lineSource.line,
570
+ column: tailOffset + 1
571
+ });
572
+ const fromSource = expressionSource(tail.indexOf(fromText));
573
+ const toSource = expressionSource(tail.indexOf(toText, toKeyword.end));
574
+ const durationSource = expressionSource(tail.indexOf(durationText, durationKeyword.end));
575
+ const time = {
576
+ name: timeHeader[1],
577
+ nameSource: { line: lineSource.line, column: line.indexOf(timeHeader[1]) + 1 },
578
+ from: parseExpression(fromText, fromSource),
579
+ fromText,
580
+ fromSource,
581
+ to: parseExpression(toText, toSource),
582
+ toText,
583
+ toSource,
584
+ duration: parseExpression(durationText, durationSource),
585
+ durationText,
586
+ durationSource,
587
+ source: lineSource
588
+ };
589
+ statement.times.push(time);
590
+ index++;
591
+ continue;
592
+ }
593
+ const elementHeader = line.match(/^\s*([A-Za-z][A-Za-z0-9_]*)\s+([A-Za-z][A-Za-z0-9_]*)\s*\{\s*$/);
594
+ if (elementHeader) {
595
+ const primitive = elementHeader[1];
596
+ const elementName = elementHeader[2];
597
+ const element = {
598
+ type: 'diagramElement',
599
+ primitive,
600
+ name: elementName,
601
+ nameSource: { line: lineSource.line, column: line.indexOf(elementName) + 1 },
602
+ properties: [],
603
+ source: { line: lineSource.line, column: lineSource.column }
604
+ };
605
+ index++;
606
+ let elementClosed = false;
607
+ while (index < lines.length) {
608
+ const propertyLine = lines[index];
609
+ if (/^\s*}\s*$/.test(propertyLine)) {
610
+ elementClosed = true;
611
+ index++;
612
+ break;
613
+ }
614
+ if (!propertyLine.trim()) {
615
+ index++;
616
+ continue;
617
+ }
618
+ const property = parseDiagramProperty(lines, index, source.line + index - startIndex);
619
+ element.properties.push(property.node);
620
+ index += property.lineCount;
621
+ }
622
+ if (!elementClosed)
623
+ syntaxError('Unclosed diagram element', element.source);
624
+ statement.elements.push(element);
625
+ continue;
626
+ }
627
+ const property = parseDiagramProperty(lines, index, source.line + index - startIndex);
628
+ statement.properties.push(property.node);
629
+ index += property.lineCount;
630
+ }
631
+ syntaxError('Unclosed diagram declaration', source);
632
+ }
633
+ function parseDiagramProperty(lines, index, lineNumber) {
634
+ const line = lines[index];
635
+ const match = line.match(/^\s*([A-Za-z][A-Za-z0-9_]*)\s*:\s*(.*)$/);
636
+ const source = {
637
+ line: lineNumber,
638
+ column: line.length - line.trimStart().length + 1
639
+ };
640
+ if (!match)
641
+ syntaxError('Invalid diagram property', source);
642
+ const name = match[1];
643
+ const initialValue = match[2];
644
+ if (!initialValue.trim())
645
+ syntaxError('Invalid diagram property value', source);
646
+ const collected = collectDelimitedExpression(lines, index, initialValue);
647
+ const rawValue = collected.text.trim();
648
+ const valueOffset = line.indexOf(initialValue) + initialValue.indexOf(initialValue.trim());
649
+ const valueSource = locationAtOffset(rawValue, 0, {
650
+ line: source.line,
651
+ column: valueOffset + 1
652
+ });
653
+ return {
654
+ node: {
655
+ name,
656
+ expression: parseExpression(rawValue, valueSource),
657
+ rawValue,
658
+ nameSource: { line: source.line, column: line.indexOf(name) + 1 },
659
+ valueSource,
660
+ source
661
+ },
662
+ lineCount: collected.lineCount
663
+ };
664
+ }
440
665
  export function parseTypeReference(text, source) {
441
666
  const name = text.match(/^[A-Za-z][A-Za-z0-9_]*/)?.[0];
442
667
  if (!name)