@nova-energy/openamx 0.11.0 → 0.12.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 {
@@ -148,9 +197,16 @@ export function parseStatements(body, start = { line: 1, column: 1 }, context =
148
197
  if (/^\s*type\b/.test(rawLine)) {
149
198
  if (context.allowFor === false)
150
199
  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*$/);
200
+ 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
201
  if (!header)
153
202
  throw new Error(`Invalid type declaration at ${source.line}:${source.column}`);
203
+ let parentSearchFrom = rawLine.indexOf('extends') + 'extends'.length;
204
+ const parents = header[2] ? header[2].split(',').map(rawName => {
205
+ const name = rawName.trim();
206
+ const parentIndex = rawLine.indexOf(name, parentSearchFrom);
207
+ parentSearchFrom = parentIndex + name.length;
208
+ return { name, source: { line: source.line, column: parentIndex + 1 } };
209
+ }) : undefined;
154
210
  const fields = [];
155
211
  let closed = false;
156
212
  while (++i < lines.length) {
@@ -161,21 +217,43 @@ export function parseStatements(body, start = { line: 1, column: 1 }, context =
161
217
  }
162
218
  if (!fieldLine.trim())
163
219
  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 };
220
+ 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*$/);
221
+ const fieldColumn = match
222
+ ? fieldLine.indexOf(match[2], match[1] ? fieldLine.indexOf(match[1]) + match[1].length : 0) + 1
223
+ : fieldLine.length - fieldLine.trimStart().length + 1;
224
+ const fieldSource = { line: start.line + i, column: fieldColumn };
166
225
  if (!match)
167
226
  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 });
227
+ const overrideSource = match[1]
228
+ ? { line: fieldSource.line, column: fieldLine.indexOf(match[1]) + 1 }
229
+ : undefined;
230
+ fields.push({ name: match[2], optional: !!match[3], annotation: parseTypeReference(match[4], fieldSource),
231
+ ...(match[1] ? { override: true, overrideSource } : {}),
232
+ ...(match[5] ? { defaultExpression: parseExpression(match[5], { line: fieldSource.line, column: fieldLine.indexOf(match[5]) + 1 }) } : {}), source: fieldSource });
170
233
  }
171
234
  if (!closed)
172
235
  throw new Error(`Unclosed type declaration at ${source.line}:${source.column}`);
173
- statements.push({ type: 'typeDeclaration', name: header[1], fields, ...(exported ? { exported } : {}), source });
236
+ statements.push({
237
+ type: 'typeDeclaration',
238
+ name: header[1],
239
+ nameSource: { line: source.line, column: rawLine.indexOf(header[1]) + 1 },
240
+ fields,
241
+ ...(parents ? { parents } : {}),
242
+ ...(exported ? { exported } : {}),
243
+ source
244
+ });
174
245
  continue;
175
246
  }
176
247
  if (context.allowFor === false && containsForExpression(rawLine)) {
177
248
  throw new Error(`Nested loops are unsupported at ${source.line}:${source.column}`);
178
249
  }
