@mun-ui/compiler 0.0.0-stage → 0.2.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 (143) hide show
  1. package/LICENSE +21 -0
  2. package/dist/analysis.d.ts +11 -0
  3. package/dist/analysis.d.ts.map +1 -0
  4. package/dist/analysis.js +80 -0
  5. package/dist/analysis.js.map +1 -0
  6. package/dist/ast.d.ts +121 -0
  7. package/dist/ast.d.ts.map +1 -0
  8. package/dist/ast.js +1022 -0
  9. package/dist/ast.js.map +1 -0
  10. package/dist/builtins.d.ts +47 -0
  11. package/dist/builtins.d.ts.map +1 -0
  12. package/dist/builtins.js +259 -0
  13. package/dist/builtins.js.map +1 -0
  14. package/dist/collection-specialization.d.ts +2 -0
  15. package/dist/collection-specialization.d.ts.map +1 -0
  16. package/dist/collection-specialization.js +475 -0
  17. package/dist/collection-specialization.js.map +1 -0
  18. package/dist/diagnostics.d.ts +12 -0
  19. package/dist/diagnostics.d.ts.map +1 -0
  20. package/dist/diagnostics.js +182 -0
  21. package/dist/diagnostics.js.map +1 -0
  22. package/dist/effect-analysis.d.ts +54 -0
  23. package/dist/effect-analysis.d.ts.map +1 -0
  24. package/dist/effect-analysis.js +318 -0
  25. package/dist/effect-analysis.js.map +1 -0
  26. package/dist/execution-plan.d.ts +63 -0
  27. package/dist/execution-plan.d.ts.map +1 -0
  28. package/dist/execution-plan.js +223 -0
  29. package/dist/execution-plan.js.map +1 -0
  30. package/dist/gpu-island-ir.d.ts +85 -0
  31. package/dist/gpu-island-ir.d.ts.map +1 -0
  32. package/dist/gpu-island-ir.js +159 -0
  33. package/dist/gpu-island-ir.js.map +1 -0
  34. package/dist/gpu-region.d.ts +28 -0
  35. package/dist/gpu-region.d.ts.map +1 -0
  36. package/dist/gpu-region.js +136 -0
  37. package/dist/gpu-region.js.map +1 -0
  38. package/dist/index.d.ts +29 -0
  39. package/dist/index.d.ts.map +1 -0
  40. package/dist/index.js +56 -0
  41. package/dist/index.js.map +1 -0
  42. package/dist/kernel-ir.d.ts +13 -0
  43. package/dist/kernel-ir.d.ts.map +1 -0
  44. package/dist/kernel-ir.js +221 -0
  45. package/dist/kernel-ir.js.map +1 -0
  46. package/dist/language-catalog.d.ts +26 -0
  47. package/dist/language-catalog.d.ts.map +1 -0
  48. package/dist/language-catalog.js +27 -0
  49. package/dist/language-catalog.js.map +1 -0
  50. package/dist/lifecycle.d.ts +15 -0
  51. package/dist/lifecycle.d.ts.map +1 -0
  52. package/dist/lifecycle.js +122 -0
  53. package/dist/lifecycle.js.map +1 -0
  54. package/dist/native-contract.d.ts +27 -0
  55. package/dist/native-contract.d.ts.map +1 -0
  56. package/dist/native-contract.js +163 -0
  57. package/dist/native-contract.js.map +1 -0
  58. package/dist/native-member-contract.d.ts +13 -0
  59. package/dist/native-member-contract.d.ts.map +1 -0
  60. package/dist/native-member-contract.js +10 -0
  61. package/dist/native-member-contract.js.map +1 -0
  62. package/dist/native-values.d.ts +43 -0
  63. package/dist/native-values.d.ts.map +1 -0
  64. package/dist/native-values.js +450 -0
  65. package/dist/native-values.js.map +1 -0
  66. package/dist/observable.d.ts +19 -0
  67. package/dist/observable.d.ts.map +1 -0
  68. package/dist/observable.js +203 -0
  69. package/dist/observable.js.map +1 -0
  70. package/dist/pipeline.d.ts +11 -0
  71. package/dist/pipeline.d.ts.map +1 -0
  72. package/dist/pipeline.js +2290 -0
  73. package/dist/pipeline.js.map +1 -0
  74. package/dist/resident-fusion.d.ts +102 -0
  75. package/dist/resident-fusion.d.ts.map +1 -0
  76. package/dist/resident-fusion.js +423 -0
  77. package/dist/resident-fusion.js.map +1 -0
  78. package/dist/resident-js.d.ts +7 -0
  79. package/dist/resident-js.d.ts.map +1 -0
  80. package/dist/resident-js.js +106 -0
  81. package/dist/resident-js.js.map +1 -0
  82. package/dist/resident-planner.d.ts +58 -0
  83. package/dist/resident-planner.d.ts.map +1 -0
  84. package/dist/resident-planner.js +101 -0
  85. package/dist/resident-planner.js.map +1 -0
  86. package/dist/resident-wasm.d.ts +56 -0
  87. package/dist/resident-wasm.d.ts.map +1 -0
  88. package/dist/resident-wasm.js +867 -0
  89. package/dist/resident-wasm.js.map +1 -0
  90. package/dist/scanner.d.ts +63 -0
  91. package/dist/scanner.d.ts.map +1 -0
  92. package/dist/scanner.js +760 -0
  93. package/dist/scanner.js.map +1 -0
  94. package/dist/semantic.d.ts +100 -0
  95. package/dist/semantic.d.ts.map +1 -0
  96. package/dist/semantic.js +669 -0
  97. package/dist/semantic.js.map +1 -0
  98. package/dist/shorthand.d.ts +16 -0
  99. package/dist/shorthand.d.ts.map +1 -0
  100. package/dist/shorthand.js +324 -0
  101. package/dist/shorthand.js.map +1 -0
  102. package/dist/source-map.d.ts +26 -0
  103. package/dist/source-map.d.ts.map +1 -0
  104. package/dist/source-map.js +228 -0
  105. package/dist/source-map.js.map +1 -0
  106. package/dist/specialization.d.ts +34 -0
  107. package/dist/specialization.d.ts.map +1 -0
  108. package/dist/specialization.js +1996 -0
  109. package/dist/specialization.js.map +1 -0
  110. package/dist/state-specialization.d.ts +3 -0
  111. package/dist/state-specialization.d.ts.map +1 -0
  112. package/dist/state-specialization.js +227 -0
  113. package/dist/state-specialization.js.map +1 -0
  114. package/dist/struct-state.d.ts +39 -0
  115. package/dist/struct-state.d.ts.map +1 -0
  116. package/dist/struct-state.js +225 -0
  117. package/dist/struct-state.js.map +1 -0
  118. package/dist/types.d.ts +70 -0
  119. package/dist/types.d.ts.map +1 -0
  120. package/dist/types.js +2 -0
  121. package/dist/types.js.map +1 -0
  122. package/dist/ui-ir.d.ts +151 -0
  123. package/dist/ui-ir.d.ts.map +1 -0
  124. package/dist/ui-ir.js +2793 -0
  125. package/dist/ui-ir.js.map +1 -0
  126. package/dist/value-types.d.ts +74 -0
  127. package/dist/value-types.d.ts.map +1 -0
  128. package/dist/value-types.js +246 -0
  129. package/dist/value-types.js.map +1 -0
  130. package/dist/vite.d.ts +33 -0
  131. package/dist/vite.d.ts.map +1 -0
  132. package/dist/vite.js +233 -0
  133. package/dist/vite.js.map +1 -0
  134. package/dist/vue-host.d.ts +25 -0
  135. package/dist/vue-host.d.ts.map +1 -0
  136. package/dist/vue-host.js +103 -0
  137. package/dist/vue-host.js.map +1 -0
  138. package/dist/web-analysis.d.ts +7 -0
  139. package/dist/web-analysis.d.ts.map +1 -0
  140. package/dist/web-analysis.js +81 -0
  141. package/dist/web-analysis.js.map +1 -0
  142. package/package.json +29 -3
  143. package/README.md +0 -3
