@nova-energy/openamx 0.12.0 → 0.15.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/dist/cli.js CHANGED
@@ -80,7 +80,7 @@ cli
80
80
  .option("--out <path>", "Output PDF or DOCX file path")
81
81
  .option("--input <mapping>", "Map a logical input to a data file", { type: [String] })
82
82
  .option("--validation <mode>", "Validation mode: aggregate or fail-fast")
83
- .option("--project-root <path>", "Project root for report metadata and logo assets")
83
+ .option("--project-root <path>", "Project root for report metadata and assets")
84
84
  .action(async (format, input, options) => {
85
85
  try {
86
86
  const inputMappings = suppliedMappings(options, "input");
@@ -90,8 +90,8 @@ cli
90
90
  inputMappings,
91
91
  validation: options.validation
92
92
  });
93
- const report = await prepareReport(doc, env, { file: input, projectRoot: options.projectRoot });
94
- const bytes = await serializeDocxReport(prepareDocxReport(report, {
93
+ const report = await prepareReport(doc, env, { file: input, projectRoot: options.projectRoot, includeStylesheet: false });
94
+ const bytes = await serializeDocxReport(await prepareDocxReport(report, {
95
95
  sourceDocumentPath: input,
96
96
  destinationPath: destination.path
97
97
  }));
@@ -106,7 +106,7 @@ cli
106
106
  inputMappings,
107
107
  validation: options.validation
108
108
  });
109
- const report = await prepareReport(doc, env, { file: input, projectRoot: options.projectRoot });
109
+ const report = await prepareReport(doc, env, { file: input, projectRoot: options.projectRoot, includeStylesheet: false });
110
110
  const bytes = await serializePdfReport(preparePdfReport(report, {
111
111
  sourceDocumentPath: input,
112
112
  destinationPath: destination.path
@@ -130,7 +130,7 @@ cli
130
130
  .option("--input <mapping>", "Map a logical input to a data file", { type: [String] })
131
131
  .option("--output <mapping>", "Write an exported value to a JSON or CSV file", { type: [String] })
132
132
  .option("--validation <mode>", "Validation mode: aggregate or fail-fast")
133
- .option("--project-root <path>", "Project root for report metadata and logo assets")
133
+ .option("--project-root <path>", "Project root for report metadata and assets")
134
134
  .action(async (input, options) => {
135
135
  try {
136
136
  const outPath = options.out || input.replace(/\.amx$/, ".html");
@@ -9,8 +9,24 @@ const v04Keywords = ["table", "chart", "show", "title", "description", "column",
9
9
  const v09ListKeywords = ["add", "remove", "at"];
10
10
  const v09UnitKeywords = ["dimension", "unit"];
11
11
  const v12Keywords = ["enum", "extends", "override"];
12
+ const v13Keywords = ["diagram"];
13
+ const v14Keywords = ["is"];
12
14
  const standardFunctions = ["sum", "min", "max", "mean", "round", "abs", "sqrt", "pow"];
15
+ const v14Functions = [
16
+ "sin", "cos", "tan", "asin", "acos", "atan", "sinh", "cosh", "tanh", "asinh", "acosh", "atanh", "ln", "log", "exp",
17
+ "len", "trim", "left", "right", "format"
18
+ ];
19
+ const standardConstants = ["PI", "E"];
13
20
  const primitiveTypes = ["Number", "String", "Boolean", "DateTime"];
21
+ const diagramProperties = ["title", "description", "width", "height"];
22
+ const diagramElements = ["line", "rectangle", "circle", "text"];
23
+ const elementProperties = {
24
+ line: ["x1", "y1", "x2", "y2", "stroke", "lineWidth", "arrow"],
25
+ rectangle: ["x", "y", "width", "height", "stroke", "fill", "lineWidth"],
26
+ circle: ["cx", "cy", "r", "stroke", "fill", "lineWidth"],
27
+ text: ["x", "y", "value", "fill"]
28
+ };
29
+ const arrowValues = ['"none"', '"start"', '"end"', '"both"'];
14
30
  function cursorInsideOpenAmxFence(text, cursorOffset) {
15
31
  const frontMatter = parseFrontMatter(text);
16
32
  if (frontMatter.error)
@@ -111,6 +127,85 @@ function statementEndOffset(text, statement) {
111
127
  }
112
128
  return text.length;
113
129
  }
130
+ function blockBounds(text, source) {
131
+ const start = sourceOffset(text, source);
132
+ if (start === undefined)
133
+ return undefined;
134
+ let open = -1;
135
+ let depth = 0;
136
+ for (let offset = start; offset < text.length; offset++) {
137
+ if (text[offset] === '"' || text[offset] === "'") {
138
+ const end = findStringLiteralEnd(text, offset);
139
+ if (end === undefined)
140
+ return open < 0 ? undefined : { open, close: text.length };
141
+ offset = end;
142
+ }
143
+ else if (text[offset] === "{") {
144
+ if (open < 0)
145
+ open = offset;
146
+ depth++;
147
+ }
148
+ else if (text[offset] === "}" && open >= 0 && --depth === 0)
149
+ return { open, close: offset };
150
+ }
151
+ return open < 0 ? undefined : { open, close: text.length };
152
+ }
153
+ function diagramAt(text, parsed, cursorOffset) {
154
+ for (const diagram of statementsOf(parsed).filter((statement) => statement.type === "diagramDeclaration")) {
155
+ const bounds = blockBounds(text, diagram.source);
156
+ if (!bounds || cursorOffset <= bounds.open || cursorOffset > bounds.close)
157
+ continue;
158
+ const element = diagram.elements.find(candidate => {
159
+ const elementBounds = blockBounds(text, candidate.source);
160
+ return !!elementBounds && cursorOffset > elementBounds.open && cursorOffset <= elementBounds.close;
161
+ });
162
+ return { diagram, element };
163
+ }
164
+ return undefined;
165
+ }
166
+ function diagramCompletionFacts(text, contextText, cursorOffset, parsed, visible) {
167
+ const active = diagramAt(text, parsed, cursorOffset);
168
+ if (!active)
169
+ return undefined;
170
+ const contextCursor = Math.max(0, Math.min(cursorOffset, contextText.length));
171
+ const lineStart = contextText.lastIndexOf("\n", Math.max(0, contextCursor - 1)) + 1;
172
+ const prefix = contextText.slice(lineStart, contextCursor);
173
+ const propertyValue = prefix.match(/^\s*([A-Za-z_][A-Za-z0-9_]*)\s*:\s*/);
174
+ if (propertyValue) {
175
+ if (active.element?.primitive === "line" && propertyValue[1] === "arrow") {
176
+ return arrowValues.map(label => ({ label, kind: "keyword" }));
177
+ }
178
+ const variables = new Set(visible.variables);
179
+ if (active.element && active.diagram.times.length === 1)
180
+ variables.add(active.diagram.times[0].name);
181
+ const fieldReceiver = prefix.match(/\b([A-Za-z][A-Za-z0-9_]*)\.\w*$/)?.[1];
182
+ const fields = fieldReceiver
183
+ ? visible.enums.get(fieldReceiver)?.members.map(member => member.name)
184
+ ?? visible.recordTypes.get(fieldReceiver)?.fields.map(field => field.name) ?? []
185
+ : [];
186
+ return [
187
+ ...standardFunctions.map(label => ({ label, kind: "function" })),
188
+ ...[...visible.functions].map(label => ({ label, kind: "function" })),
189
+ ...[...visible.types].map(label => ({ label, kind: "class" })),
190
+ ...[...variables].map(label => ({ label, kind: "variable" })),
191
+ ...[...visible.views].map(label => ({ label, kind: "reference" })),
192
+ ...fields.map(label => ({ label, kind: "field" }))
193
+ ];
194
+ }
195
+ const partialProperty = prefix.match(/^\s*([A-Za-z_][A-Za-z0-9_]*)?$/);
196
+ if (!partialProperty)
197
+ return [];
198
+ const existing = active.element
199
+ ? active.element.properties.map(property => property.name)
200
+ : [...active.diagram.properties.map(property => property.name), ...(active.diagram.times.length ? ["time"] : [])];
201
+ const available = active.element
202
+ ? elementProperties[active.element.primitive] ?? []
203
+ : [...diagramProperties, "time", ...diagramElements];
204
+ return available.filter(name => !existing.includes(name)).map(label => ({
205
+ label,
206
+ kind: diagramElements.includes(label) || label === "time" ? "keyword" : "field"
207
+ }));
208
+ }
114
209
  function loopBounds(text, loop) {
115
210
  const start = sourceOffset(text, loop.source);
116
211
  if (start === undefined)
@@ -308,6 +403,9 @@ function visibleSymbols(text, parsed, cursorOffset, analysis) {
308
403
  collectExpression(expression.left);
309
404
  collectExpression(expression.right);
310
405
  break;
406
+ case "typeTestExpression":
407
+ collectExpression(expression.value);
408
+ break;
311
409
  case "measurementAttachment":
312
410
  case "measurementConversion":
313
411
  collectExpression(expression.value);
@@ -383,14 +481,18 @@ export function editorCompletionFacts(text, cursorOffset, parsed, analysis, cont
383
481
  ?? visible.recordTypes.get(fieldReceiver)?.fields.map(field => field.name) ?? []
384
482
  : [];
385
483
  const facts = [
386
- ...[...v02Keywords, ...v03Keywords, ...v04Keywords, ...v09ListKeywords, ...v09UnitKeywords, ...v12Keywords].map(label => ({ label, kind: "keyword" })),
387
- ...standardFunctions.map(label => ({ label, kind: "function" })),
484
+ ...[...v02Keywords, ...v03Keywords, ...v04Keywords, ...v09ListKeywords, ...v09UnitKeywords, ...v12Keywords, ...v13Keywords, ...v14Keywords].map(label => ({ label, kind: "keyword" })),
485
+ ...[...standardFunctions, ...v14Functions].map(label => ({ label, kind: "function" })),
486
+ ...standardConstants.map(label => ({ label, kind: "variable" })),
388
487
  ...[...visible.functions].map(label => ({ label, kind: "function" })),
389
488
  ...[...visible.types].map(label => ({ label, kind: "class" })),
390
489
  ...[...visible.variables].map(label => ({ label, kind: "variable" })),
391
490
  ...[...visible.views].map(label => ({ label, kind: "reference" })),
392
491
  ...fields.map(label => ({ label, kind: "field" }))
393
492
  ];
493
+ const diagramFacts = diagramCompletionFacts(text, contextText, cursor, parsed, visible);
494
+ if (diagramFacts)
495
+ return diagramFacts;
394
496
  return facts;
395
497
  }
396
498
  export function executableBlockContentStart(text, node) {
@@ -95,6 +95,11 @@ export function editorHighlightFacts(text, document) {
95
95
  expression(node.left);
96
96
  expression(node.right);
97
97
  break;
98
+ case "typeTestExpression":
99
+ expression(node.value);
100
+ add(node.operatorSource, "is", "keyword");
101
+ typeReference(node.target);
102
+ break;
98
103
  case "unaryExpression":
99
104
  expression(node.argument);
100
105
  break;
@@ -143,7 +148,7 @@ export function editorHighlightFacts(text, document) {
143
148
  variableDeclaration: "let", typeDeclaration: "type", enumDeclaration: "enum", functionDeclaration: "fn",
144
149
  dimensionDeclaration: "dimension", unitDeclaration: "unit",
145
150
  inputDeclaration: "input", importDeclaration: "import", tableDeclaration: "table",
146
- chartDeclaration: "chart", showStatement: "show", forStatement: "for",
151
+ chartDeclaration: "chart", diagramDeclaration: "diagram", showStatement: "show", forStatement: "for",
147
152
  assignmentStatement: "", compoundAssignmentStatement: "", bracedIfStatement: "if", returnStatement: "return",
148
153
  addStatement: "add", removeStatement: "remove"
149
154
  };
@@ -170,6 +175,27 @@ export function editorHighlightFacts(text, document) {
170
175
  add(item.source, item.name, "reference");
171
176
  if (node.type === "inputDeclaration")
172
177
  typeReference(node.annotation);
178
+ if (node.type === "diagramDeclaration") {
179
+ for (const property of node.properties) {
180
+ add(property.nameSource, property.name, "field");
181
+ expression(property.expression);
182
+ }
183
+ for (const time of node.times) {
184
+ add(time.source, "time", "keyword");
185
+ add(time.nameSource, time.name, "declaration");
186
+ expression(time.from);
187
+ expression(time.to);
188
+ expression(time.duration);
189
+ }
190
+ for (const element of node.elements) {
191
+ add(element.source, element.primitive, "keyword");
192
+ add(element.nameSource, element.name, "declaration");
193
+ for (const property of element.properties) {
194
+ add(property.nameSource, property.name, "field");
195
+ expression(property.expression);
196
+ }
197
+ }
198
+ }
173
199
  if (node.type === "typeDeclaration") {
174
200
  const firstParent = node.parents?.[0];
175
201
  const typeOffset = sourceOffset(text, node.source);
@@ -2,7 +2,10 @@ import { sourceTokenRange } from "./sourceRanges";
2
2
  const reservedNames = new Set([
3
3
  "let", "for", "in", "to", "return", "match", "case", "default", "if", "then", "else", "and", "or", "not", "dimension", "unit", "extends", "override", "enum",
4
4
  "true", "false", "null", "type", "fn", "import", "from", "input", "export", "table", "chart", "show",
5
- "title", "description", "column", "category", "x", "y", "group", "labels", "series", "as",
5
+ "diagram", "time", "line", "rectangle", "circle", "text",
6
+ "title", "description", "column", "category", "x", "y", "width", "height", "duration",
7
+ "x1", "y1", "x2", "y2", "cx", "cy", "r", "stroke", "fill", "lineWidth", "arrow", "value",
8
+ "group", "labels", "series", "as",
6
9
  "Number", "String", "Boolean", "DateTime"
7
10
  ]);
8
11
  export function isSafeRenameIdentifier(name) {
@@ -7,7 +7,8 @@ const declarationKeywords = {
7
7
  inputDeclaration: "input",
8
8
  variableDeclaration: "let",
9
9
  tableDeclaration: "table",
10
- chartDeclaration: "chart"
10
+ chartDeclaration: "chart",
11
+ diagramDeclaration: "diagram"
11
12
  };
12
13
  export function sourceOffset(text, source) {
13
14
  if (!source || !Number.isSafeInteger(source.line) || !Number.isSafeInteger(source.column)
@@ -60,11 +60,13 @@ export function editorSymbolFacts(text, entryFile, entryDocument, analysis, modu
60
60
  const range = sourceTokenRange(moduleText, member.nameSource, member.name);
61
61
  if (!range)
62
62
  continue;
63
+ const parent = declaration(moduleText, file, declarationNode)?.target;
63
64
  enumMemberTargets.set(`${file}\0${declarationNode.name}\0${member.name}`, {
64
65
  ...range,
65
66
  file,
66
67
  name: member.name,
67
68
  target: { file, ...range },
69
+ parent,
68
70
  declaration: true,
69
71
  kind: "enumMember",
70
72
  detail: `enum member ${declarationNode.name}.${member.name}`
@@ -89,56 +91,66 @@ export function editorSymbolFacts(text, entryFile, entryDocument, analysis, modu
89
91
  if (range)
90
92
  result.push({ ...target, ...range, file, declaration: false });
91
93
  };
92
- const expression = (node) => {
94
+ const typeReference = (reference, scope) => {
95
+ if (reference.type === "namedType" && reference.name)
96
+ add(reference.source, reference.name, scope.get(reference.name));
97
+ else if (reference.element)
98
+ typeReference(reference.element, scope);
99
+ };
100
+ const expression = (node, scope = visible) => {
93
101
  if (!analysis && statements.some(statement => statement.type === "importDeclaration"))
94
102
  return;
95
103
  switch (node.type) {
96
104
  case "stringInterpolation":
97
105
  node.parts.forEach(part => { if (typeof part !== "string")
98
- expression(part); });
106
+ expression(part, scope); });
99
107
  break;
100
108
  case "identifier":
101
- add(node.source, node.name, visible.get(node.name));
109
+ add(node.source, node.name, scope.get(node.name));
102
110
  break;
103
111
  case "functionCall":
104
- add(node.source, node.callee, visible.get(node.callee));
105
- node.arguments.forEach(expression);
112
+ add(node.source, node.callee, scope.get(node.callee));
113
+ node.arguments.forEach(argument => expression(argument, scope));
106
114
  break;
107
115
  case "recordConstructor":
108
- add(node.source, node.name, visible.get(node.name));
109
- node.fields.forEach(field => expression(field.expression));
116
+ add(node.source, node.name, scope.get(node.name));
117
+ node.fields.forEach(field => expression(field.expression, scope));
110
118
  break;
111
119
  case "binaryExpression":
112
- expression(node.left);
113
- expression(node.right);
120
+ expression(node.left, scope);
121
+ expression(node.right, scope);
122
+ break;
123
+ case "typeTestExpression":
124
+ expression(node.value, scope);
125
+ typeReference(node.target, scope);
114
126
  break;
115
127
  case "measurementAttachment":
116
128
  case "measurementConversion":
117
- add(node.unitSource, node.unit, visible.get(node.unit));
118
- expression(node.value);
129
+ add(node.unitSource, node.unit, scope.get(node.unit));
130
+ expression(node.value, scope);
119
131
  break;
120
132
  case "unaryExpression":
121
- expression(node.argument);
133
+ expression(node.argument, scope);
122
134
  break;
123
135
  case "conditionalExpression":
124
- expression(node.test);
125
- expression(node.consequent);
126
- expression(node.alternate);
136
+ expression(node.test, scope);
137
+ expression(node.consequent, scope);
138
+ expression(node.alternate, scope);
127
139
  break;
128
140
  case "listLiteral":
129
- node.elements.forEach(expression);
141
+ node.elements.forEach(element => expression(element, scope));
130
142
  break;
131
143
  case "rangeExpression":
132
- expression(node.start);
133
- expression(node.end);
144
+ expression(node.start, scope);
145
+ expression(node.end, scope);
134
146
  break;
135
147
  case "matchExpression":
136
- expression(node.expression);
137
- node.cases.forEach(arm => expression(arm.expression));
138
- expression(node.defaultExpression);
148
+ expression(node.expression, scope);
149
+ node.cases.forEach(arm => expression(arm.expression, scope));
150
+ expression(node.defaultExpression, scope);
139
151
  break;
140
152
  case "fieldAccess": {
141
- expression(node.receiver);
153
+ expression(node.receiver, scope);
142
154
  if (node.receiver.type === "identifier") {
143
155
  const visibleEnum = visibleEnums.get(node.receiver.name);
144
156
  const member = visibleEnum && enumMemberTargets.get(`${visibleEnum.file}\0${visibleEnum.declaration.name}\0${node.field}`);
@@ -147,47 +159,47 @@ export function editorSymbolFacts(text, entryFile, entryDocument, analysis, modu
147
159
  break;
148
160
  }
149
161
  case "listAccess":
150
- expression(node.receiver);
151
- expression(node.index);
162
+ expression(node.receiver, scope);
163
+ expression(node.index, scope);
152
164
  break;
153
165
  case "forExpression":
154
- expression(node.iterable);
155
- node.body.forEach(nestedStatement);
166
+ expression(node.iterable, scope);
167
+ node.body.forEach(statement => nestedStatement(statement, scope));
156
168
  break;
157
169
  case "bracedIfExpression":
158
- expression(node.test);
159
- node.consequent.forEach(nestedStatement);
160
- node.alternate.forEach(nestedStatement);
170
+ expression(node.test, scope);
171
+ node.consequent.forEach(statement => nestedStatement(statement, scope));
172
+ node.alternate.forEach(statement => nestedStatement(statement, scope));
161
173
  break;
162
174
  default: break;
163
175
  }
164
176
  };
165
- const nestedStatement = (statement) => {
177
+ const nestedStatement = (statement, scope = visible) => {
166
178
  if (statement.type === "variableDeclaration")
167
- expression(statement.expression);
179
+ expression(statement.expression, scope);
168
180
  else if (statement.type === "typeDeclaration") {
169
181
  for (const parent of statement.parents ?? [])
170
- add(parent.source, parent.name, visible.get(parent.name));
182
+ add(parent.source, parent.name, scope.get(parent.name));
171
183
  for (const field of statement.fields)
172
184
  if (field.defaultExpression)
173
- expression(field.defaultExpression);
185
+ expression(field.defaultExpression, scope);
174
186
  }
175
187
  else if (statement.type === "enumDeclaration") {
176
188
  for (const member of statement.members)
177
189
  if (member.value)
178
- expression(member.value);
190
+ expression(member.value, scope);
179
191
  }
180
192
  else if (statement.type === "forStatement") {
181
- expression(statement.iterable);
182
- statement.body.forEach(nestedStatement);
193
+ expression(statement.iterable, scope);
194
+ statement.body.forEach(item => nestedStatement(item, scope));
183
195
  }
184
196
  else if (statement.type === "bracedIfStatement") {
185
- expression(statement.test);
186
- statement.consequent.forEach(nestedStatement);
187
- statement.alternate?.forEach(nestedStatement);
197
+ expression(statement.test, scope);
198
+ statement.consequent.forEach(item => nestedStatement(item, scope));
199
+ statement.alternate?.forEach(item => nestedStatement(item, scope));
188
200
  }
189
201
  else if ("expression" in statement && statement.expression)
190
- expression(statement.expression);
202
+ expression(statement.expression, scope);
191
203
  };
192
204
  for (const statement of statements) {
193
205
  if (statement.type === "importDeclaration") {
@@ -232,6 +244,52 @@ export function editorSymbolFacts(text, entryFile, entryDocument, analysis, modu
232
244
  }
233
245
  if (statement.type === "variableDeclaration")
234
246
  expression(statement.expression);
247
+ if (statement.type === "diagramDeclaration") {
248
+ const diagram = declaration(moduleText, file, statement);
249
+ const diagramParent = !duplicates.has(statement.name) ? diagram?.target : undefined;
250
+ const diagramScope = new Map(visible);
251
+ for (const property of statement.properties)
252
+ expression(property.expression);
253
+ for (const time of statement.times) {
254
+ expression(time.from);
255
+ expression(time.to);
256
+ expression(time.duration);
257
+ const range = sourceTokenRange(moduleText, time.nameSource, time.name);
258
+ if (!range || !diagramParent)
259
+ continue;
260
+ const localTime = {
261
+ ...range,
262
+ file,
263
+ name: time.name,
264
+ target: { file, ...range },
265
+ parent: diagramParent,
266
+ declaration: true,
267
+ kind: "diagramTime",
268
+ detail: `time ${time.name}`
269
+ };
270
+ result.push(localTime);
271
+ diagramScope.set(time.name, localTime);
272
+ }
273
+ const elementNames = new Set();
274
+ for (const element of statement.elements) {
275
+ const range = sourceTokenRange(moduleText, element.nameSource, element.name);
276
+ if (range && diagramParent && !elementNames.has(element.name)) {
277
+ elementNames.add(element.name);
278
+ result.push({
279
+ ...range,
280
+ file,
281
+ name: element.name,
282
+ target: { file, ...range },
283
+ parent: diagramParent,
284
+ declaration: true,
285
+ kind: "diagramElement",
286
+ detail: `${element.primitive} ${element.name}`
287
+ });
288
+ }
289
+ for (const property of element.properties)
290
+ expression(property.expression, diagramScope);
291
+ }
292
+ }
235
293
  if (statement.type === "typeDeclaration") {
236
294
  for (const parent of statement.parents ?? [])
237
295
  add(parent.source, parent.name, visible.get(parent.name));
@@ -277,12 +335,12 @@ export function editorSymbolFacts(text, entryFile, entryDocument, analysis, modu
277
335
  }
278
336
  if (statement.type === "forStatement") {
279
337
  expression(statement.iterable);
280
- statement.body.forEach(nestedStatement);
338
+ statement.body.forEach(item => nestedStatement(item));
281
339
  }
282
340
  if (statement.type === "bracedIfStatement") {
283
341
  expression(statement.test);
284
- statement.consequent.forEach(nestedStatement);
285
- statement.alternate?.forEach(nestedStatement);
342
+ statement.consequent.forEach(item => nestedStatement(item));
343
+ statement.alternate?.forEach(item => nestedStatement(item));
286
344
  }
287
345
  if (statement.type === "functionDeclaration")
288
346
  expression(statement.body);
@@ -293,13 +351,14 @@ export function editorSymbolFacts(text, entryFile, entryDocument, analysis, modu
293
351
  if (inferred)
294
352
  declared.detail = `binding ${statement.name}: ${typeText(inferred)}`;
295
353
  }
296
- visible.set(statement.name, declared);
354
+ if (statement.type !== "diagramDeclaration")
355
+ visible.set(statement.name, declared);
297
356
  result.push(declared);
298
357
  if (statement.type === "typeDeclaration")
299
358
  for (const field of statement.fields) {
300
359
  const range = sourceTokenRange(moduleText, field.source, field.name);
301
360
  if (range)
302
- result.push({ ...range, file, name: field.name, target: { file, ...range }, declaration: true, kind: "field", detail: `field ${field.name}: ${field.annotation.name ?? field.annotation.type}` });
361
+ result.push({ ...range, file, name: field.name, target: { file, ...range }, parent: declared.target, declaration: true, kind: "field", detail: `field ${field.name}: ${field.annotation.name ?? field.annotation.type}` });
303
362
  }
304
363
  }
305
364
  }
@@ -33,21 +33,97 @@ export function formatAmx(source) {
33
33
  lines.pop();
34
34
  if (lines.length === 0)
35
35
  return '';
36
- parseStatements(lines.join('\n'));
36
+ const statements = parseStatements(lines.join('\n'));
37
+ const diagramsByLine = new Map();
38
+ collectDiagramDeclarations(statements, diagramsByLine);
37
39
  let depth = 0;
38
- const formatted = lines.map((rawLine) => {
40
+ const formatted = [];
41
+ for (let index = 0; index < lines.length; index++) {
42
+ const diagram = diagramsByLine.get(index);
43
+ if (diagram) {
44
+ formatted.push(...formatDiagram(diagram, depth));
45
+ index = diagramEndLine(lines, index);
46
+ continue;
47
+ }
48
+ const rawLine = lines[index];
39
49
  const line = rawLine.replace(/[ \t]+$/, '');
40
- if (line.trim().length === 0)
41
- return '';
50
+ if (line.trim().length === 0) {
51
+ formatted.push('');
52
+ continue;
53
+ }
42
54
  const content = line.trimStart();
43
55
  const braces = scanBraces(content);
44
56
  const lineDepth = Math.max(0, depth - braces.leadingClosures);
45
- const result = `${' '.repeat(lineDepth)}${content}`;
57
+ formatted.push(`${' '.repeat(lineDepth)}${content}`);
46
58
  depth = Math.max(0, depth + braces.opens - braces.closes);
47
- return result;
48
- });
59
+ }
49
60
  return `${formatted.join('\n')}\n`;
50
61
  }
62
+ function collectDiagramDeclarations(statements, result) {
63
+ for (const statement of statements) {
64
+ if (statement.type === 'diagramDeclaration') {
65
+ if (statement.source)
66
+ result.set(statement.source.line - 1, statement);
67
+ }
68
+ else if (statement.type === 'forStatement') {
69
+ collectDiagramDeclarations(statement.body, result);
70
+ }
71
+ else if (statement.type === 'bracedIfStatement') {
72
+ collectDiagramDeclarations(statement.consequent, result);
73
+ if (statement.alternate)
74
+ collectDiagramDeclarations(statement.alternate, result);
75
+ }
76
+ }
77
+ }
78
+ function diagramEndLine(lines, start) {
79
+ let depth = 0;
80
+ for (let index = start; index < lines.length; index++) {
81
+ const braces = scanBraces(lines[index]);
82
+ depth += braces.opens - braces.closes;
83
+ if (depth === 0)
84
+ return index;
85
+ }
86
+ return lines.length - 1;
87
+ }
88
+ function orderedProperties(properties, order) {
89
+ const positions = new Map(order.map((name, index) => [name, index]));
90
+ return [...properties].sort((left, right) => (positions.get(left.name) ?? Number.MAX_SAFE_INTEGER) - (positions.get(right.name) ?? Number.MAX_SAFE_INTEGER));
91
+ }
92
+ function formatProperty(property, level) {
93
+ const indentation = ' '.repeat(level);
94
+ const continuationIndentation = ' '.repeat(level + 1);
95
+ const valueLines = property.rawValue.split('\n');
96
+ return [
97
+ `${indentation}${property.name}: ${valueLines[0]}`,
98
+ ...valueLines.slice(1).map(line => `${continuationIndentation}${line.trimStart()}`)
99
+ ];
100
+ }
101
+ function elementPropertyOrder(element) {
102
+ switch (element.primitive) {
103
+ case 'line': return ['x1', 'y1', 'x2', 'y2', 'stroke', 'lineWidth', 'arrow'];
104
+ case 'rectangle': return ['x', 'y', 'width', 'height', 'stroke', 'fill', 'lineWidth'];
105
+ case 'circle': return ['cx', 'cy', 'r', 'stroke', 'fill', 'lineWidth'];
106
+ case 'text': return ['x', 'y', 'value', 'fill'];
107
+ default: return [];
108
+ }
109
+ }
110
+ function formatDiagram(diagram, level) {
111
+ const indentation = ' '.repeat(level);
112
+ const output = [`${indentation}diagram ${diagram.name} {`];
113
+ output.push(...orderedProperties(diagram.properties, ['title', 'description', 'width', 'height'])
114
+ .flatMap(property => formatProperty(property, level + 1)));
115
+ for (const time of diagram.times) {
116
+ output.push(`${' '.repeat(level + 1)}time ${time.name} from ${time.fromText} to ${time.toText} duration ${time.durationText}`);
117
+ }
118
+ for (const element of diagram.elements) {
119
+ output.push(`${' '.repeat(level + 1)}${element.primitive} ${element.name} {`);
120
+ output.push(...orderedProperties(element.properties, elementPropertyOrder(element))
121
+ .flatMap(property => formatProperty(property, level + 2)));
122
+ output.push(`${' '.repeat(level + 1)}}`);
123
+ }
124
+ output.push(`${indentation}}`);
125
+ return output;
126
+ }
51
127
  function scanBraces(line) {
52
128
  let opens = 0;
53
129
  let closes = 0;