250
+ if (/^\s*if\b/.test(rawLine)) {
251
+ const collected = collectDelimitedExpression(lines, i, rawLine.trimStart());
252
+ const parsed = parseBracedIfStatement(collected.text, source, context);
253
+ statements.push(parsed.statement);
254
+ i += parsed.lineCount - 1;
255
+ continue;
256
+ }
179
257
  if (/^\s*for\b/.test(rawLine)) {
180
258
  if (context.allowFor === false) {
181
259
  throw new Error(`Nested loops are unsupported at ${source.line}:${source.column}`);
@@ -7,6 +7,8 @@ import { throwUndefinedIdentifier } from '../diagnostics/errors';
7
7
  export class Environment {
8
8
  store = new Map();
9
9
  recordTypes;
10
+ enumDeclarations = new Map();
11
+ enumValues = new Map();
10
12
  functions;
11
13
  bindingTypes = new Map();
12
14
  dimensionRegistry;
@@ -79,13 +79,13 @@ function validateRuntimeValue(value, expected, env, source, file, valuePath) {
79
79
  }
80
80
  const record = actual;
81
81
  const fieldNames = new Set(declaration.fields.map(field => field.name));
82
- const recordRegistry = fieldRegistry(declaration, env.dimensionRegistry);
83
82
  for (const field of declaration.fields) {
83
+ const fieldScope = fieldRegistry(field, env.dimensionRegistry);
84
84
  if (!Object.prototype.hasOwnProperty.call(record, field.name)) {
85
- report(`Missing computed field '${field.name}'`, checkedType(field.annotation, recordRegistry), 'missing', `${dataPath}.${field.name}`, field.source);
85
+ report(`Missing computed field '${field.name}'`, checkedType(field.annotation, fieldScope), 'missing', `${dataPath}.${field.name}`, field.source);
86
86
  }
87
87
  else {
88
- visit(record[field.name], checkedType(field.annotation, recordRegistry), `${dataPath}.${field.name}`, field.source);
88
+ visit(record[field.name], checkedType(field.annotation, fieldScope), `${dataPath}.${field.name}`, field.source);
89
89
  }
90
90
  }
91
91
  for (const name of Object.keys(record).filter(name => !fieldNames.has(name)).sort()) {
@@ -96,6 +96,18 @@ function validateRuntimeValue(value, expected, env, source, file, valuePath) {
96
96
  if (diagnostics.length)
97
97
  throwInputErrors(diagnostics);
98
98
  }
99
+ function evaluateFieldDefault(field, env, file) {
100
+ if (!field.defaultExpression)
101
+ return null;
102
+ const currentRegistry = env.dimensionRegistry;
103
+ env.dimensionRegistry = fieldRegistry(field, currentRegistry);
104
+ try {
105
+ return evaluateExpression(field.defaultExpression, env, file);
106
+ }
107
+ finally {
108
+ env.dimensionRegistry = currentRegistry;
109
+ }
110
+ }
99
111
  function checkedType(reference, scope) {
100
112
  const registry = scope instanceof Environment ? scope.dimensionRegistry : scope;
101
113
  if (reference.type === 'namedType') {
@@ -154,13 +166,19 @@ export function evaluateExpression(node, env, file) {
154
166
  const record = {};
155
167
  for (const field of declaration.fields) {
156
168
  record[field.name] = supplied.has(field.name) ? supplied.get(field.name)
157
- : field.defaultExpression ? evaluateExpression(field.defaultExpression, env, file) : null;
169
+ : field.defaultExpression ? evaluateFieldDefault(field, env, file) : null;
158
170
  }
159
171
  validateRuntimeValue(record, { kind: 'named', name: node.name }, env, node.source, file, `record ${node.name}`);
160
172
  return record;
161
173
  }
162
- case 'fieldAccess':
174
+ case 'fieldAccess': {
175
+ if (node.receiver.type === 'identifier') {
176
+ const enumeration = env.enumValues.get(node.receiver.name);
177
+ if (enumeration)
178
+ return enumeration[node.field];
179
+ }
163
180
  return evaluateExpression(node.receiver, env, file)[node.field];
181
+ }
164
182
  case 'listAccess':
165
183
  return evalListAccess(node, env, file);
166
184
  case 'numberLiteral':
@@ -219,6 +237,8 @@ export function evaluateExpression(node, env, file) {
219
237
  return evalUnary(node, env, file);
220
238
  case 'conditionalExpression':
221
239
  return evalConditional(node, env, file);
240
+ case 'bracedIfExpression':
241
+ return evalBracedIfExpression(node, env, file);
222
242
  case 'listLiteral':
223
243
  return evalListLiteral(node, env, file);
224
244
  case 'functionCall':
@@ -385,6 +405,58 @@ function evalConditional(node, env, file) {
385
405
  ? evaluateExpression(node.consequent, env, file)
386
406
  : evaluateExpression(node.alternate, env, file);
387
407
  }
408
+ class ConditionalValueReturn {
409
+ value;
410
+ constructor(value) {
411
+ this.value = value;
412
+ }
413
+ }
414
+ class ForExpressionReturn {
415
+ value;
416
+ constructor(value) {
417
+ this.value = value;
418
+ }
419
+ }
420
+ const conditionalReturnDepth = new WeakMap();
421
+ const forExpressionDepth = new WeakMap();
422
+ function withDepth(depths, env, run) {
423
+ depths.set(env, (depths.get(env) ?? 0) + 1);
424
+ try {
425
+ return run();
426
+ }
427
+ finally {
428
+ const depth = depths.get(env) - 1;
429
+ if (depth)
430
+ depths.set(env, depth);
431
+ else
432
+ depths.delete(env);
433
+ }
434
+ }
435
+ function evaluateScopedStatements(statements, env, file) {
436
+ const existing = new Set(Object.keys(env.toObject()));
437
+ try {
438
+ evaluateStatements(statements, env, file);
439
+ }
440
+ finally {
441
+ for (const name of Object.keys(env.toObject())) {
442
+ if (!existing.has(name))
443
+ env.delete(name);
444
+ }
445
+ }
446
+ }
447
+ function evalBracedIfExpression(node, env, file) {
448
+ const branch = toBoolean(evaluateExpression(node.test, env, file)) ? node.consequent : node.alternate;
449
+ const closingSource = branch === node.consequent ? node.consequentSource : node.alternateSource;
450
+ try {
451
+ withDepth(conditionalReturnDepth, env, () => evaluateScopedStatements(branch, env, file));
452
+ }
453
+ catch (error) {
454
+ if (error instanceof ConditionalValueReturn)
455
+ return error.value;
456
+ throw error;
457
+ }
458
+ return staticError('AMX3021', 'Every possible path in an if expression must return a value', closingSource ?? node.source, file);
459
+ }
388
460
  function evalListLiteral(node, env, file) {
389
461
  return node.elements.map(el => evaluateExpression(el, env, file));
390
462
  }
@@ -732,6 +804,20 @@ function evaluateStatement(statement, env, file) {
732
804
  case 'typeDeclaration':
733
805
  env.recordTypes.set(statement.name, statement);
734
806
  return;
807
+ case 'enumDeclaration': {
808
+ const values = statement.resolvedValues ?? statement.members.map((member, index) => {
809
+ if (!member.value)
810
+ return index + 1;
811
+ if (member.value.type === 'numberLiteral' || member.value.type === 'stringLiteral')
812
+ return member.value.value;
813
+ return staticError('AMX3020', 'Only constant values can be assigned to enum members', member.valueSource ?? member.value.source, file);
814
+ });
815
+ const enumeration = {};
816
+ statement.members.forEach((member, index) => { enumeration[member.name] = values[index]; });
817
+ env.enumDeclarations.set(statement.name, statement);
818
+ env.enumValues.set(statement.name, enumeration);
819
+ return;
820
+ }
735
821
  case 'functionDeclaration':
736
822
  env.functions.set(statement.name, statement);
737
823
  return;
@@ -775,10 +861,24 @@ function evaluateStatement(statement, env, file) {
775
861
  case 'forStatement':
776
862
  evalForStatement(statement, env, file);
777
863
  return;
864
+ case 'bracedIfStatement':
865
+ evalBracedIfStatement(statement, env, file);
866
+ return;
778
867
  case 'returnStatement':
868
+ if (conditionalReturnDepth.has(env)) {
869
+ throw new ConditionalValueReturn(evaluateExpression(statement.expression, env, file));
870
+ }
871
+ if (forExpressionDepth.has(env)) {
872
+ throw new ForExpressionReturn(evaluateExpression(statement.expression, env, file));
873
+ }
779
874
  throwInvalidReturnContext(statement.source, file);
780
875
  }
781
876
  }
877
+ function evalBracedIfStatement(node, env, file) {
878
+ const branch = toBoolean(evaluateExpression(node.test, env, file)) ? node.consequent : node.alternate;
879
+ if (branch)
880
+ evaluateScopedStatements(branch, env, file);
881
+ }
782
882
  function mutationTarget(name, env, source, file) {
783
883
  const target = env.get(name, source, file);
784
884
  if (!Array.isArray(target))
@@ -852,16 +952,24 @@ function evalForStatement(node, env, file) {
852
952
  function evalForExpression(node, env, file) {
853
953
  const values = evaluateLoopIterable(node.iterable, env, file);
854
954
  const results = [];
855
- withLoopBinding(node.variable, values, env, () => {
955
+ withDepth(forExpressionDepth, env, () => withLoopBinding(node.variable, values, env, () => {
856
956
  for (const statement of node.body) {
857
957
  if (statement.type === 'returnStatement') {
858
958
  results.push(evaluateExpression(statement.expression, env, file));
859
959
  }
860
960
  else {
861
- evaluateStatement(statement, env, file);
961
+ try {
962
+ evaluateStatement(statement, env, file);
963
+ }
964
+ catch (error) {
965
+ if (error instanceof ForExpressionReturn)
966
+ results.push(error.value);
967
+ else
968
+ throw error;
969
+ }
862
970
  }
863
971
  }
864
- });
972
+ }));
865
973
  return results;
866
974
  }
867
975
  function evaluateLoopIterable(node, env, file) {
@@ -20,20 +20,22 @@ export function describeInputSchema(declaration, types, registry) {
20
20
  && declaration.annotation.element?.type === 'namedType'
21
21
  ? types.get(declaration.annotation.element.name)
22
22
  : undefined;
23
- const recordRegistry = recordType ? fieldRegistry(recordType, registry) : undefined;
24
- const csvCompatible = !!recordType && recordType.fields.every(field => isCsvScalar(field.annotation, recordRegistry));
23
+ const csvCompatible = !!recordType && recordType.fields.every(field => isCsvScalar(field.annotation, fieldRegistry(field, registry)));
25
24
  return {
26
25
  name: declaration.name,
27
26
  type: typeName(declaration.annotation),
28
27
  acceptedFormats: csvCompatible ? ['json', 'csv'] : ['json'],
29
28
  ...(registry ? measurementSchema(declaration.annotation, registry) : {}),
30
- ...(recordType ? { fields: recordType.fields.map(field => ({
31
- name: field.name,
32
- type: typeName(field.annotation),
33
- optional: field.optional,
34
- hasDefault: field.defaultExpression !== undefined,
35
- ...(recordRegistry ? measurementSchema(field.annotation, recordRegistry) : {})
36
- })) } : {})
29
+ ...(recordType ? { fields: recordType.fields.map(field => {
30
+ const fieldScope = fieldRegistry(field, registry);
31
+ return {
32
+ name: field.name,
33
+ type: typeName(field.annotation),
34
+ optional: field.optional,
35
+ hasDefault: field.defaultExpression !== undefined,
36
+ ...(fieldScope ? measurementSchema(field.annotation, fieldScope) : {})
37
+ };
38
+ }) } : {})
37
39
  };
38
40
  }
39
41
  export function validateInputText(text, format, declaration, types, mode = 'aggregate', context = {}, registry) {
@@ -215,15 +217,15 @@ function convertJson(value, annotation, pointer, declarationSource, types, envir
215
217
  report(shapeDiagnostic(`Unknown field '${key}'`, 'declared record field', describe(object[key]), propertyPointer, context, declarationSource, fieldSource));
216
218
  }
217
219
  const materialized = {};
218
- const recordRegistry = fieldRegistry(declaration, registry);
219
220
  for (const field of declaration.fields) {
221
+ const fieldScope = fieldRegistry(field, registry);
220
222
  const propertyPointer = `${pointer}/${escapePointer(field.name)}`;
221
223
  if (Object.prototype.hasOwnProperty.call(object, field.name)) {
222
- materialized[field.name] = convertJson(object[field.name], field.annotation, propertyPointer, declarationSource, types, environment, report, context, field.source, recordRegistry, internalDefault);
224
+ materialized[field.name] = convertJson(object[field.name], field.annotation, propertyPointer, declarationSource, types, environment, report, context, field.source, fieldScope, internalDefault);
223
225
  }
224
226
  else if (field.defaultExpression) {
225
- const value = evaluateExpression(field.defaultExpression, defaultsEnvironment(environment, recordRegistry), context.file);
226
- materialized[field.name] = convertJson(value, field.annotation, propertyPointer, declarationSource, types, environment, report, context, field.source, recordRegistry, true);
227
+ const value = evaluateExpression(field.defaultExpression, defaultsEnvironment(environment, fieldScope), context.file);
228
+ materialized[field.name] = convertJson(value, field.annotation, propertyPointer, declarationSource, types, environment, report, context, field.source, fieldScope, true);
227
229
  }
228
230
  else if (field.optional) {
229
231
  materialized[field.name] = null;
@@ -240,8 +242,7 @@ function convertCsv(text, annotation, declarationSource, types, environment, rep
240
242
  return [];
241
243
  }
242
244
  const recordType = types.get(annotation.element.name);
243
- const recordRegistry = fieldRegistry(recordType, registry);
244
- const scalarFields = recordType.fields.every(field => isCsvScalar(field.annotation, recordRegistry));
245
+ const scalarFields = recordType.fields.every(field => isCsvScalar(field.annotation, fieldRegistry(field, registry)));
245
246
  if (!scalarFields) {
246
247
  report(shapeDiagnostic('CSV records may contain only scalar fields', 'scalar-field RecordType[]', recordType.name, '', context, declarationSource));
247
248
  return [];
@@ -291,8 +292,9 @@ function convertCsv(text, annotation, declarationSource, types, environment, rep
291
292
  const propertyPath = `record[${recordNumber}].${field.name}`;
292
293
  if (column < 0) {
293
294
  if (field.defaultExpression) {
294
- const value = evaluateExpression(field.defaultExpression, defaultsEnvironment(environment, recordRegistry), context.file);
295
- materialized[field.name] = convertJson(value, field.annotation, propertyPath, context.declarationSource, types, environment, report, context, field.source, recordRegistry, true);
295
+ const fieldScope = fieldRegistry(field, registry);
296
+ const value = evaluateExpression(field.defaultExpression, defaultsEnvironment(environment, fieldScope), context.file);
297
+ materialized[field.name] = convertJson(value, field.annotation, propertyPath, context.declarationSource, types, environment, report, context, field.source, fieldScope, true);
296
298
  }
297
299
  else if (field.optional)
298
300
  materialized[field.name] = null;
@@ -301,7 +303,7 @@ function convertCsv(text, annotation, declarationSource, types, environment, rep
301
303
  const cell = row[column];
302
304
  if (!cell)
303
305
  continue;
304
- materialized[field.name] = convertCsvCell(cell, field.annotation, propertyPath, recordNumber, column + 1, field.source, report, context, recordRegistry);
306
+ materialized[field.name] = convertCsvCell(cell, field.annotation, propertyPath, recordNumber, column + 1, field.source, report, context, fieldRegistry(field, registry));
305
307
  }
306
308
  result.push(materialized);
307
309
  }
@@ -96,7 +96,7 @@ export async function loadEntryModule(entryPath, options = {}) {
96
96
  const statements = flattenStatements(doc);
97
97
  const localNames = new Set();
98
98
  for (const statement of statements) {
99
- if (statement.type === 'typeDeclaration' || statement.type === 'functionDeclaration' || statement.type === 'variableDeclaration' || statement.type === 'inputDeclaration'
99
+ if (statement.type === 'typeDeclaration' || statement.type === 'enumDeclaration' || statement.type === 'functionDeclaration' || statement.type === 'variableDeclaration' || statement.type === 'inputDeclaration'
100
100
  || statement.type === 'tableDeclaration' || statement.type === 'chartDeclaration'
101
101
  || statement.type === 'dimensionDeclaration' || statement.type === 'unitDeclaration') {
102
102
  localNames.add(statement.name);
@@ -121,6 +121,8 @@ export async function loadEntryModule(entryPath, options = {}) {
121
121
  const imports = statements.filter((s) => s.type === 'importDeclaration');
122
122
  const localDimensionUnitNames = new Set(statements.flatMap(statement => statement.type === 'dimensionDeclaration' || statement.type === 'unitDeclaration' ? [statement.name] : []));
123
123
  const importedTypes = new Map();
124
+ const importedEnums = new Map();
125
+ const importedEnumSources = new Map();
124
126
  const importedFunctions = new Map();
125
127
  const importedBindings = new Map();
126
128
  const importedBindingSources = new Map();
@@ -157,6 +159,10 @@ export async function loadEntryModule(entryPath, options = {}) {
157
159
  if (dependency.checkResult.exportedTypes.has(importedName.name)) {
158
160
  importedTypes.set(importedName.name, dependency.checkResult.exportedTypes.get(importedName.name));
159
161
  }
162
+ else if (dependency.checkResult.exportedEnums.has(importedName.name)) {
163
+ importedEnums.set(importedName.name, dependency.checkResult.exportedEnums.get(importedName.name));
164
+ importedEnumSources.set(importedName.name, dependency.canonicalPath);
165
+ }
160
166
  else if (dependency.checkResult.exportedFunctions.has(importedName.name)) {
161
167
  importedFunctions.set(importedName.name, dependency.checkResult.exportedFunctions.get(importedName.name));
162
168
  }
@@ -179,6 +185,7 @@ export async function loadEntryModule(entryPath, options = {}) {
179
185
  }
180
186
  const checkResult = checkDocument(doc, canonicalPath, {
181
187
  types: importedTypes,
188
+ enums: importedEnums,
182
189
  functions: importedFunctions,
183
190
  bindings: importedBindings,
184
191
  dimensions: importedDimensions,
@@ -188,7 +195,7 @@ export async function loadEntryModule(entryPath, options = {}) {
188
195
  isEntryModule: canonicalPath === realEntry
189
196
  });
190
197
  visiting.pop();
191
- const record = { canonicalPath, doc, checkResult, importedTypes, importedFunctions, importedBindings, importedBindingSources, importedDimensions, importedUnits };
198
+ const record = { canonicalPath, doc, checkResult, importedTypes, importedEnums, importedEnumSources, importedFunctions, importedBindings, importedBindingSources, importedDimensions, importedUnits };
192
199
  resolved.set(canonicalPath, record);
193
200
  evaluationOrder.push(canonicalPath);
194
201
  return record;
@@ -251,6 +258,13 @@ export async function loadEntryModule(entryPath, options = {}) {
251
258
  env.validationMode = options.validation ?? 'aggregate';
252
259
  for (const [name, typeDeclaration] of record.importedTypes)
253
260
  env.recordTypes.set(name, typeDeclaration);
261
+ for (const [name, enumDeclaration] of record.importedEnums) {
262
+ const dependency = evaluatedEnvironments.get(record.importedEnumSources.get(name));
263
+ if (!dependency)
264
+ moduleError('AMX5002', `Imported enum '${name}' was not materialized`, enumDeclaration.source, canonicalPath);
265
+ env.enumDeclarations.set(name, enumDeclaration);
266
+ env.enumValues.set(name, dependency.enumValues.get(name));
267
+ }
254
268
  for (const [name, functionDeclaration] of record.importedFunctions)
255
269
  env.functions.set(name, functionDeclaration);
256
270
  for (const [name, bindingType] of record.checkResult.bindingTypes)