package/dist/ast.js ADDED
@@ -0,0 +1,1022 @@
1
+ const closing = { "(": ")", "{": "}", "[": "]" };
2
+ const regexAfterKeywords = new Set([
3
+ "case", "delete", "do", "else", "in", "instanceof", "of", "return", "throw",
4
+ "typeof", "void", "yield", "await",
5
+ ]);
6
+ function isRawHtmlClosingTag(source, index) {
7
+ if (source[index - 1] !== "<" || !/[A-Za-z]/.test(source[index + 1] ?? ""))
8
+ return false;
9
+ let cursor = index + 2;
10
+ while (/[A-Za-z0-9:._-]/.test(source[cursor] ?? ""))
11
+ cursor += 1;
12
+ while (/\s/.test(source[cursor] ?? ""))
13
+ cursor += 1;
14
+ return source[cursor] === ">";
15
+ }
16
+ function syntaxError(message, offset) {
17
+ const error = new SyntaxError(message);
18
+ error.offset = offset;
19
+ return error;
20
+ }
21
+ function identifierPart(value) {
22
+ return !!value && /[A-Za-z0-9_$]/.test(value);
23
+ }
24
+ function skipQuoted(source, index) {
25
+ const quote = source[index];
26
+ for (let cursor = index + 1; cursor < source.length; cursor += 1) {
27
+ // Swift interpolation `\(…)` may itself contain quotes: `"a \(x ? "y" : "n")"`.
28
+ if (quote === "\"" && source[cursor] === "\\" && source[cursor + 1] === "(") {
29
+ cursor = findMatching(source, cursor + 1, "(");
30
+ continue;
31
+ }
32
+ if (source[cursor] === "\\") {
33
+ cursor += 1;
34
+ continue;
35
+ }
36
+ if (source[cursor] === quote)
37
+ return cursor + 1;
38
+ }
39
+ throw syntaxError(`Unclosed ${quote} string in Mün source`, index);
40
+ }
41
+ function skipTemplate(source, index) {
42
+ for (let cursor = index + 1; cursor < source.length; cursor += 1) {
43
+ if (source[cursor] === "\\") {
44
+ cursor += 1;
45
+ continue;
46
+ }
47
+ if (source[cursor] === "`")
48
+ return cursor + 1;
49
+ if (source[cursor] !== "$" || source[cursor + 1] !== "{")
50
+ continue;
51
+ const close = findMatching(source, cursor + 1, "{");
52
+ cursor = close;
53
+ }
54
+ throw syntaxError("Unclosed template literal in Mün source", index);
55
+ }
56
+ function skipTrivia(source, index) {
57
+ let cursor = index;
58
+ while (cursor < source.length) {
59
+ if (/\s/.test(source[cursor])) {
60
+ cursor += 1;
61
+ continue;
62
+ }
63
+ if (source.startsWith("//", cursor) || source.startsWith("/*", cursor)) {
64
+ cursor = skipComment(source, cursor);
65
+ continue;
66
+ }
67
+ break;
68
+ }
69
+ return cursor;
70
+ }
71
+ function skipComment(source, index) {
72
+ if (source.startsWith("//", index)) {
73
+ const end = source.indexOf("\n", index + 2);
74
+ return end < 0 ? source.length : end;
75
+ }
76
+ const end = source.indexOf("*/", index + 2);
77
+ if (end < 0)
78
+ throw syntaxError("Unclosed block comment in Mün source", index);
79
+ return end + 2;
80
+ }
81
+ function regexCanStart(source, index) {
82
+ if (isRawHtmlClosingTag(source, index))
83
+ return false;
84
+ for (let cursor = index - 1; cursor >= 0; cursor -= 1) {
85
+ if (/\s/.test(source[cursor]))
86
+ continue;
87
+ if ("([{=,:;!?&|+-*%^~<>".includes(source[cursor]))
88
+ return true;
89
+ if (/[A-Za-z_$]/.test(source[cursor])) {
90
+ const end = cursor + 1;
91
+ while (cursor >= 0 && /[A-Za-z0-9_$]/.test(source[cursor]))
92
+ cursor -= 1;
93
+ const word = source.slice(cursor + 1, end);
94
+ // Same keyword set as the scanner: a regex literal may follow an
95
+ // expression keyword, but not an identifier or property access.
96
+ return regexAfterKeywords.has(word);
97
+ }
98
+ return false;
99
+ }
100
+ return true;
101
+ }
102
+ function skipRegex(source, index) {
103
+ let inClass = false;
104
+ for (let cursor = index + 1; cursor < source.length; cursor += 1) {
105
+ if (source[cursor] === "\\") {
106
+ cursor += 1;
107
+ continue;
108
+ }
109
+ if (source[cursor] === "[")
110
+ inClass = true;
111
+ if (source[cursor] === "]")
112
+ inClass = false;
113
+ if (source[cursor] === "/" && !inClass) {
114
+ cursor += 1;
115
+ while (/[A-Za-z]/.test(source[cursor] ?? ""))
116
+ cursor += 1;
117
+ return cursor;
118
+ }
119
+ if (source[cursor] === "\n" || source[cursor] === "\r")
120
+ throw syntaxError("Unclosed regular expression in Mün source", index);
121
+ }
122
+ throw syntaxError("Unclosed regular expression in Mün source", index);
123
+ }
124
+ function findMatching(source, openIndex, open) {
125
+ const stack = [open];
126
+ for (let cursor = openIndex + 1; cursor < source.length; cursor += 1) {
127
+ const character = source[cursor];
128
+ const next = source[cursor + 1];
129
+ if (character === "\"" || character === "'") {
130
+ cursor = skipQuoted(source, cursor) - 1;
131
+ continue;
132
+ }
133
+ if (character === "`") {
134
+ cursor = skipTemplate(source, cursor) - 1;
135
+ continue;
136
+ }
137
+ if (character === "/" && (next === "/" || next === "*")) {
138
+ cursor = skipComment(source, cursor) - 1;
139
+ continue;
140
+ }
141
+ if (character === "/" && regexCanStart(source, cursor)) {
142
+ cursor = skipRegex(source, cursor) - 1;
143
+ continue;
144
+ }
145
+ if (character === "(" || character === "{" || character === "[") {
146
+ stack.push(character);
147
+ continue;
148
+ }
149
+ if (character === ")" || character === "}" || character === "]") {
150
+ const expected = closing[stack[stack.length - 1]];
151
+ if (character !== expected)
152
+ throw syntaxError(`Unexpected ${character} in Mün source`, cursor);
153
+ stack.pop();
154
+ if (stack.length === 0)
155
+ return cursor;
156
+ }
157
+ }
158
+ throw syntaxError(`Unclosed ${open} block in Mün source`, openIndex);
159
+ }
160
+ function lineBreakBoundary(source, index) {
161
+ let previousIndex = index - 1;
162
+ while (previousIndex >= 0 && /\s/.test(source[previousIndex]))
163
+ previousIndex -= 1;
164
+ const previous = previousIndex >= 0 ? source[previousIndex] : undefined;
165
+ const nextIndex = skipTrivia(source, index + 1);
166
+ const next = source[nextIndex];
167
+ if (!previous || !next)
168
+ return true;
169
+ if (source.slice(nextIndex, nextIndex + 4) === "else")
170
+ return false;
171
+ if (",([{.=:+-*/%!&|?<>".includes(previous))
172
+ return false;
173
+ if (".),]}:;".includes(next))
174
+ return false;
175
+ return true;
176
+ }
177
+ function splitTopLevel(source, separators, baseOffset) {
178
+ const parts = [];
179
+ let start = 0;
180
+ const stack = [];
181
+ for (let cursor = 0; cursor < source.length; cursor += 1) {
182
+ const character = source[cursor];
183
+ const next = source[cursor + 1];
184
+ if (character === "\"" || character === "'") {
185
+ cursor = skipQuoted(source, cursor) - 1;
186
+ continue;
187
+ }
188
+ if (character === "`") {
189
+ cursor = skipTemplate(source, cursor) - 1;
190
+ continue;
191
+ }
192
+ if (character === "/" && (next === "/" || next === "*")) {
193
+ cursor = skipComment(source, cursor) - 1;
194
+ continue;
195
+ }
196
+ if (character === "/" && regexCanStart(source, cursor)) {
197
+ cursor = skipRegex(source, cursor) - 1;
198
+ continue;
199
+ }
200
+ if (character === "(" || character === "{" || character === "[")
201
+ stack.push(character);
202
+ else if (character === ")" || character === "}" || character === "]") {
203
+ if (stack.length > 0)
204
+ stack.pop();
205
+ }
206
+ const boundary = stack.length === 0 && (separators.includes(character) || (character === "\n" && lineBreakBoundary(source, cursor)));
207
+ if (boundary) {
208
+ parts.push({ source: source.slice(start, cursor), start: baseOffset + start, end: baseOffset + cursor });
209
+ start = cursor + 1;
210
+ }
211
+ }
212
+ parts.push({ source: source.slice(start), start: baseOffset + start, end: baseOffset + source.length });
213
+ return parts.filter(part => part.source.trim().length > 0);
214
+ }
215
+ function trimSlice(slice) {
216
+ const leading = slice.source.search(/\S|$/);
217
+ const trimmed = slice.source.trimEnd();
218
+ return { source: trimmed.slice(leading), start: slice.start + leading, end: slice.start + trimmed.length };
219
+ }
220
+ function raw(slice) {
221
+ const value = trimSlice(slice);
222
+ return { kind: "raw", source: value.source, range: { start: value.start, end: value.end } };
223
+ }
224
+ function parseClosure(slice) {
225
+ const value = trimSlice(slice);
226
+ if (value.source[0] !== "{")
227
+ return undefined;
228
+ const close = findMatching(value.source, 0, "{");
229
+ if (close !== value.source.length - 1)
230
+ return undefined;
231
+ const inner = value.source.slice(1, close);
232
+ const parameter = /^\s*([A-Za-z_$][A-Za-z0-9_$]*)\s+in\s+/.exec(inner);
233
+ // A direct object argument is not a Mun closure. Check the first member
234
+ // rather than any colon: closure bodies legitimately contain ternaries.
235
+ if (!parameter && /^(?:\s*(?:[A-Za-z_$][A-Za-z0-9_$]*|["'][^"']*["']|-?\d+(?:\.\d+)?)\s*:)/.test(inner))
236
+ return undefined;
237
+ const bodySource = parameter ? inner.slice(parameter[0].length) : inner;
238
+ const bodyOffset = value.start + 1 + (parameter ? parameter[0].length : 0);
239
+ return {
240
+ kind: "closure",
241
+ parameter: parameter?.[1],
242
+ bodySource,
243
+ body: parseMunBuilder(bodySource, bodyOffset),
244
+ range: { start: value.start, end: value.end },
245
+ };
246
+ }
247
+ function topLevelColon(source) {
248
+ const slices = splitTopLevel(source, ":", 0);
249
+ return slices.length > 1 ? slices[0].source.length : -1;
250
+ }
251
+ function parseArgument(slice) {
252
+ const value = trimSlice(slice);
253
+ const colon = topLevelColon(value.source);
254
+ const labelStart = skipTrivia(value.source, 0);
255
+ const label = colon < 0 ? undefined : value.source.slice(labelStart, colon).trim();
256
+ if (label && !/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(label))
257
+ return { value: raw(value), range: { start: value.start, end: value.end } };
258
+ const valueSlice = colon < 0
259
+ ? value
260
+ : { source: value.source.slice(colon + 1), start: value.start + colon + 1, end: value.end };
261
+ return { label, value: parseClosure(valueSlice) ?? raw(valueSlice), range: { start: value.start, end: value.end } };
262
+ }
263
+ function parseCall(slice) {
264
+ const value = trimSlice(slice);
265
+ const identifier = /^([A-Za-z_$][A-Za-z0-9_$]*)/.exec(value.source);
266
+ if (!identifier)
267
+ return undefined;
268
+ const open = skipTrivia(value.source, identifier[0].length);
269
+ // Swift allows a call with only a trailing closure: `ZStack { … }`.
270
+ if (value.source[open] === "{" && /^[A-Z]/.test(identifier[1])) {
271
+ const trailingClose = findMatching(value.source, open, "{");
272
+ if (skipTrivia(value.source, trailingClose + 1) !== value.source.length)
273
+ return undefined;
274
+ const trailing = parseClosure({ source: value.source.slice(open, trailingClose + 1), start: value.start + open, end: value.start + trailingClose + 1 });
275
+ if (!trailing)
276
+ return undefined;
277
+ return { kind: "call", callee: identifier[1], arguments: [], trailing, range: { start: value.start, end: value.end } };
278
+ }
279
+ if (value.source[open] !== "(")
280
+ return undefined;
281
+ const close = findMatching(value.source, open, "(");
282
+ const afterClose = skipTrivia(value.source, close + 1);
283
+ let trailing;
284
+ let end = close + 1;
285
+ if (value.source[afterClose] === "{") {
286
+ const trailingClose = findMatching(value.source, afterClose, "{");
287
+ if (skipTrivia(value.source, trailingClose + 1) !== value.source.length)
288
+ return undefined;
289
+ trailing = parseClosure({ source: value.source.slice(afterClose, trailingClose + 1), start: value.start + afterClose, end: value.start + trailingClose + 1 });
290
+ // A block after a call is only Mun syntax when it is a closure. Do not
291
+ // consume an object-like block and silently drop it from the generated
292
+ // TypeScript when the source is ordinary or malformed JavaScript.
293
+ if (!trailing)
294
+ return undefined;
295
+ end = trailingClose + 1;
296
+ }
297
+ if (skipTrivia(value.source, end) !== value.source.length)
298
+ return undefined;
299
+ return {
300
+ kind: "call",
301
+ callee: identifier[1],
302
+ arguments: splitTopLevel(value.source.slice(open + 1, close), ",", value.start + open + 1).map(parseArgument),
303
+ trailing,
304
+ range: { start: value.start, end: value.end },
305
+ };
306
+ }
307
+ function parseConditional(slice) {
308
+ const value = trimSlice(slice);
309
+ if (!/^if\b/.test(value.source))
310
+ return undefined;
311
+ const conditionStart = skipTrivia(value.source, 2);
312
+ let conditionSourceStart = conditionStart;
313
+ let conditionEnd;
314
+ let thenOpen;
315
+ if (value.source[conditionStart] === "(") {
316
+ const close = findMatching(value.source, conditionStart, "(");
317
+ conditionSourceStart = conditionStart + 1;
318
+ conditionEnd = close;
319
+ thenOpen = skipTrivia(value.source, close + 1);
320
+ }
321
+ else {
322
+ let parenDepth = 0;
323
+ let bracketDepth = 0;
324
+ let cursor = conditionStart;
325
+ for (; cursor < value.source.length; cursor += 1) {
326
+ const character = value.source[cursor];
327
+ if (character === "\"" || character === "'" || character === "`") {
328
+ cursor = skipQuoted(value.source, cursor) - 1;
329
+ continue;
330
+ }
331
+ if (character === "(")
332
+ parenDepth += 1;
333
+ else if (character === ")")
334
+ parenDepth -= 1;
335
+ else if (character === "[")
336
+ bracketDepth += 1;
337
+ else if (character === "]")
338
+ bracketDepth -= 1;
339
+ else if (character === "{" && parenDepth === 0 && bracketDepth === 0)
340
+ break;
341
+ }
342
+ if (cursor >= value.source.length)
343
+ return undefined;
344
+ thenOpen = cursor;
345
+ conditionEnd = cursor;
346
+ }
347
+ if (value.source[thenOpen] !== "{")
348
+ return undefined;
349
+ const thenClose = findMatching(value.source, thenOpen, "{");
350
+ const afterThen = skipTrivia(value.source, thenClose + 1);
351
+ const condition = raw({
352
+ source: value.source.slice(conditionSourceStart, conditionEnd),
353
+ start: value.start + conditionSourceStart,
354
+ end: value.start + conditionEnd,
355
+ });
356
+ let otherwise;
357
+ if (value.source.slice(afterThen, afterThen + 4) === "else" && !/[A-Za-z0-9_$]/.test(value.source[afterThen + 4] ?? "")) {
358
+ const elseStart = skipTrivia(value.source, afterThen + 4);
359
+ const rest = { source: value.source.slice(elseStart), start: value.start + elseStart, end: value.end };
360
+ if (/^if\b/.test(rest.source)) {
361
+ otherwise = parseConditional(rest);
362
+ if (!otherwise)
363
+ return undefined;
364
+ }
365
+ else if (rest.source[0] === "{") {
366
+ const elseClose = findMatching(rest.source, 0, "{");
367
+ if (skipTrivia(rest.source, elseClose + 1) !== rest.source.length)
368
+ return undefined;
369
+ otherwise = parseMunBuilder(rest.source.slice(1, elseClose), rest.start + 1);
370
+ }
371
+ else
372
+ return undefined;
373
+ }
374
+ else if (afterThen !== value.source.length) {
375
+ // Keep parser ownership of the entire slice. Without this guard, a
376
+ // conditional followed by another expression is accepted and the suffix
377
+ // disappears during AST lowering.
378
+ return undefined;
379
+ }
380
+ return {
381
+ kind: "conditional",
382
+ condition,
383
+ then: parseMunBuilder(value.source.slice(thenOpen + 1, thenClose), value.start + thenOpen + 1),
384
+ otherwise,
385
+ range: { start: value.start, end: value.end },
386
+ };
387
+ }
388
+ /**
389
+ * Swift `switch` over a scalar subject, desugared to an `if`/`else if` chain:
390
+ * `case 1, 2:` becomes `subject == 1 || subject == 2`. Patterns are literals;
391
+ * other Swift patterns are diagnosed. Like Swift, the switch must be
392
+ * exhaustive (a `default:` unless the cases are `true` and `false`).
393
+ */
394
+ function parseSwitch(slice) {
395
+ const value = trimSlice(slice);
396
+ if (!/^switch\b/.test(value.source))
397
+ return undefined;
398
+ let open = -1;
399
+ for (let cursor = 6, depth = 0; cursor < value.source.length; cursor += 1) {
400
+ const character = value.source[cursor];
401
+ if (character === "\"" || character === "'") {
402
+ cursor = skipQuoted(value.source, cursor) - 1;
403
+ continue;
404
+ }
405
+ if (character === "(" || character === "[")
406
+ depth += 1;
407
+ else if (character === ")" || character === "]")
408
+ depth -= 1;
409
+ else if (character === "{" && depth === 0) {
410
+ open = cursor;
411
+ break;
412
+ }
413
+ }
414
+ if (open < 0)
415
+ throw new SyntaxError("switch requires a { case … } body");
416
+ const close = findMatching(value.source, open, "{");
417
+ if (skipTrivia(value.source, close + 1) !== value.source.length)
418
+ return undefined;
419
+ const subject = value.source.slice(6, open).trim().replace(/^\(([\s\S]*)\)$/, "$1").trim();
420
+ if (!subject)
421
+ throw new SyntaxError("switch requires a subject expression");
422
+ const body = value.source.slice(open + 1, close);
423
+ const bodyStart = value.start + open + 1;
424
+ // Labels (`case …:` / `default:`) at statement starts of the switch body.
425
+ const labels = [];
426
+ let lineStart = true;
427
+ for (let cursor = 0, depth = 0; cursor < body.length; cursor += 1) {
428
+ const character = body[cursor];
429
+ if (character === "\"" || character === "'") {
430
+ cursor = skipQuoted(body, cursor) - 1;
431
+ lineStart = false;
432
+ continue;
433
+ }
434
+ if (character === "\n" || character === ";") {
435
+ lineStart = true;
436
+ continue;
437
+ }
438
+ if (/\s/.test(character))
439
+ continue;
440
+ if ("([{".includes(character))
441
+ depth += 1;
442
+ else if (")]}".includes(character))
443
+ depth -= 1;
444
+ if (depth === 0 && lineStart && /^(?:case\b|default\s*:)/.test(body.slice(cursor))) {
445
+ const isDefault = body.startsWith("default", cursor);
446
+ let colon = -1;
447
+ for (let scan = cursor + (isDefault ? 7 : 4), inner = 0; scan < body.length; scan += 1) {
448
+ const next = body[scan];
449
+ if (next === "\"" || next === "'") {
450
+ scan = skipQuoted(body, scan) - 1;
451
+ continue;
452
+ }
453
+ if ("([{".includes(next))
454
+ inner += 1;
455
+ else if (")]}".includes(next))
456
+ inner -= 1;
457
+ else if (next === ":" && inner === 0) {
458
+ colon = scan;
459
+ break;
460
+ }
461
+ }
462
+ if (colon < 0)
463
+ throw new SyntaxError("switch case label requires ':'");
464
+ labels.push({ start: cursor, colon, ...(isDefault ? {} : { pattern: body.slice(cursor + 4, colon).trim() }) });
465
+ cursor = colon;
466
+ }
467
+ lineStart = false;
468
+ }
469
+ if (labels.length === 0)
470
+ throw new SyntaxError("switch requires at least one case");
471
+ if (body.slice(0, labels[0].start).trim())
472
+ throw new SyntaxError("switch body must start with a case label");
473
+ const seen = new Set();
474
+ const cases = labels.map((label, index) => {
475
+ const end = labels[index + 1]?.start ?? body.length;
476
+ const caseSource = body.slice(label.colon + 1, end);
477
+ if (!caseSource.trim()) {
478
+ throw new SyntaxError(`switch ${label.pattern === undefined ? "default" : `case ${label.pattern}`} has no Views; every case needs at least one`);
479
+ }
480
+ const program = parseMunBuilder(caseSource, bodyStart + label.colon + 1);
481
+ if (label.pattern === undefined) {
482
+ if (index !== labels.length - 1)
483
+ throw new SyntaxError("switch default must be the last case");
484
+ return { program };
485
+ }
486
+ const patterns = splitTopLevel(label.pattern, ",", 0).map(item => item.source.trim());
487
+ for (const pattern of patterns) {
488
+ if (/\bwhere\b/.test(pattern))
489
+ throw new SyntaxError(`switch case 'where' clauses are not supported in Mün: case ${label.pattern}`);
490
+ if (/\.\.[.<]/.test(pattern))
491
+ throw new SyntaxError(`switch range patterns are not supported in Mün; use if with comparisons: case ${pattern}`);
492
+ if (!/^(?:-?\d+(?:\.\d+)?|"(?:[^"\\]|\\.)*"|true|false)$/.test(pattern)) {
493
+ throw new SyntaxError(`switch case patterns must be String, number or Bool literals in Mün: case ${pattern}`);
494
+ }
495
+ if (seen.has(pattern))
496
+ throw new SyntaxError(`switch case ${pattern} is repeated`);
497
+ seen.add(pattern);
498
+ }
499
+ if (/^\s*fallthrough\b/m.test(caseSource))
500
+ throw new SyntaxError("fallthrough is not supported in Mün switch");
501
+ return { patterns, program };
502
+ });
503
+ const exhaustive = cases.at(-1)?.patterns === undefined || (seen.has("true") && seen.has("false") && seen.size === 2);
504
+ if (!exhaustive)
505
+ throw new SyntaxError(`switch over '${subject}' must be exhaustive: add a default case`);
506
+ const range = { start: value.start, end: value.end };
507
+ const chain = (index) => {
508
+ const item = cases[index];
509
+ if (!item.patterns)
510
+ return item.program;
511
+ if (index === cases.length - 1)
512
+ return item.program;
513
+ const condition = item.patterns.map(pattern => `(${subject}) == ${pattern}`).join(" || ");
514
+ return {
515
+ kind: "conditional",
516
+ condition: { kind: "raw", source: condition, range },
517
+ then: item.program,
518
+ otherwise: chain(index + 1),
519
+ range,
520
+ };
521
+ };
522
+ return chain(0);
523
+ }
524
+ function parseNode(slice) {
525
+ const switched = parseSwitch(slice);
526
+ if (switched) {
527
+ // A switch whose only case is `default` is just its Views.
528
+ return switched.kind === "program"
529
+ ? { kind: "conditional", condition: { kind: "raw", source: "true", range: switched.range }, then: switched, range: switched.range }
530
+ : switched;
531
+ }
532
+ return parseConditional(slice) ?? parseCall(slice) ?? raw(slice);
533
+ }
534
+ export function parseMunBuilder(source, baseOffset = 0) {
535
+ return { kind: "program", source, range: { start: baseOffset, end: baseOffset + source.length }, statements: splitTopLevel(source, ",;", baseOffset).map(parseNode) };
536
+ }
537
+ function findStructs(source, start) {
538
+ for (let cursor = start; cursor < source.length; cursor += 1) {
539
+ const character = source[cursor];
540
+ const next = source[cursor + 1];
541
+ if (character === "\"" || character === "'") {
542
+ cursor = skipQuoted(source, cursor) - 1;
543
+ continue;
544
+ }
545
+ if (character === "`") {
546
+ cursor = skipTemplate(source, cursor) - 1;
547
+ continue;
548
+ }
549
+ if (character === "/" && (next === "/" || next === "*")) {
550
+ cursor = skipComment(source, cursor) - 1;
551
+ continue;
552
+ }
553
+ if (character === "/" && regexCanStart(source, cursor)) {
554
+ cursor = skipRegex(source, cursor) - 1;
555
+ continue;
556
+ }
557
+ if (!source.startsWith("struct", cursor))
558
+ continue;
559
+ if (identifierPart(source[cursor - 1]) || identifierPart(source[cursor + 6]))
560
+ continue;
561
+ return cursor;
562
+ }
563
+ return -1;
564
+ }
565
+ /**
566
+ * Top-level `var name: Type { ... }` members other than `body`. A non-empty
567
+ * type before the brace distinguishes a computed property from a stored
568
+ * property whose type is an object literal (`var x: { a: number }`).
569
+ */
570
+ function findComputedProperties(source) {
571
+ const found = [];
572
+ let braces = 0;
573
+ for (let cursor = 0; cursor < source.length; cursor += 1) {
574
+ const character = source[cursor];
575
+ const next = source[cursor + 1];
576
+ if (character === "\"" || character === "'") {
577
+ cursor = skipQuoted(source, cursor) - 1;
578
+ continue;
579
+ }
580
+ if (character === "`") {
581
+ cursor = skipTemplate(source, cursor) - 1;
582
+ continue;
583
+ }
584
+ if (character === "/" && (next === "/" || next === "*")) {
585
+ cursor = skipComment(source, cursor) - 1;
586
+ continue;
587
+ }
588
+ if (character === "/" && regexCanStart(source, cursor)) {
589
+ cursor = skipRegex(source, cursor) - 1;
590
+ continue;
591
+ }
592
+ if (braces === 0 && source.startsWith("var", cursor) && !identifierPart(source[cursor - 1]) && !identifierPart(source[cursor + 3])) {
593
+ const match = /^var\s+([A-Za-z_$][A-Za-z0-9_$]*)\s*:\s*([^={};\n]*[^={};\s])\s*\{/.exec(source.slice(cursor));
594
+ if (match && match[1] !== "body") {
595
+ const open = cursor + match[0].length - 1;
596
+ const close = findMatching(source, open, "{");
597
+ const lineStart = source.lastIndexOf("\n", cursor) + 1;
598
+ const prefix = /(?:(?:@ViewBuilder|private|fileprivate|internal|public)\s+)*$/.exec(source.slice(lineStart, cursor))?.[0] ?? "";
599
+ found.push({ name: match[1], type: match[2].trim(), start: cursor - prefix.length, open, close });
600
+ cursor = close;
601
+ continue;
602
+ }
603
+ }
604
+ if (character === "{")
605
+ braces += 1;
606
+ else if (character === "}")
607
+ braces -= 1;
608
+ }
609
+ return found;
610
+ }
611
+ /** Top-level `func` members of a struct body. */
612
+ function findStructMethods(source, baseOffset = 0) {
613
+ const found = [];
614
+ let braces = 0;
615
+ for (let cursor = 0; cursor < source.length; cursor += 1) {
616
+ const character = source[cursor];
617
+ const next = source[cursor + 1];
618
+ if (character === "\"" || character === "'") {
619
+ cursor = skipQuoted(source, cursor) - 1;
620
+ continue;
621
+ }
622
+ if (character === "`") {
623
+ cursor = skipTemplate(source, cursor) - 1;
624
+ continue;
625
+ }
626
+ if (character === "/" && (next === "/" || next === "*")) {
627
+ cursor = skipComment(source, cursor) - 1;
628
+ continue;
629
+ }
630
+ if (braces === 0 && source.startsWith("func", cursor) && !identifierPart(source[cursor - 1]) && !identifierPart(source[cursor + 4])) {
631
+ const match = /^func\s+([A-Za-z_$][A-Za-z0-9_$]*)\s*\(/.exec(source.slice(cursor));
632
+ if (match) {
633
+ const parametersOpen = cursor + match[0].length - 1;
634
+ const parametersClose = findMatching(source, parametersOpen, "(");
635
+ const open = source.indexOf("{", parametersClose);
636
+ if (open < 0)
637
+ throw syntaxError(`Method ${match[1]} must have a body`, baseOffset + cursor);
638
+ const effects = source.slice(parametersClose + 1, open).trim();
639
+ if (!/^(?:async\b\s*)?(?:->\s*[^{}]+)?$/.test(effects)) {
640
+ throw syntaxError(`Unsupported method effects '${effects}'; use async and an optional -> result type. Handle failures with try/catch in the method body.`, baseOffset + parametersClose + 1);
641
+ }
642
+ const close = findMatching(source, open, "{");
643
+ const lineStart = source.lastIndexOf("\n", cursor) + 1;
644
+ const prefix = /(?:(?:@MainActor|private|fileprivate|internal|public|mutating|static)\s+)*$/.exec(source.slice(lineStart, cursor))?.[0] ?? "";
645
+ found.push({
646
+ name: match[1],
647
+ parameters: source.slice(parametersOpen + 1, parametersClose),
648
+ asynchronous: /^async\b/.test(effects),
649
+ returnType: /->\s*([\s\S]+)$/.exec(effects)?.[1].trim(),
650
+ start: cursor - prefix.length,
651
+ open,
652
+ close,
653
+ });
654
+ cursor = close;
655
+ continue;
656
+ }
657
+ }
658
+ if (character === "{")
659
+ braces += 1;
660
+ else if (character === "}")
661
+ braces -= 1;
662
+ }
663
+ return found;
664
+ }
665
+ function maskRanges(source, ranges) {
666
+ if (ranges.length === 0)
667
+ return source;
668
+ const characters = [...source];
669
+ for (const range of ranges) {
670
+ for (let index = range.start; index <= range.close; index += 1) {
671
+ if (characters[index] !== "\n" && characters[index] !== "\r")
672
+ characters[index] = " ";
673
+ }
674
+ }
675
+ return characters.join("");
676
+ }
677
+ function findTopLevelBodyExpression(source) {
678
+ let braces = 0;
679
+ for (let cursor = 0; cursor < source.length; cursor += 1) {
680
+ const character = source[cursor];
681
+ const next = source[cursor + 1];
682
+ if (character === "\"" || character === "'") {
683
+ cursor = skipQuoted(source, cursor) - 1;
684
+ continue;
685
+ }
686
+ if (character === "`") {
687
+ cursor = skipTemplate(source, cursor) - 1;
688
+ continue;
689
+ }
690
+ if (character === "/" && (next === "/" || next === "*")) {
691
+ cursor = skipComment(source, cursor) - 1;
692
+ continue;
693
+ }
694
+ if (character === "/" && regexCanStart(source, cursor)) {
695
+ cursor = skipRegex(source, cursor) - 1;
696
+ continue;
697
+ }
698
+ if (braces === 0 && source.startsWith("var", cursor) && !identifierPart(source[cursor - 1]) && !identifierPart(source[cursor + 3])) {
699
+ const match = /^var\s+body\s*:[^{]*\{/.exec(source.slice(cursor));
700
+ if (match) {
701
+ const open = cursor + match[0].lastIndexOf("{");
702
+ return { declarationStart: cursor, open, close: findMatching(source, open, "{") };
703
+ }
704
+ }
705
+ if (character === "{")
706
+ braces += 1;
707
+ else if (character === "}")
708
+ braces -= 1;
709
+ }
710
+ return undefined;
711
+ }
712
+ function maskNestedStructs(source) {
713
+ const characters = [...source];
714
+ let cursor = 0;
715
+ while (cursor < source.length) {
716
+ const index = findStructs(source, cursor);
717
+ if (index < 0)
718
+ break;
719
+ const header = /^struct\s+([A-Za-z_$][A-Za-z0-9_$]*)(?:\s*<([^>{}]*)>)?\s*:\s*View\b/.exec(source.slice(index));
720
+ if (!header) {
721
+ cursor = index + 6;
722
+ continue;
723
+ }
724
+ const brace = source.indexOf("{", index + header[0].length);
725
+ if (brace < 0)
726
+ break;
727
+ const close = findMatching(source, brace, "{");
728
+ for (let position = index; position <= close; position += 1) {
729
+ if (characters[position] !== "\n" && characters[position] !== "\r")
730
+ characters[position] = " ";
731
+ }
732
+ cursor = close + 1;
733
+ }
734
+ return characters.join("");
735
+ }
736
+ function maskInitializerBodies(source) {
737
+ const masked = [...source];
738
+ let cursor = 0;
739
+ while (true) {
740
+ const initializer = findInitializer(source, cursor);
741
+ if (initializer < 0)
742
+ break;
743
+ const open = skipTrivia(source, initializer + 4);
744
+ const close = findMatching(source, open, "(");
745
+ const blockOpen = skipTrivia(source, close + 1);
746
+ if (source[blockOpen] !== "{") {
747
+ cursor = initializer + 4;
748
+ continue;
749
+ }
750
+ const blockClose = findMatching(source, blockOpen, "{");
751
+ for (let index = initializer; index <= blockClose; index += 1) {
752
+ if (masked[index] !== "\n" && masked[index] !== "\r")
753
+ masked[index] = " ";
754
+ }
755
+ cursor = blockClose + 1;
756
+ }
757
+ return masked.join("");
758
+ }
759
+ function findInitializer(source, start) {
760
+ for (let cursor = start; cursor < source.length; cursor += 1) {
761
+ const character = source[cursor];
762
+ const next = source[cursor + 1];
763
+ if (character === "\"" || character === "'") {
764
+ cursor = skipQuoted(source, cursor) - 1;
765
+ continue;
766
+ }
767
+ if (character === "`") {
768
+ cursor = skipTemplate(source, cursor) - 1;
769
+ continue;
770
+ }
771
+ if (character === "/" && (next === "/" || next === "*")) {
772
+ cursor = skipComment(source, cursor) - 1;
773
+ continue;
774
+ }
775
+ if (character === "/" && regexCanStart(source, cursor)) {
776
+ cursor = skipRegex(source, cursor) - 1;
777
+ continue;
778
+ }
779
+ if (!source.startsWith("init", cursor) || identifierPart(source[cursor - 1]) || identifierPart(source[cursor + 4]))
780
+ continue;
781
+ if (source[skipTrivia(source, cursor + 4)] === "(")
782
+ return cursor;
783
+ }
784
+ return -1;
785
+ }
786
+ /** End of a stored-property initializer: the first top-level newline or `;`. */
787
+ function initializerEnd(source, start) {
788
+ let depth = 0;
789
+ for (let cursor = start; cursor < source.length; cursor += 1) {
790
+ const character = source[cursor];
791
+ const next = source[cursor + 1];
792
+ if (character === "\"" || character === "'") {
793
+ cursor = skipQuoted(source, cursor) - 1;
794
+ continue;
795
+ }
796
+ if (character === "`") {
797
+ cursor = skipTemplate(source, cursor) - 1;
798
+ continue;
799
+ }
800
+ if (character === "/" && (next === "/" || next === "*")) {
801
+ cursor = skipComment(source, cursor) - 1;
802
+ continue;
803
+ }
804
+ if (character === "(" || character === "[" || character === "{")
805
+ depth += 1;
806
+ else if (character === ")" || character === "]" || character === "}") {
807
+ if (depth === 0)
808
+ return cursor;
809
+ depth -= 1;
810
+ }
811
+ else if (depth === 0 && (character === "\n" || character === ";"))
812
+ return cursor;
813
+ }
814
+ return source.length;
815
+ }
816
+ function parseStructMembers(body, baseOffset) {
817
+ const fields = [];
818
+ const initializers = [];
819
+ const nestedMaskedBody = maskNestedStructs(body);
820
+ const maskedBody = maskInitializerBodies(nestedMaskedBody);
821
+ // `=` starts a stored-property initializer, but the same character is also
822
+ // part of a TypeScript function type (`(value: string) => void`). Keep `=>`
823
+ // inside the type span instead of truncating the type and inventing a
824
+ // default value such as `> void`.
825
+ // `@State private var`, `private @State var`, `private let` …
826
+ const fieldPattern = /(?:^|[;\n])\s*(?:(private|fileprivate|internal|public)\s+)?(?:(@State|@Binding)\s+)?(?:(private|fileprivate|internal|public)\s+)?(?:let|var)\s+([A-Za-z_$][A-Za-z0-9_$]*)(?:\s*:\s*((?:(?:=>)|[^=\n;])+))?(?:\s*=(?!>)\s*([^\n;]+))?/g;
827
+ for (const match of maskedBody.matchAll(fieldPattern)) {
828
+ const [, accessBefore, wrapper, accessAfter, name, type, initializerSource] = match;
829
+ if (name === "body")
830
+ continue;
831
+ if (accessBefore && accessAfter)
832
+ throw new SyntaxError(`Member '${name}' declares its access level twice`);
833
+ const access = (accessBefore ?? accessAfter);
834
+ const start = baseOffset + (match.index ?? 0) + match[0].indexOf(name, match[0].search(/\b(?:let|var)\s/) + 4);
835
+ // An initializer may span lines inside brackets (`[\n { ... },\n]`); the
836
+ // regex only sees its first line, so read the balanced extent.
837
+ const initializerStart = initializerSource === undefined ? undefined : (match.index ?? 0) + match[0].length - initializerSource.length;
838
+ const initializer = initializerStart === undefined
839
+ ? undefined
840
+ : body.slice(initializerStart, initializerEnd(maskedBody, initializerStart)).trim();
841
+ fields.push({ name, kind: wrapper === "@State" ? "state" : wrapper === "@Binding" ? "binding" : "stored", ...(access ? { access } : {}), type: type?.trim(), initializer, range: { start, end: start + name.length } });
842
+ }
843
+ let cursor = 0;
844
+ while (true) {
845
+ const initializer = findInitializer(nestedMaskedBody, cursor);
846
+ if (initializer < 0)
847
+ break;
848
+ const open = skipTrivia(nestedMaskedBody, initializer + 4);
849
+ const close = findMatching(nestedMaskedBody, open, "(");
850
+ const blockOpen = skipTrivia(nestedMaskedBody, close + 1);
851
+ if (nestedMaskedBody[blockOpen] !== "{") {
852
+ cursor = initializer + 4;
853
+ continue;
854
+ }
855
+ const blockClose = findMatching(nestedMaskedBody, blockOpen, "{");
856
+ initializers.push({
857
+ parametersSource: body.slice(open + 1, close),
858
+ bodySource: body.slice(blockOpen + 1, blockClose),
859
+ range: { start: baseOffset + initializer, end: baseOffset + blockClose + 1 },
860
+ parametersRange: { start: baseOffset + open + 1, end: baseOffset + close },
861
+ bodyRange: { start: baseOffset + blockOpen + 1, end: baseOffset + blockClose },
862
+ });
863
+ cursor = blockClose + 1;
864
+ }
865
+ return { fields, initializers };
866
+ }
867
+ /**
868
+ * Parsed declarations keyed by their exact source text, with offsets relative
869
+ * to the declaration start. A declaration's parse depends only on its own
870
+ * text, so an unchanged View in an edited file is not reparsed. Bounded.
871
+ */
872
+ const parsedDeclarations = new Map();
873
+ const parsedDeclarationLimit = 4096;
874
+ let declarationsParsed = 0;
875
+ let declarationsReused = 0;
876
+ /** Cumulative struct-parse counters (development tooling diffs them per compile). */
877
+ export function munStructParseStats() {
878
+ return { parsed: declarationsParsed, reused: declarationsReused };
879
+ }
880
+ function shiftedRange(range, delta) {
881
+ return { start: range.start + delta, end: range.end + delta };
882
+ }
883
+ /** The same declaration with every source range moved by `delta`. */
884
+ export function shiftMunStruct(declaration, delta) {
885
+ if (delta === 0)
886
+ return declaration;
887
+ return {
888
+ ...declaration,
889
+ range: shiftedRange(declaration.range, delta),
890
+ bodyRange: shiftedRange(declaration.bodyRange, delta),
891
+ bodyExpressionRange: shiftedRange(declaration.bodyExpressionRange, delta),
892
+ fields: declaration.fields.map(field => ({ ...field, range: shiftedRange(field.range, delta) })),
893
+ initializers: declaration.initializers.map(initializer => ({
894
+ ...initializer,
895
+ range: shiftedRange(initializer.range, delta),
896
+ parametersRange: shiftedRange(initializer.parametersRange, delta),
897
+ bodyRange: shiftedRange(initializer.bodyRange, delta),
898
+ })),
899
+ ...(declaration.methods ? { methods: declaration.methods.map(method => ({ ...method, range: shiftedRange(method.range, delta), bodyRange: shiftedRange(method.bodyRange, delta) })) } : {}),
900
+ ...(declaration.environment ? { environment: declaration.environment.map(value => ({ ...value, range: shiftedRange(value.range, delta) })) } : {}),
901
+ ...(declaration.computed ? { computed: declaration.computed.map(property => ({ ...property, range: shiftedRange(property.range, delta) })) } : {}),
902
+ ...(declaration.nested ? { nested: declaration.nested.map(item => shiftMunStruct(item, delta)) } : {}),
903
+ };
904
+ }
905
+ export function parseMunStructs(source, baseOffset = 0) {
906
+ const declarations = [];
907
+ let cursor = 0;
908
+ while (cursor < source.length) {
909
+ const index = findStructs(source, cursor);
910
+ if (index < 0)
911
+ break;
912
+ const header = /^struct\s+([A-Za-z_$][A-Za-z0-9_$]*)(?:\s*<([^>{}]*)>)?\s*:\s*View\b/.exec(source.slice(index));
913
+ if (!header) {
914
+ cursor = index + 6;
915
+ continue;
916
+ }
917
+ const brace = source.indexOf("{", index + header[0].length);
918
+ if (brace < 0)
919
+ throw syntaxError(`Missing body for struct ${header[1]}`, baseOffset + index);
920
+ const close = findMatching(source, brace, "{");
921
+ const text = source.slice(index, close + 1);
922
+ const cached = parsedDeclarations.get(text);
923
+ if (cached) {
924
+ declarationsReused += 1;
925
+ declarations.push(shiftMunStruct(cached, baseOffset + index));
926
+ cursor = close + 1;
927
+ continue;
928
+ }
929
+ let parsed;
930
+ try {
931
+ parsed = parseStructDeclaration(text, header, text.indexOf("{", header[0].length), text.length - 1);
932
+ }
933
+ catch (error) {
934
+ if (typeof error?.offset === "number")
935
+ error.offset += baseOffset + index;
936
+ throw error;
937
+ }
938
+ declarationsParsed += 1;
939
+ if (parsedDeclarations.size >= parsedDeclarationLimit)
940
+ parsedDeclarations.clear();
941
+ parsedDeclarations.set(text, parsed);
942
+ declarations.push(shiftMunStruct(parsed, baseOffset + index));
943
+ cursor = close + 1;
944
+ }
945
+ return declarations;
946
+ }
947
+ /** Parse one declaration whose text starts at offset 0 (`struct Name: View {` … `}`). */
948
+ function parseStructDeclaration(source, header, brace, close) {
949
+ const bodySource = source.slice(brace + 1, close);
950
+ const bodyExpression = findTopLevelBodyExpression(bodySource);
951
+ if (!bodyExpression)
952
+ throw syntaxError(`struct ${header[1]} must declare var body`, 0);
953
+ const methods = findStructMethods(maskInitializerBodies(maskNestedStructs(bodySource)), brace + 1);
954
+ const computed = findComputedProperties(maskRanges(maskInitializerBodies(maskNestedStructs(bodySource)), methods));
955
+ const memberSource = maskRanges(maskInitializerBodies(maskNestedStructs(bodySource)), [...methods, ...computed, { start: bodyExpression.declarationStart, close: bodyExpression.close }]);
956
+ const environment = [...memberSource.matchAll(/(^|[;\n])[ \t]*@Environment\s*\(([^()\n]*)\)\s*(?:(?:private|fileprivate|internal|public)\s+)?var\s+([A-Za-z_$][A-Za-z0-9_$]*)(?:\s*:\s*[^=\n;]+)?/g)]
957
+ .map(match => ({ name: match[3], key: match[2].trim(), start: (match.index ?? 0) + match[1].length, close: (match.index ?? 0) + match[0].length - 1 }));
958
+ const members = parseStructMembers(maskRanges(bodySource, [...methods, ...computed, ...environment]).slice(0, bodyExpression.declarationStart), brace + 1);
959
+ return {
960
+ kind: "struct",
961
+ name: header[1],
962
+ genericParameters: header[2]?.trim(),
963
+ source,
964
+ bodySource,
965
+ bodyExpressionSource: bodySource.slice(bodyExpression.open + 1, bodyExpression.close),
966
+ range: { start: 0, end: close + 1 },
967
+ bodyRange: { start: brace + 1, end: close },
968
+ bodyExpressionRange: { start: brace + 1 + bodyExpression.open + 1, end: brace + 1 + bodyExpression.close },
969
+ fields: members.fields,
970
+ initializers: members.initializers,
971
+ ...(computed.length > 0 ? {
972
+ computed: computed.map(property => ({
973
+ name: property.name,
974
+ type: property.type,
975
+ bodySource: bodySource.slice(property.open + 1, property.close),
976
+ range: { start: brace + 1 + property.start, end: brace + 1 + property.close + 1 },
977
+ })),
978
+ } : {}),
979
+ ...(methods.length > 0 ? {
980
+ methods: methods.map(method => ({
981
+ name: method.name,
982
+ parametersSource: method.parameters,
983
+ asynchronous: method.asynchronous,
984
+ returnType: method.returnType,
985
+ bodyRange: { start: brace + 1 + method.open + 1, end: brace + 1 + method.close },
986
+ bodySource: bodySource.slice(method.open + 1, method.close),
987
+ range: { start: brace + 1 + method.start, end: brace + 1 + method.close + 1 },
988
+ })),
989
+ } : {}),
990
+ ...(environment.length > 0 ? {
991
+ environment: environment.map(value => ({
992
+ name: value.name,
993
+ key: value.key,
994
+ range: { start: brace + 1 + value.start, end: brace + 1 + value.close + 1 },
995
+ })),
996
+ } : {}),
997
+ nested: parseMunStructs(bodySource, brace + 1),
998
+ };
999
+ }
1000
+ function lowerProgram(program, lowering) {
1001
+ return program.statements.map(node => {
1002
+ if (node.kind === "raw")
1003
+ return lowering.transformRaw(node.source);
1004
+ if (node.kind === "call") {
1005
+ const positional = node.arguments.filter(argument => !argument.label).map((argument, argumentIndex) => argument.value.kind === "closure"
1006
+ ? lowering.closure(argument.value.bodySource, argument.value.parameter, lowering.closureRole?.(node, { position: "argument", argumentIndex, label: argument.label }))
1007
+ : lowering.transformArgument?.(argument.value.source, node, argumentIndex, argument.label) ?? lowering.transformRaw(argument.value.source));
1008
+ const named = node.arguments.filter(argument => argument.label).map((argument, argumentIndex) => `${argument.label}: ${argument.value.kind === "closure"
1009
+ ? lowering.closure(argument.value.bodySource, argument.value.parameter, lowering.closureRole?.(node, { position: "argument", argumentIndex, label: argument.label }))
1010
+ : lowering.transformArgument?.(argument.value.source, node, argumentIndex, argument.label) ?? lowering.transformRaw(argument.value.source)}`);
1011
+ const args = [...positional, ...(named.length ? [`namedArguments({ ${named.join(", ")} })`] : []), ...(node.trailing ? [lowering.closure(node.trailing.bodySource, node.trailing.parameter, lowering.closureRole?.(node, { position: "trailing" }))] : [])];
1012
+ return `${node.callee}(${args.join(", ")})`;
1013
+ }
1014
+ const thenBranch = lowerProgram(node.then, lowering).join(", ");
1015
+ const otherwise = !node.otherwise ? "[]" : node.otherwise.kind === "conditional" ? lowerProgram({ ...node.otherwise.then, statements: [node.otherwise] }, lowering)[0] : `[${lowerProgram(node.otherwise, lowering).join(", ")}]`;
1016
+ return `(${lowering.transformRaw(node.condition.source)} ? [${thenBranch}] : ${otherwise})`;
1017
+ });
1018
+ }
1019
+ export function lowerMunBuilderAst(program, lowering) {
1020
+ return lowerProgram(program, lowering);
1021
+ }
1022
+ //# sourceMappingURL=ast.js.map