@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/ui-ir.js ADDED
@@ -0,0 +1,2793 @@
1
+ import { horizontalAlignments, overlayAlignments, paddingEdges } from './native-member-contract.js';
2
+ import ts from "typescript";
3
+ import { compileMotionPlan as compileInheritedMotionPlan, curves as inheritedCurves, spring as inheritedSpring, timing as inheritedTiming } from "@mun-ui/animation/core";
4
+ import { Animation, munMotionPropertyBit, resolveSemanticInitializer, } from "@mun-ui/core";
5
+ import { munExtension, nativeModifierSymbols, nativeViewInitializerSymbols, swiftUIApiManifest, swiftUIUnsupportedInitializerSignatures, swiftUIUnsupportedModifierSignatures, } from "@mun-ui/core/swiftui-manifest";
6
+ import { parseMunBuilder, parseMunStructs, } from "./ast.js";
7
+ import { assertCanonicalMunSource } from "./analysis.js";
8
+ import { describeValueType, displayMunType, parseMunType, runtimeTypeName, validateCanonicalDeclarations, valueMatchesType } from "./value-types.js";
9
+ import { resolveContractCall, swiftTypeName } from "./native-contract.js";
10
+ import { lowerAnimationValue, lowerColor, lowerPaint, lowerTransitionValue, nativeValueImplementations, parseMemberChain, lowerFontValue, lowerFontWeight } from "./native-values.js";
11
+ import { semanticViewLookupCandidates, semanticViewsForStructs, } from "./semantic.js";
12
+ import { splitStatements, splitTopLevel } from "./scanner.js";
13
+ const emptyBindings = new Map();
14
+ const literal = (value) => ({ kind: "literal", value });
15
+ function unwrap(expression) {
16
+ let current = expression;
17
+ while (ts.isParenthesizedExpression(current))
18
+ current = current.expression;
19
+ return current;
20
+ }
21
+ /**
22
+ * Parsed expressions keyed by source text. TypeScript nodes are immutable, so
23
+ * an identical expression (within one compile or across development
24
+ * recompiles) is parsed once. Bounded: cleared when it grows past the limit.
25
+ */
26
+ const parsedExpressions = new Map();
27
+ const parsedExpressionLimit = 8192;
28
+ let parsedExpressionHits = 0;
29
+ let parsedExpressionMisses = 0;
30
+ /** Development counters for the expression cache; never part of the IR. */
31
+ export function parsedExpressionCacheStats() {
32
+ return { hits: parsedExpressionHits, misses: parsedExpressionMisses, size: parsedExpressions.size };
33
+ }
34
+ function parsedExpression(source) {
35
+ const cached = parsedExpressions.get(source);
36
+ if (cached) {
37
+ parsedExpressionHits += 1;
38
+ return cached;
39
+ }
40
+ parsedExpressionMisses += 1;
41
+ const expression = parseExpressionUncached(source);
42
+ if (parsedExpressions.size >= parsedExpressionLimit)
43
+ parsedExpressions.clear();
44
+ parsedExpressions.set(source, expression);
45
+ return expression;
46
+ }
47
+ function parseExpressionUncached(source) {
48
+ const file = ts.createSourceFile("mun-ui-expression.ts", `(${swiftDictionaryLiterals(source)})`, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS);
49
+ const statement = file.statements[0];
50
+ if (!statement || !ts.isExpressionStatement(statement)) {
51
+ throw new SyntaxError(`Expected Mün UI expression, received: ${source}`);
52
+ }
53
+ return unwrap(statement.expression);
54
+ }
55
+ /**
56
+ * TypeScript recovers from syntax errors (`[` parses as `[]`). State initial
57
+ * values are stored data, so a recovered tree must never become one.
58
+ */
59
+ /**
60
+ * Swift dictionary literals (`[:]`, `["a": 1, "b": 2]`) as record literals, so
61
+ * value expressions keep one parser. Array literals and ternaries are untouched.
62
+ */
63
+ function swiftDictionaryLiterals(source) {
64
+ let output = "";
65
+ for (let index = 0; index < source.length; index += 1) {
66
+ const character = source[index];
67
+ if (character === "\"" || character === "'" || character === "`") {
68
+ let end = index + 1;
69
+ while (end < source.length && source[end] !== character) {
70
+ // Swift interpolation `\(…)` may itself contain quotes.
71
+ if (character === "\"" && source[end] === "\\" && source[end + 1] === "(") {
72
+ end = matchingParenthesis(source, end + 1) + 1;
73
+ continue;
74
+ }
75
+ end += source[end] === "\\" ? 2 : 1;
76
+ }
77
+ const literal = source.slice(index, end + 1);
78
+ output += character === "\"" ? swiftInterpolation(literal) : literal;
79
+ index = end;
80
+ continue;
81
+ }
82
+ if (character !== "[") {
83
+ output += character;
84
+ continue;
85
+ }
86
+ let depth = 0;
87
+ let close = -1;
88
+ for (let scan = index; scan < source.length; scan += 1) {
89
+ const next = source[scan];
90
+ if (next === "\"" || next === "'") {
91
+ scan += 1;
92
+ while (scan < source.length && source[scan] !== next)
93
+ scan += source[scan] === "\\" ? 2 : 1;
94
+ continue;
95
+ }
96
+ if ("([{".includes(next))
97
+ depth += 1;
98
+ else if (")]}".includes(next) && --depth === 0) {
99
+ close = scan;
100
+ break;
101
+ }
102
+ }
103
+ if (close < 0) {
104
+ output += character;
105
+ continue;
106
+ }
107
+ const inner = source.slice(index + 1, close);
108
+ if (inner.trim() === ":") {
109
+ output += "{}";
110
+ index = close;
111
+ continue;
112
+ }
113
+ const entries = splitTopLevel(inner).filter(entry => entry.trim());
114
+ const pairs = entries.map(entry => {
115
+ let level = 0;
116
+ for (let scan = 0; scan < entry.length; scan += 1) {
117
+ const next = entry[scan];
118
+ if (next === "\"" || next === "'") {
119
+ scan += 1;
120
+ while (scan < entry.length && entry[scan] !== next)
121
+ scan += entry[scan] === "\\" ? 2 : 1;
122
+ continue;
123
+ }
124
+ if ("([{".includes(next))
125
+ level += 1;
126
+ else if (")]}".includes(next))
127
+ level -= 1;
128
+ else if (level === 0 && next === "?")
129
+ return undefined;
130
+ else if (level === 0 && next === ":")
131
+ return [entry.slice(0, scan).trim(), entry.slice(scan + 1).trim()];
132
+ }
133
+ return undefined;
134
+ });
135
+ if (entries.length > 0 && pairs.every(pair => pair !== undefined)) {
136
+ output += `{ ${pairs.map(pair => `${pair[0]}: ${swiftDictionaryLiterals(pair[1])}`).join(", ")} }`;
137
+ }
138
+ else {
139
+ output += `[${swiftDictionaryLiterals(inner)}]`;
140
+ }
141
+ index = close;
142
+ }
143
+ return output;
144
+ }
145
+ function matchingParenthesis(source, open) {
146
+ let depth = 0;
147
+ for (let index = open; index < source.length; index += 1) {
148
+ const character = source[index];
149
+ if (character === "\"") {
150
+ index += 1;
151
+ while (index < source.length && source[index] !== "\"") {
152
+ if (source[index] === "\\" && source[index + 1] === "(") {
153
+ index = matchingParenthesis(source, index + 1) + 1;
154
+ continue;
155
+ }
156
+ index += source[index] === "\\" ? 2 : 1;
157
+ }
158
+ continue;
159
+ }
160
+ if (character === "(")
161
+ depth += 1;
162
+ else if (character === ")" && --depth === 0)
163
+ return index;
164
+ }
165
+ throw new SyntaxError(`Unclosed string interpolation in Mün source: ${source}`);
166
+ }
167
+ /** `"Total: \(count) items"` → `("Total: " + String(count) + " items")`. */
168
+ function swiftInterpolation(literal) {
169
+ if (!literal.includes("\\("))
170
+ return literal;
171
+ const body = literal.slice(1, -1);
172
+ const parts = [];
173
+ let segment = "";
174
+ for (let index = 0; index < body.length; index += 1) {
175
+ if (body[index] === "\\" && body[index + 1] === "(") {
176
+ const close = matchingParenthesis(body, index + 1);
177
+ if (segment)
178
+ parts.push(`"${segment}"`);
179
+ segment = "";
180
+ parts.push(`String(${swiftDictionaryLiterals(body.slice(index + 2, close))})`);
181
+ index = close;
182
+ continue;
183
+ }
184
+ if (body[index] === "\\") {
185
+ segment += body.slice(index, index + 2);
186
+ index += 1;
187
+ continue;
188
+ }
189
+ segment += body[index];
190
+ }
191
+ if (segment)
192
+ parts.push(`"${segment}"`);
193
+ return `(${parts.join(" + ")})`;
194
+ }
195
+ /** Initial-value sources already proven well-formed; the check is pure. Bounded. */
196
+ const wellFormedValueSources = new Set();
197
+ function assertWellFormedValueSource(source, owner) {
198
+ if (wellFormedValueSources.has(source))
199
+ return;
200
+ const file = ts.createSourceFile("mun-ui-value.ts", `(${swiftDictionaryLiterals(source)})`, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS);
201
+ const diagnostics = file.parseDiagnostics;
202
+ if (file.statements.length !== 1 || (diagnostics?.length ?? 0) > 0) {
203
+ throw new SyntaxError(`${owner} has a malformed initial value: ${source}`);
204
+ }
205
+ if (wellFormedValueSources.size >= parsedExpressionLimit)
206
+ wellFormedValueSources.clear();
207
+ wellFormedValueSources.add(source);
208
+ }
209
+ function scalarFromExpression(expression) {
210
+ const value = unwrap(expression);
211
+ if (ts.isStringLiteral(value) || ts.isNoSubstitutionTemplateLiteral(value))
212
+ return value.text;
213
+ if (ts.isNumericLiteral(value))
214
+ return Number(value.text);
215
+ if (value.kind === ts.SyntaxKind.TrueKeyword)
216
+ return true;
217
+ if (value.kind === ts.SyntaxKind.FalseKeyword)
218
+ return false;
219
+ if (value.kind === ts.SyntaxKind.NullKeyword)
220
+ return null;
221
+ if (ts.isPrefixUnaryExpression(value) && value.operator === ts.SyntaxKind.MinusToken && ts.isNumericLiteral(unwrap(value.operand))) {
222
+ return -Number(unwrap(value.operand).text);
223
+ }
224
+ return undefined;
225
+ }
226
+ /** Fully static array/object/scalar literal values (collection initial state). */
227
+ function staticValueFromExpression(expression) {
228
+ const value = unwrap(expression);
229
+ const scalar = scalarFromExpression(value);
230
+ if (scalar !== undefined || value.kind === ts.SyntaxKind.NullKeyword)
231
+ return scalar ?? null;
232
+ if (ts.isArrayLiteralExpression(value)) {
233
+ const items = [];
234
+ for (const element of value.elements) {
235
+ const item = staticValueFromExpression(element);
236
+ if (item === undefined)
237
+ return undefined;
238
+ items.push(item);
239
+ }
240
+ return items;
241
+ }
242
+ if (ts.isObjectLiteralExpression(value)) {
243
+ const record = {};
244
+ for (const property of value.properties) {
245
+ if (!ts.isPropertyAssignment(property))
246
+ return undefined;
247
+ const name = propertyName(property.name);
248
+ if (name === undefined)
249
+ return undefined;
250
+ const field = staticValueFromExpression(property.initializer);
251
+ if (field === undefined)
252
+ return undefined;
253
+ record[name] = field;
254
+ }
255
+ return record;
256
+ }
257
+ return undefined;
258
+ }
259
+ function propertyName(name) {
260
+ if (ts.isIdentifier(name) || ts.isStringLiteral(name) || ts.isNumericLiteral(name))
261
+ return name.text;
262
+ return undefined;
263
+ }
264
+ /** `\.a.b` key paths; `\.self` (or absent) is the item itself. */
265
+ function keyPathFromSource(source) {
266
+ if (!source)
267
+ return ["id"];
268
+ const match = /^\\\.([A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)*)$/.exec(source.trim());
269
+ if (!match)
270
+ throw new SyntaxError(`ForEach id must be a key path such as \\.id: ${source}`);
271
+ return match[1] === "self" ? [] : match[1].split(".");
272
+ }
273
+ function binaryOperator(kind) {
274
+ switch (kind) {
275
+ case ts.SyntaxKind.PlusToken: return "add";
276
+ case ts.SyntaxKind.MinusToken: return "subtract";
277
+ case ts.SyntaxKind.AsteriskToken: return "multiply";
278
+ case ts.SyntaxKind.SlashToken: return "divide";
279
+ case ts.SyntaxKind.PercentToken: return "modulo";
280
+ case ts.SyntaxKind.EqualsEqualsToken:
281
+ case ts.SyntaxKind.EqualsEqualsEqualsToken: return "equal";
282
+ case ts.SyntaxKind.ExclamationEqualsToken:
283
+ case ts.SyntaxKind.ExclamationEqualsEqualsToken: return "notEqual";
284
+ case ts.SyntaxKind.LessThanToken: return "less";
285
+ case ts.SyntaxKind.LessThanEqualsToken: return "lessOrEqual";
286
+ case ts.SyntaxKind.GreaterThanToken: return "greater";
287
+ case ts.SyntaxKind.GreaterThanEqualsToken: return "greaterOrEqual";
288
+ case ts.SyntaxKind.AmpersandAmpersandToken: return "and";
289
+ case ts.SyntaxKind.BarBarToken: return "or";
290
+ default: return undefined;
291
+ }
292
+ }
293
+ function lowerValueExpression(source, bindings = emptyBindings) {
294
+ const expression = unwrap(parsedExpression(source));
295
+ const scalar = scalarFromExpression(expression);
296
+ if (scalar !== undefined || expression.kind === ts.SyntaxKind.NullKeyword)
297
+ return literal(scalar ?? null);
298
+ const staticValue = staticValueFromExpression(expression);
299
+ if (staticValue !== undefined)
300
+ return literal(staticValue);
301
+ if (ts.isIdentifier(expression)) {
302
+ const binding = bindings.get(expression.text);
303
+ if (binding)
304
+ return binding;
305
+ // Swift's `nil` is Mün's absent optional value.
306
+ if (expression.text === "nil")
307
+ return literal(null);
308
+ }
309
+ if (ts.isObjectLiteralExpression(expression)) {
310
+ const fields = {};
311
+ for (const property of expression.properties) {
312
+ if (ts.isShorthandPropertyAssignment(property)) {
313
+ fields[property.name.text] = lowerValueExpression(property.name.text, bindings);
314
+ continue;
315
+ }
316
+ const name = ts.isPropertyAssignment(property) ? propertyName(property.name) : undefined;
317
+ if (!ts.isPropertyAssignment(property) || name === undefined) {
318
+ throw new SyntaxError(`Native record fields must be plain property assignments: ${source}`);
319
+ }
320
+ fields[name] = lowerValueExpression(property.initializer.getText(), bindings);
321
+ }
322
+ return { kind: "record", fields };
323
+ }
324
+ if (ts.isPropertyAccessExpression(expression)) {
325
+ const base = expression.expression;
326
+ const name = expression.name.text;
327
+ const baseBinding = ts.isIdentifier(base) ? bindings.get(base.text) : undefined;
328
+ if (name !== "value" || baseBinding?.kind === "item") {
329
+ if (name === "count" || name === "length") {
330
+ const collection = lowerValueExpression(base.getText(), bindings);
331
+ if (collection.kind !== "item" || collection.path.length > 0 || name === "count") {
332
+ return { kind: "count", collection };
333
+ }
334
+ }
335
+ const lowered = name === "value" && baseBinding?.kind !== "item"
336
+ ? undefined
337
+ : lowerValueExpression(base.getText(), bindings);
338
+ if (lowered?.kind === "item")
339
+ return { ...lowered, path: [...lowered.path, name] };
340
+ }
341
+ }
342
+ if (ts.isCallExpression(expression)
343
+ && ts.isPropertyAccessExpression(expression.expression)
344
+ && expression.expression.name.text === "filter"
345
+ && expression.arguments.length === 1) {
346
+ const predicate = unwrap(expression.arguments[0]);
347
+ const parameter = ts.isArrowFunction(predicate) && predicate.parameters.length === 1
348
+ && ts.isIdentifier(predicate.parameters[0].name)
349
+ ? predicate.parameters[0].name.text
350
+ : undefined;
351
+ const body = parameter && ts.isArrowFunction(predicate) && !ts.isBlock(predicate.body)
352
+ ? unwrap(predicate.body)
353
+ : undefined;
354
+ const operator = body && ts.isBinaryExpression(body) ? binaryOperator(body.operatorToken.kind) : undefined;
355
+ const fieldPath = (side) => {
356
+ const path = [];
357
+ let current = unwrap(side);
358
+ while (ts.isPropertyAccessExpression(current)) {
359
+ path.unshift(current.name.text);
360
+ current = unwrap(current.expression);
361
+ }
362
+ return ts.isIdentifier(current) && current.text === parameter && path.length > 0 ? path : undefined;
363
+ };
364
+ if (body && ts.isBinaryExpression(body) && (operator === "equal" || operator === "notEqual")) {
365
+ const leftPath = fieldPath(body.left);
366
+ const rightPath = fieldPath(body.right);
367
+ const path = leftPath ?? rightPath;
368
+ const other = leftPath ? body.right : body.left;
369
+ if (path && !(leftPath && rightPath)) {
370
+ return {
371
+ kind: "filter",
372
+ collection: lowerValueExpression(expression.expression.expression.getText(), bindings),
373
+ path,
374
+ operator,
375
+ value: lowerValueExpression(other.getText(), bindings),
376
+ };
377
+ }
378
+ }
379
+ throw new SyntaxError(`Native collection filters must compare one item field with a value, e.g. items.filter(item => item.done == false): ${source}`);
380
+ }
381
+ if (ts.isPropertyAccessExpression(expression)
382
+ && expression.name.text === "value"
383
+ && ts.isIdentifier(expression.expression)) {
384
+ const binding = bindings.get(expression.expression.text);
385
+ if (binding?.kind === "state")
386
+ return binding;
387
+ return { kind: "state", state: expression.expression.text };
388
+ }
389
+ if (ts.isCallExpression(expression)
390
+ && ts.isIdentifier(expression.expression)
391
+ && expression.expression.text === "String"
392
+ && expression.arguments.length === 1) {
393
+ return {
394
+ kind: "stringify",
395
+ value: lowerValueExpression(expression.arguments[0].getText(), bindings),
396
+ };
397
+ }
398
+ if (ts.isBinaryExpression(expression)) {
399
+ const operator = binaryOperator(expression.operatorToken.kind);
400
+ if (operator) {
401
+ return {
402
+ kind: "binary",
403
+ operator,
404
+ left: lowerValueExpression(expression.left.getText(), bindings),
405
+ right: lowerValueExpression(expression.right.getText(), bindings),
406
+ };
407
+ }
408
+ }
409
+ if (ts.isPrefixUnaryExpression(expression) && expression.operator === ts.SyntaxKind.ExclamationToken) {
410
+ return { kind: "not", value: lowerValueExpression(expression.operand.getText(), bindings) };
411
+ }
412
+ if (ts.isConditionalExpression(expression)) {
413
+ return {
414
+ kind: "conditional",
415
+ condition: lowerValueExpression(expression.condition.getText(), bindings),
416
+ then: lowerValueExpression(expression.whenTrue.getText(), bindings),
417
+ otherwise: lowerValueExpression(expression.whenFalse.getText(), bindings),
418
+ };
419
+ }
420
+ throw new SyntaxError(`Expression is not yet representable in Mün semantic UI IR: ${source}`);
421
+ }
422
+ function semanticTypeForUiExpression(expression, stateTypes) {
423
+ if (expression.kind === "literal")
424
+ return expression.value === null ? "null" : typeof expression.value;
425
+ if (expression.kind === "state")
426
+ return stateTypes.get(expression.state);
427
+ if (expression.kind === "not")
428
+ return "boolean";
429
+ if (expression.kind === "stringify")
430
+ return "string";
431
+ if (expression.kind === "binary") {
432
+ if (["equal", "notEqual", "less", "lessOrEqual", "greater", "greaterOrEqual", "and", "or"].includes(expression.operator)) {
433
+ return "boolean";
434
+ }
435
+ if (expression.operator === "add") {
436
+ const left = semanticTypeForUiExpression(expression.left, stateTypes);
437
+ const right = semanticTypeForUiExpression(expression.right, stateTypes);
438
+ if (left === "string" && right === "string")
439
+ return "string";
440
+ }
441
+ return "number";
442
+ }
443
+ if (expression.kind === "conditional") {
444
+ const thenType = semanticTypeForUiExpression(expression.then, stateTypes);
445
+ const otherwiseType = semanticTypeForUiExpression(expression.otherwise, stateTypes);
446
+ return thenType && thenType === otherwiseType ? thenType : undefined;
447
+ }
448
+ if (expression.kind === "item")
449
+ return "dynamic";
450
+ if (expression.kind === "record")
451
+ return "object";
452
+ if (expression.kind === "count")
453
+ return "number";
454
+ if (expression.kind === "filter")
455
+ return "array";
456
+ return undefined;
457
+ }
458
+ function componentSemanticArgument(argument, bindings, stateTypes) {
459
+ if (argument.value.kind === "closure") {
460
+ return { label: argument.label, type: "function", sourceArgument: argument };
461
+ }
462
+ if (isBindingSource(argument.value.source)) {
463
+ const binding = bindingStateExpression(argument.value.source, bindings);
464
+ const underlyingType = stateTypes.get(binding.state);
465
+ return {
466
+ label: argument.label,
467
+ kind: "binding",
468
+ type: "binding",
469
+ ...(underlyingType ? { underlyingType } : {}),
470
+ sourceArgument: argument,
471
+ };
472
+ }
473
+ const implicitMember = /^\.([A-Za-z_$][A-Za-z0-9_$]*)$/.exec(argument.value.source.trim());
474
+ if (implicitMember) {
475
+ return {
476
+ label: argument.label,
477
+ // `.infinity` is CGFloat.infinity; other implicit members are enum cases.
478
+ type: implicitMember[1] === "infinity" ? "number" : "string",
479
+ value: implicitMember[1],
480
+ sourceArgument: argument,
481
+ };
482
+ }
483
+ const source = argument.value.source.trim();
484
+ if (/^(?:\[|Array\s*\()/.test(source)) {
485
+ return { label: argument.label, type: "array", sourceArgument: argument };
486
+ }
487
+ if (/^\{[\s\S]*\}$/.test(source)) {
488
+ return { label: argument.label, type: "object", sourceArgument: argument };
489
+ }
490
+ let type;
491
+ try {
492
+ type = semanticTypeForUiExpression(lowerValueExpression(argument.value.source, bindings), stateTypes);
493
+ }
494
+ catch {
495
+ type = undefined;
496
+ }
497
+ return {
498
+ label: argument.label,
499
+ ...(type ? { type } : {}),
500
+ sourceArgument: argument,
501
+ };
502
+ }
503
+ /**
504
+ * Collection state is typed structurally at runtime ("array"); a declared
505
+ * element type (`Task[]`, `Array<Task>`) is accepted for it. Element shapes are
506
+ * not checked here: the runtime validates keys when it materializes items.
507
+ */
508
+ function bindingTypeMatches(expected, actual) {
509
+ if (expected === actual)
510
+ return true;
511
+ let declared;
512
+ try {
513
+ declared = parseMunType(expected, { canonical: false, what: "@Binding" });
514
+ }
515
+ catch {
516
+ return false;
517
+ }
518
+ if (actual === "null")
519
+ return declared.kind === "optional";
520
+ return runtimeTypeName(declared) === actual;
521
+ }
522
+ function stateTypeMap(states) {
523
+ return new Map(states.map(state => [
524
+ state.name,
525
+ state.initial === null ? "null" : typeof state.initial,
526
+ ]));
527
+ }
528
+ function stateTarget(name, bindings) {
529
+ const binding = bindings.get(name);
530
+ return binding?.kind === "state" ? binding.state : name;
531
+ }
532
+ function isBindingSource(source) {
533
+ const trimmed = source.trim();
534
+ return /^\$[A-Za-z_$][A-Za-z0-9_$]*$/.test(trimmed)
535
+ || /^Binding\s*\(/.test(trimmed);
536
+ }
537
+ function bindingStateExpression(source, bindings) {
538
+ const trimmed = source.trim();
539
+ const shorthand = /^\$([A-Za-z_$][A-Za-z0-9_$]*)$/.exec(trimmed);
540
+ const constructor = /^Binding\s*\(\s*\$?([A-Za-z_$][A-Za-z0-9_$]*)\s*\)$/.exec(trimmed);
541
+ const name = shorthand?.[1] ?? constructor?.[1];
542
+ if (!name) {
543
+ const plain = /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(trimmed) ? ` — pass $${trimmed}` : "";
544
+ throw new SyntaxError(`A Binding is required, but '${trimmed}' is a value${plain}. Use $state or Binding(state).`);
545
+ }
546
+ const bound = bindings.get(name);
547
+ if (bound?.kind === "state")
548
+ return bound;
549
+ return { kind: "state", state: name };
550
+ }
551
+ function initializerDefaultSources(parametersSource, parameters) {
552
+ const declarations = splitTopLevel(parametersSource);
553
+ const defaults = new Map();
554
+ for (let index = 0; index < parameters.length; index += 1) {
555
+ const name = parameters[index]?.name;
556
+ const declaration = declarations[index];
557
+ if (!name || !declaration)
558
+ continue;
559
+ const equals = declaration.search(/=(?!>)/);
560
+ if (equals < 0)
561
+ continue;
562
+ defaults.set(name, declaration.slice(equals + 1).trim());
563
+ }
564
+ return defaults;
565
+ }
566
+ function explicitInitializerAssignments(bodySource) {
567
+ const assignments = new Map();
568
+ for (const statement of splitStatements(bodySource)) {
569
+ if (/^self\.init\s*\(/.test(statement)) {
570
+ throw new SyntaxError("Native explicit initializer delegation is not implemented yet");
571
+ }
572
+ const match = /^self\.([A-Za-z_$][A-Za-z0-9_$]*)\s*=(?!=|>)\s*([\s\S]+)$/.exec(statement);
573
+ if (!match) {
574
+ throw new SyntaxError(`Native explicit initializer supports direct self.field assignments only: ${statement}`);
575
+ }
576
+ assignments.set(match[1], match[2].trim());
577
+ }
578
+ return assignments;
579
+ }
580
+ function numberValue(source, fallback, bindings = emptyBindings) {
581
+ if (source === undefined)
582
+ return fallback;
583
+ const value = lowerValueExpression(source, bindings);
584
+ if (value.kind === "literal" && typeof value.value === "number" && Number.isFinite(value.value)) {
585
+ return value.value;
586
+ }
587
+ throw new SyntaxError(`Native semantic numeric value must be a finite static number: ${source}`);
588
+ }
589
+ function stringValue(source, fallback, bindings = emptyBindings) {
590
+ if (source === undefined)
591
+ return fallback;
592
+ const value = lowerValueExpression(source, bindings);
593
+ if (value.kind === "literal" && typeof value.value === "string")
594
+ return value.value;
595
+ throw new SyntaxError(`Native semantic string value must be static: ${source}`);
596
+ }
597
+ function bindingState(source, bindings, control) {
598
+ if (!source)
599
+ throw new SyntaxError(`${control} requires a Binding`);
600
+ return bindingStateExpression(source, bindings).state;
601
+ }
602
+ function rawArgument(call, label, positionalIndex) {
603
+ const labeled = call.arguments.find(argument => argument.label === label);
604
+ const argument = labeled ?? call.arguments.filter(item => item.label === undefined)[positionalIndex];
605
+ return argument?.value.kind === "raw" ? argument.value.source.trim() : undefined;
606
+ }
607
+ function stateDeclarations(source) {
608
+ const states = [];
609
+ const pattern = /\b(?:const|let)\s+([A-Za-z_$][\w$]*)\s*=\s*State\s*\(\s*([^\n;]+?)\s*\)/g;
610
+ let match;
611
+ while ((match = pattern.exec(source))) {
612
+ const expression = parsedExpression(match[2]);
613
+ const initial = scalarFromExpression(expression);
614
+ if (initial === undefined && expression.kind !== ts.SyntaxKind.NullKeyword) {
615
+ throw new SyntaxError(`Native semantic state '${match[1]}' requires a scalar initial value for now`);
616
+ }
617
+ states.push({ name: match[1], initial: initial ?? null });
618
+ }
619
+ return states;
620
+ }
621
+ /**
622
+ * The entry View: `@main struct App: View` (canonical, as in Swift) or the
623
+ * compatibility spelling `export default App()`. Without either, the first View.
624
+ */
625
+ function entryName(source, fallback) {
626
+ const main = [...source.matchAll(/@main\s+struct\s+([A-Za-z_$][\w$]*)/g)].map(match => match[1]);
627
+ if (main.length > 1)
628
+ throw new SyntaxError(`Only one View can be @main; found ${main.join(", ")}`);
629
+ const exported = source.match(/\bexport\s+default\s+([A-Za-z_$][\w$]*)\s*\(/)?.[1];
630
+ if (main[0] && exported && main[0] !== exported) {
631
+ throw new SyntaxError(`@main ${main[0]} and export default ${exported}() name different entry Views`);
632
+ }
633
+ return main[0] ?? exported ?? fallback;
634
+ }
635
+ /** Labeled/positional arguments of a collection method call. */
636
+ function collectionArguments(source) {
637
+ if (!source.trim())
638
+ return [];
639
+ return splitTopLevel(source).map(part => {
640
+ const labeled = /^([A-Za-z_$][\w$]*)\s*:\s*([\s\S]+)$/.exec(part.trim());
641
+ return labeled ? { label: labeled[1], source: labeled[2] } : { source: part.trim() };
642
+ });
643
+ }
644
+ function collectionAction(state, method, argumentSource, bindings) {
645
+ const args = collectionArguments(argumentSource);
646
+ const positional = args.filter(argument => argument.label === undefined);
647
+ const labeled = (label) => args.find(argument => argument.label === label)?.source;
648
+ const value = (expression, role) => {
649
+ if (!expression)
650
+ throw new SyntaxError(`Collection ${method} requires ${role}: ${state}.${method}(${argumentSource})`);
651
+ return lowerValueExpression(expression, bindings);
652
+ };
653
+ // Key paths are stamped from the rendering ForEach after lowering.
654
+ const base = { kind: "collection", state, keyPath: [] };
655
+ switch (method) {
656
+ case "insert":
657
+ return { ...base, operation: "insert", value: value(positional[0]?.source, "a value"), index: value(labeled("at"), "at: index") };
658
+ case "append":
659
+ return { ...base, operation: "append", value: value(positional[0]?.source, "a value") };
660
+ case "remove":
661
+ return { ...base, operation: "remove", key: value(positional[0]?.source ?? labeled("id"), "an item key") };
662
+ case "move":
663
+ return { ...base, operation: "move", key: value(positional[0]?.source, "an item key"), offset: value(labeled("by"), "by: offset") };
664
+ case "update": {
665
+ const key = value(positional[0]?.source, "an item key");
666
+ const fields = args.filter(argument => argument.label !== undefined);
667
+ if (fields.length === 0)
668
+ throw new SyntaxError(`Collection update requires field: value arguments: ${state}.update(${argumentSource})`);
669
+ const updates = fields.map(field => ({
670
+ ...base,
671
+ operation: "update",
672
+ key,
673
+ path: [field.label],
674
+ value: lowerValueExpression(field.source, bindings),
675
+ }));
676
+ return updates.length === 1 ? updates[0] : { kind: "sequence", actions: updates };
677
+ }
678
+ default:
679
+ throw new SyntaxError(`Unsupported native collection operation '${method}'`);
680
+ }
681
+ }
682
+ /** Operating-system service calls: owner → service, operation → arity, whether it yields a value. */
683
+ const hostOperations = {
684
+ FileManager: {
685
+ service: "files",
686
+ operations: {
687
+ homeDirectory: { arity: 0, result: true },
688
+ list: { arity: 1, result: true },
689
+ exists: { arity: 1, result: true },
690
+ readText: { arity: 1, result: true },
691
+ writeText: { arity: 2, result: false },
692
+ createDirectory: { arity: 1, result: false },
693
+ remove: { arity: 1, result: false },
694
+ parent: { arity: 1, result: true },
695
+ join: { arity: 2, result: true },
696
+ },
697
+ },
698
+ Workspace: { service: "workspace", operations: { open: { arity: 1, result: false }, reveal: { arity: 1, result: false } } },
699
+ };
700
+ function hostAction(owner, operation, argumentSource, state, bindings) {
701
+ const contract = hostOperations[owner]?.operations[operation];
702
+ if (!contract) {
703
+ const known = Object.keys(hostOperations[owner]?.operations ?? {}).join(", ");
704
+ throw new SyntaxError(`Unknown host operation ${owner}.${operation}; available: ${known}`);
705
+ }
706
+ const args = collectionArguments(argumentSource);
707
+ if (args.some(argument => argument.label !== undefined)) {
708
+ throw new SyntaxError(`${owner}.${operation} takes positional arguments only: ${owner}.${operation}(${argumentSource})`);
709
+ }
710
+ if (args.length !== contract.arity) {
711
+ throw new SyntaxError(`${owner}.${operation} takes ${contract.arity} argument(s), got ${args.length}: ${owner}.${operation}(${argumentSource})`);
712
+ }
713
+ if (state && !contract.result)
714
+ throw new SyntaxError(`${owner}.${operation} returns no value to assign`);
715
+ return {
716
+ kind: "host",
717
+ service: hostOperations[owner].service,
718
+ operation,
719
+ arguments: args.map(argument => lowerValueExpression(argument.source, bindings)),
720
+ ...(state ? { state } : {}),
721
+ };
722
+ }
723
+ function actionFromClosure(source, bindings = emptyBindings) {
724
+ const body = source.trim().replace(/;$/, "").trim();
725
+ const statements = splitStatements(body);
726
+ if (statements.length > 1) {
727
+ return { kind: "sequence", actions: statements.map(statement => actionFromClosure(statement, bindings)) };
728
+ }
729
+ const actionProgram = parseMunBuilder(body);
730
+ if (actionProgram.statements.length === 1) {
731
+ const statement = actionProgram.statements[0];
732
+ if (statement.kind === "call" && statement.callee === "withAnimation" && statement.trailing) {
733
+ const animationSource = statement.arguments[0]?.value.kind === "raw"
734
+ ? statement.arguments[0].value.source.trim()
735
+ : undefined;
736
+ const animation = animationSource === "null"
737
+ ? null
738
+ : animationPlan(animationSource ?? "Animation.default");
739
+ const nested = actionFromClosure(statement.trailing.bodySource, bindings);
740
+ if (nested.transaction)
741
+ return nested;
742
+ return {
743
+ ...nested,
744
+ transaction: {
745
+ animation,
746
+ disablesAnimations: false,
747
+ isContinuous: false,
748
+ },
749
+ };
750
+ }
751
+ if (statement.kind === "call" && statement.callee === "withTransaction" && statement.trailing) {
752
+ const transactionSource = statement.arguments[0]?.value.kind === "raw"
753
+ ? statement.arguments[0].value.source.trim()
754
+ : undefined;
755
+ if (!transactionSource) {
756
+ throw new SyntaxError("withTransaction requires a statically representable Transaction");
757
+ }
758
+ const nested = actionFromClosure(statement.trailing.bodySource, bindings);
759
+ if (nested.transaction)
760
+ return nested;
761
+ return { ...nested, transaction: transactionPlan(transactionSource) };
762
+ }
763
+ }
764
+ const toggleAssignment = body.match(/^([A-Za-z_$][\w$]*)\.value\s*=\s*!\s*\1\.value$/);
765
+ if (toggleAssignment)
766
+ return { kind: "toggle-state", state: stateTarget(toggleAssignment[1], bindings) };
767
+ const toggleCall = body.match(/^([A-Za-z_$][\w$]*)\.toggle\s*\(\s*\)$/);
768
+ if (toggleCall)
769
+ return { kind: "toggle-state", state: stateTarget(toggleCall[1], bindings) };
770
+ const compoundAssignment = body.match(/^([A-Za-z_$][\w$]*)\.value\s*(\+=|-=|\*=|\/=|%=)\s*(.+)$/s);
771
+ if (compoundAssignment) {
772
+ const operator = compoundAssignment[2][0];
773
+ return {
774
+ kind: "set-state",
775
+ state: stateTarget(compoundAssignment[1], bindings),
776
+ value: lowerValueExpression(`${compoundAssignment[1]}.value ${operator} (${compoundAssignment[3]})`, bindings),
777
+ };
778
+ }
779
+ const assignment = body.match(/^([A-Za-z_$][\w$]*)\.value\s*=\s*(.+)$/s);
780
+ if (assignment) {
781
+ return {
782
+ kind: "set-state",
783
+ state: stateTarget(assignment[1], bindings),
784
+ value: lowerValueExpression(assignment[2], bindings),
785
+ };
786
+ }
787
+ const hostCall = /^(?:([A-Za-z_$][\w$]*)(?:\.value)?\s*=\s*)?(FileManager|Workspace)\.([A-Za-z]+)\s*\(([\s\S]*)\)$/.exec(body);
788
+ if (hostCall) {
789
+ const [, target, owner, operation, argumentSource] = hostCall;
790
+ if (target && bindings.get(target)?.kind !== "state" && !/\.value\s*=/.test(body)) {
791
+ throw new SyntaxError(`${owner}.${operation} results can only be assigned to @State: ${body}`);
792
+ }
793
+ return hostAction(owner, operation, argumentSource, target ? stateTarget(target, bindings) : undefined, bindings);
794
+ }
795
+ const collectionCall = /^([A-Za-z_$][\w$]*)\.(insert|append|remove|move|update)\s*\(([\s\S]*)\)$/.exec(body);
796
+ if (collectionCall) {
797
+ return collectionAction(stateTarget(collectionCall[1], bindings), collectionCall[2], collectionCall[3], bindings);
798
+ }
799
+ const plainAssignment = /^([A-Za-z_$][\w$]*)\s*(\+=|-=|\*=|\/=|%=|=)(?!=)\s*([\s\S]+)$/.exec(body);
800
+ if (plainAssignment && bindings.get(plainAssignment[1])?.kind === "state") {
801
+ const [, name, operator, valueSource] = plainAssignment;
802
+ return {
803
+ kind: "set-state",
804
+ state: stateTarget(name, bindings),
805
+ value: lowerValueExpression(operator === "=" ? valueSource : `${name} ${operator[0]} (${valueSource})`, bindings),
806
+ };
807
+ }
808
+ throw new SyntaxError(`Action body is not yet representable in native Mün IR: ${source.trim()}`);
809
+ }
810
+ function lowerAnimation(animation, source) {
811
+ const descriptor = animation.descriptor;
812
+ const repeatCount = descriptor.repeatCount === Number.POSITIVE_INFINITY
813
+ ? "infinite"
814
+ : Math.max(1, Math.floor(Number.isFinite(descriptor.repeatCount) ? descriptor.repeatCount ?? 1 : 1));
815
+ const speed = descriptor.speed > 0 && Number.isFinite(descriptor.speed) ? descriptor.speed : 1;
816
+ const delayMs = Math.max(0, descriptor.delay) / speed * 1000;
817
+ if (descriptor.kind === "spring") {
818
+ const response = Math.max(0.05, descriptor.response ?? descriptor.duration) / speed;
819
+ const dampingRatio = Math.max(0, descriptor.dampingFraction ?? 0.825);
820
+ const blendDuration = Math.max(0, descriptor.blendDuration ?? 0) / speed;
821
+ const inherited = compileInheritedMotionPlan(inheritedSpring({ response, dampingRatio, blendDuration }));
822
+ if (inherited.route !== "spring") {
823
+ throw new SyntaxError(`Inherited motion planner did not produce a spring plan for ${source}`);
824
+ }
825
+ return {
826
+ kind: "spring",
827
+ omega: inherited.omega,
828
+ dampingRatio: inherited.dampingRatio,
829
+ blendDuration: inherited.spec.blendDuration ?? blendDuration,
830
+ delayMs,
831
+ repeatCount,
832
+ autoreverses: descriptor.autoreverses ?? true,
833
+ };
834
+ }
835
+ const curve = descriptor.kind === "linear" ? inheritedCurves.linear
836
+ : descriptor.kind === "easeIn" ? inheritedCurves.easeIn
837
+ : descriptor.kind === "easeOut" ? inheritedCurves.easeOut
838
+ : inheritedCurves.easeInOut;
839
+ const duration = Math.max(0, descriptor.duration) / speed;
840
+ const inherited = compileInheritedMotionPlan(inheritedTiming({ duration, curve }));
841
+ if (inherited.route !== "timing") {
842
+ throw new SyntaxError(`Inherited motion planner did not produce a timing plan for ${source}`);
843
+ }
844
+ return {
845
+ kind: "timing",
846
+ duration: inherited.spec.duration,
847
+ curve: [inherited.spec.curve.x1, inherited.spec.curve.y1, inherited.spec.curve.x2, inherited.spec.curve.y2],
848
+ delayMs,
849
+ repeatCount,
850
+ autoreverses: descriptor.autoreverses ?? true,
851
+ };
852
+ }
853
+ function animationPlan(source) {
854
+ return lowerAnimation(lowerAnimationValue(source), source);
855
+ }
856
+ function lowerTransition(source) {
857
+ const transition = lowerTransitionValue(source);
858
+ return {
859
+ insertion: transition.insertion.map(effect => ({ ...effect })),
860
+ removal: transition.removal.map(effect => ({ ...effect })),
861
+ ...(transition.animation ? { animation: lowerAnimation(transition.animation, `${source}.animation`) } : {}),
862
+ };
863
+ }
864
+ /** `Transaction(animation: .linear(duration: 1))`. */
865
+ function transactionPlan(source) {
866
+ const trimmed = source.trim();
867
+ if (/^new\s/.test(trimmed))
868
+ throw new SyntaxError(`'new' is TypeScript syntax. Use Transaction(animation: …): ${source}`);
869
+ const statement = parseMunBuilder(trimmed).statements[0];
870
+ const argument = statement?.kind === "call" && statement.callee === "Transaction" && !statement.trailing && statement.arguments.length === 1
871
+ ? statement.arguments[0]
872
+ : undefined;
873
+ if (!argument || argument.label !== "animation" || argument.value.kind !== "raw") {
874
+ throw new SyntaxError(`withTransaction requires Transaction(animation: …): ${source}`);
875
+ }
876
+ const animationSource = argument.value.source.trim();
877
+ const animation = animationSource === "nil" ? null : lowerAnimationValue(animationSource);
878
+ return { animation: animation ? lowerAnimation(animation, source) : null, disablesAnimations: false, isContinuous: false };
879
+ }
880
+ function skipQuoted(source, index) {
881
+ const quote = source[index];
882
+ for (let cursor = index + 1; cursor < source.length; cursor += 1) {
883
+ if (source[cursor] === "\\") {
884
+ cursor += 1;
885
+ continue;
886
+ }
887
+ if (source[cursor] === quote)
888
+ return cursor + 1;
889
+ }
890
+ throw new SyntaxError("Unclosed string while reading Mün view modifiers");
891
+ }
892
+ function findMatchingParenthesis(source, openIndex, open = "(", close = ")") {
893
+ let depth = 1;
894
+ for (let cursor = openIndex + 1; cursor < source.length; cursor += 1) {
895
+ const character = source[cursor];
896
+ if (character === "\"" || character === "'" || character === "`") {
897
+ cursor = skipQuoted(source, cursor) - 1;
898
+ continue;
899
+ }
900
+ if (character === open)
901
+ depth += 1;
902
+ else if (character === close) {
903
+ depth -= 1;
904
+ if (depth === 0)
905
+ return cursor;
906
+ }
907
+ }
908
+ throw new SyntaxError(open === "(" ? "Unclosed modifier argument list in Mün source" : "Unclosed modifier closure in Mün source");
909
+ }
910
+ function firstTopLevelModifier(source) {
911
+ const stack = [];
912
+ const closes = { "(": ")", "{": "}", "[": "]" };
913
+ for (let cursor = 0; cursor < source.length; cursor += 1) {
914
+ const character = source[cursor];
915
+ if (character === "\"" || character === "'" || character === "`") {
916
+ cursor = skipQuoted(source, cursor) - 1;
917
+ continue;
918
+ }
919
+ if (character === "(" || character === "{" || character === "[") {
920
+ stack.push(character);
921
+ continue;
922
+ }
923
+ if (character === ")" || character === "}" || character === "]") {
924
+ const open = stack.at(-1);
925
+ if (open && closes[open] === character)
926
+ stack.pop();
927
+ continue;
928
+ }
929
+ if (character === "." && stack.length === 0 && /[A-Za-z_$]/.test(source[cursor + 1] ?? ""))
930
+ return cursor;
931
+ }
932
+ return -1;
933
+ }
934
+ function modifierArguments(source, trailing) {
935
+ if (!source.trim() && trailing === undefined)
936
+ return { arguments: [] };
937
+ const program = parseMunBuilder(`M(${source})${trailing === undefined ? "" : ` ${trailing}`}`);
938
+ const statement = program.statements[0];
939
+ if (!statement || statement.kind !== "call")
940
+ throw new SyntaxError(`Invalid Mün modifier arguments: ${source}`);
941
+ return { arguments: statement.arguments, ...(statement.trailing ? { trailing: statement.trailing } : {}) };
942
+ }
943
+ function splitViewChain(source) {
944
+ const trimmed = source.trim();
945
+ const firstDot = firstTopLevelModifier(trimmed);
946
+ if (firstDot < 0) {
947
+ const program = parseMunBuilder(trimmed);
948
+ if (program.statements.length !== 1)
949
+ throw new SyntaxError(`Expected one Mün view expression: ${trimmed}`);
950
+ return { base: program.statements[0], modifiers: [] };
951
+ }
952
+ const baseSource = trimmed.slice(0, firstDot).trim();
953
+ const program = parseMunBuilder(baseSource);
954
+ if (program.statements.length !== 1)
955
+ throw new SyntaxError(`Expected one Mün base view expression: ${baseSource}`);
956
+ const modifiers = [];
957
+ let cursor = firstDot;
958
+ while (cursor < trimmed.length) {
959
+ while (/\s/.test(trimmed[cursor] ?? ""))
960
+ cursor += 1;
961
+ if (trimmed[cursor] !== ".")
962
+ throw new SyntaxError(`Expected Mün view modifier near: ${trimmed.slice(cursor)}`);
963
+ cursor += 1;
964
+ while (/\s/.test(trimmed[cursor] ?? ""))
965
+ cursor += 1;
966
+ const nameStart = cursor;
967
+ while (/[A-Za-z0-9_$]/.test(trimmed[cursor] ?? ""))
968
+ cursor += 1;
969
+ const name = trimmed.slice(nameStart, cursor);
970
+ while (/\s/.test(trimmed[cursor] ?? ""))
971
+ cursor += 1;
972
+ // `.name(args)`, `.name(args) { … }` or `.name { … }` (trailing closure).
973
+ let argumentSource = "";
974
+ const hasArgumentList = trimmed[cursor] === "(";
975
+ if (hasArgumentList) {
976
+ const close = findMatchingParenthesis(trimmed, cursor);
977
+ argumentSource = trimmed.slice(cursor + 1, close);
978
+ cursor = close + 1;
979
+ }
980
+ let lookahead = cursor;
981
+ while (/\s/.test(trimmed[lookahead] ?? ""))
982
+ lookahead += 1;
983
+ let trailing;
984
+ if (trimmed[lookahead] === "{") {
985
+ const close = findMatchingParenthesis(trimmed, lookahead, "{", "}");
986
+ trailing = trimmed.slice(lookahead, close + 1);
987
+ cursor = close + 1;
988
+ }
989
+ else if (!hasArgumentList) {
990
+ throw new SyntaxError(`Modifier .${name} requires an argument list`);
991
+ }
992
+ modifiers.push({ name, ...modifierArguments(argumentSource, trailing) });
993
+ }
994
+ return { base: program.statements[0], modifiers };
995
+ }
996
+ function expressionIsDynamic(value) {
997
+ return !!value && value.kind !== "literal";
998
+ }
999
+ function collectStructDeclarations(declarations, prefix = "", byQualifiedName = new Map(), qualifiedNameByDeclaration = new Map()) {
1000
+ for (const declaration of declarations) {
1001
+ const qualifiedName = prefix ? `${prefix}.${declaration.name}` : declaration.name;
1002
+ byQualifiedName.set(qualifiedName, declaration);
1003
+ qualifiedNameByDeclaration.set(declaration, qualifiedName);
1004
+ collectStructDeclarations(declaration.nested ?? [], qualifiedName, byQualifiedName, qualifiedNameByDeclaration);
1005
+ }
1006
+ return { byQualifiedName, qualifiedNameByDeclaration };
1007
+ }
1008
+ function identityPathKey(path) {
1009
+ return path.map(segment => typeof segment === "number" ? `#${segment}` : segment).join("/");
1010
+ }
1011
+ function childIdentityPath(path, ...segments) {
1012
+ return path ? [...path, ...segments] : null;
1013
+ }
1014
+ function encodedIdentityKeySegment(key) {
1015
+ return typeof key === "number"
1016
+ ? `n:${Object.is(key, -0) ? "0" : String(key)}`
1017
+ : `s:${encodeURIComponent(key)}`;
1018
+ }
1019
+ function keyedIdentityPath(path, key) {
1020
+ const parent = path.at(-2) === "child" ? path.slice(0, -2) : path;
1021
+ return [...parent, "key", encodedIdentityKeySegment(key)];
1022
+ }
1023
+ function keyedStateIdentityPath(path, key) {
1024
+ return path ? keyedIdentityPath(path, key) : null;
1025
+ }
1026
+ function nodeIdentityPathForModifiers(path, modifiers, bindings) {
1027
+ let current = path;
1028
+ for (const modifier of modifiers) {
1029
+ if (modifier.name !== "id")
1030
+ continue;
1031
+ const identityKey = semanticIdentityKey(idModifierSource(modifier), bindings);
1032
+ if (identityKey.kind !== "literal")
1033
+ continue;
1034
+ if (typeof identityKey.value !== "string" && typeof identityKey.value !== "number")
1035
+ continue;
1036
+ current = keyedIdentityPath(current, identityKey.value);
1037
+ }
1038
+ return current;
1039
+ }
1040
+ function stateIdentityPathForModifiers(path, modifiers, bindings) {
1041
+ let current = path;
1042
+ for (const modifier of modifiers) {
1043
+ if (modifier.name !== "id")
1044
+ continue;
1045
+ const identityKey = semanticIdentityKey(idModifierSource(modifier), bindings);
1046
+ if (identityKey.kind !== "literal")
1047
+ return null;
1048
+ if (typeof identityKey.value !== "string" && typeof identityKey.value !== "number")
1049
+ return null;
1050
+ current = keyedStateIdentityPath(current, identityKey.value);
1051
+ }
1052
+ return current;
1053
+ }
1054
+ function argumentSource(context, name) {
1055
+ const argument = context.args.get(name)?.sourceArgument;
1056
+ return argument?.value.kind === "raw" ? argument.value.source.trim() : undefined;
1057
+ }
1058
+ function argumentClosure(context, name) {
1059
+ const argument = context.args.get(name);
1060
+ if (argument?.trailingClosure)
1061
+ return argument.trailingClosure;
1062
+ return argument?.sourceArgument?.value.kind === "closure" ? argument.sourceArgument.value : undefined;
1063
+ }
1064
+ function staticTitle(source, bindings, what) {
1065
+ const value = source === undefined ? undefined : lowerValueExpression(source, bindings);
1066
+ if (value?.kind === "literal" && typeof value.value === "string")
1067
+ return value.value;
1068
+ throw new SyntaxError(`${what} must be a string literal in native Mün: ${source}`);
1069
+ }
1070
+ /** `Text("literal")` as a prompt or label. */
1071
+ function staticTextView(source, what) {
1072
+ const statement = parseMunBuilder(source.trim()).statements[0];
1073
+ const argument = statement?.kind === "call" && statement.callee === "Text" && !statement.trailing && statement.arguments.length === 1
1074
+ ? statement.arguments[0]
1075
+ : undefined;
1076
+ const text = argument && argument.label === undefined && argument.value.kind === "raw" ? argument.value.source.trim() : undefined;
1077
+ if (text && /^"(?:[^"\\]|\\.)*"$/.test(text))
1078
+ return JSON.parse(text);
1079
+ throw new SyntaxError(`${what} must be Text with a string literal in native Mün: ${source.trim()}`);
1080
+ }
1081
+ function closureLabel(closure, what) {
1082
+ if (!closure || closure.body.statements.length !== 1)
1083
+ throw new SyntaxError(`${what} must contain exactly one Text`);
1084
+ const statement = closure.body.statements[0];
1085
+ return staticTextView(statement.kind === "raw" || statement.kind === "call" ? closure.bodySource : "", what);
1086
+ }
1087
+ function horizontalAlignment(source) {
1088
+ if (source === undefined)
1089
+ return undefined;
1090
+ const value = source.trim().replace(/^(?:HorizontalAlignment)?\./, "");
1091
+ if (horizontalAlignments.includes(value))
1092
+ return value;
1093
+ throw new SyntaxError(`VStack alignment must be .leading, .center or .trailing: ${source}`);
1094
+ }
1095
+ function verticalAlignment(source) {
1096
+ if (source === undefined)
1097
+ return undefined;
1098
+ const value = source.trim().replace(/^(?:VerticalAlignment)?\./, "");
1099
+ if (value === "top")
1100
+ return "leading";
1101
+ if (value === "bottom")
1102
+ return "trailing";
1103
+ if (value === "center")
1104
+ return "center";
1105
+ if (value === "firstTextBaseline" || value === "lastTextBaseline") {
1106
+ throw new SyntaxError(`HStack text-baseline alignment is not implemented by native Mün: ${source}`);
1107
+ }
1108
+ throw new SyntaxError(`HStack alignment must be .top, .center or .bottom: ${source}`);
1109
+ }
1110
+ const alignments = overlayAlignments;
1111
+ function alignment(source, what) {
1112
+ if (source === undefined)
1113
+ return undefined;
1114
+ const value = source.trim().replace(/^(?:Alignment)?\./, "");
1115
+ if (alignments.includes(value))
1116
+ return value;
1117
+ throw new SyntaxError(`${what} must be an Alignment such as .center or .topLeading: ${source}`);
1118
+ }
1119
+ /** System-default metrics (global divergence `defaultMetrics`). */
1120
+ const defaultStackSpacing = 8;
1121
+ const defaultPadding = 16;
1122
+ const flexibleBoth = { maxWidth: "infinity", maxHeight: "infinity" };
1123
+ function shapeNode(context, shape, cornerRadius) {
1124
+ return {
1125
+ kind: "panel",
1126
+ id: context.lowerer.id("panel", context.path),
1127
+ shape,
1128
+ // Shapes fill the space they are offered, like SwiftUI shapes.
1129
+ layout: flexibleBoth,
1130
+ ...(cornerRadius !== undefined ? { visual: { cornerRadius } } : {}),
1131
+ };
1132
+ }
1133
+ function cornerStyle(source) {
1134
+ if (source === undefined)
1135
+ return;
1136
+ const value = source.trim().replace(/^(?:RoundedCornerStyle)?\./, "");
1137
+ if (value !== "continuous" && value !== "circular")
1138
+ throw new SyntaxError(`Corner style must be .continuous or .circular: ${source}`);
1139
+ }
1140
+ /** Picker content: `Text("Label").tag(value)` rows, optionally `.disabled(true)`. */
1141
+ function pickerOptions(closure) {
1142
+ if (!closure)
1143
+ throw new SyntaxError("Picker requires content");
1144
+ const seen = new Set();
1145
+ return closure.body.statements.map((statement, index) => {
1146
+ if (statement.kind === "conditional")
1147
+ throw new SyntaxError(`Picker content #${index + 1} must be Text(…).tag(…); conditionals are not supported`);
1148
+ const source = statement.kind === "raw"
1149
+ ? statement.source.trim()
1150
+ : closure.bodySource.slice(statement.range.start - closure.body.range.start, statement.range.end - closure.body.range.start).trim();
1151
+ const dot = firstTopLevelModifier(source);
1152
+ const label = staticTextView(dot < 0 ? source : source.slice(0, dot), `Picker content #${index + 1}`);
1153
+ const modifiers = dot < 0 ? [] : splitViewChain(source).modifiers;
1154
+ let value;
1155
+ let disabled = false;
1156
+ for (const modifier of modifiers) {
1157
+ const argument = modifier.arguments[0];
1158
+ const raw = argument?.value.kind === "raw" ? argument.value.source.trim() : undefined;
1159
+ if (modifier.name === "tag" && modifier.arguments.length === 1 && argument.label === undefined && raw !== undefined) {
1160
+ const lowered = lowerValueExpression(raw);
1161
+ if (lowered.kind !== "literal" || (typeof lowered.value !== "string" && (typeof lowered.value !== "number" || !Number.isFinite(lowered.value)))) {
1162
+ throw new SyntaxError(`Picker tag must be a static string or number: ${raw}`);
1163
+ }
1164
+ value = lowered.value;
1165
+ }
1166
+ else if (modifier.name === "disabled" && modifier.arguments.length === 1 && raw !== undefined) {
1167
+ if (raw !== "true" && raw !== "false")
1168
+ throw new SyntaxError(`Picker option .disabled(_:) must be a static Bool: ${raw}`);
1169
+ disabled = raw === "true";
1170
+ }
1171
+ else {
1172
+ throw new SyntaxError(`Picker content supports only .tag(_:) and .disabled(_:), found .${modifier.name}`);
1173
+ }
1174
+ }
1175
+ if (value === undefined)
1176
+ throw new SyntaxError(`Picker content #${index + 1} requires .tag(_:)`);
1177
+ const key = `${typeof value}:${String(value)}`;
1178
+ if (seen.has(key))
1179
+ throw new SyntaxError("Picker tags must be unique");
1180
+ seen.add(key);
1181
+ return { label, value, ...(disabled ? { disabled } : {}) };
1182
+ });
1183
+ }
1184
+ function stackChildren(context) {
1185
+ const closure = argumentClosure(context, "content");
1186
+ return closure ? context.lowerer.lowerProgram(closure.body, context.bindings, [...context.path, "content"], childIdentityPath(context.statePath, "content")) : [];
1187
+ }
1188
+ /**
1189
+ * Native implementations of manifest View overloads, keyed `View.signature`.
1190
+ * Their keys are the compiler's implementation metadata (nativeLoweringMetadata).
1191
+ */
1192
+ const nativeViews = {
1193
+ "Text.init(_:)": context => [textNode(context, argumentSource(context, "content"))],
1194
+ "Text.init(verbatim:)": context => [textNode(context, argumentSource(context, "verbatim"))],
1195
+ "Button.init(_:action:)": context => [actionNode(context, staticTitle(argumentSource(context, "title"), context.bindings, "Button title"), argumentClosure(context, "action"))],
1196
+ "Button.init(action:label:)": context => [actionNode(context, closureLabel(argumentClosure(context, "label"), "Button label"), argumentClosure(context, "action"))],
1197
+ "TextField.init(_:text:)": context => [textFieldNode(context, staticTitle(argumentSource(context, "title"), context.bindings, "TextField title"))],
1198
+ "TextField.init(_:text:prompt:)": context => [textFieldNode(context, staticTitle(argumentSource(context, "title"), context.bindings, "TextField title"), staticTextView(argumentSource(context, "prompt") ?? "", "TextField prompt"))],
1199
+ "SecureField.init(_:text:)": context => [textFieldNode(context, staticTitle(argumentSource(context, "title"), context.bindings, "SecureField title"), undefined, true)],
1200
+ "SecureField.init(_:text:prompt:)": context => [textFieldNode(context, staticTitle(argumentSource(context, "title"), context.bindings, "SecureField title"), staticTextView(argumentSource(context, "prompt") ?? "", "SecureField prompt"), true)],
1201
+ "Toggle.init(_:isOn:)": context => [toggleNode(context, staticTitle(argumentSource(context, "title"), context.bindings, "Toggle title"))],
1202
+ "Toggle.init(isOn:label:)": context => [toggleNode(context, closureLabel(argumentClosure(context, "label"), "Toggle label"))],
1203
+ "ProgressView.init(value:total:)": context => [progressNode(context)],
1204
+ "ProgressView.init(_:value:total:)": context => [progressNode(context, staticTitle(argumentSource(context, "title"), context.bindings, "ProgressView title"))],
1205
+ "Spacer.init(minLength:)": context => {
1206
+ const minLength = numberValue(argumentSource(context, "minLength"), undefined, context.bindings);
1207
+ if (minLength !== undefined && minLength < 0)
1208
+ throw new SyntaxError(`Spacer minLength must not be negative: ${minLength}`);
1209
+ return [{ kind: "spacer", id: context.lowerer.id("spacer", context.path), ...(minLength !== undefined ? { minLength } : {}) }];
1210
+ },
1211
+ "Divider.init()": context => [{ kind: "divider", id: context.lowerer.id("divider", context.path) }],
1212
+ "Picker.init(_:selection:content:)": context => {
1213
+ const title = staticTitle(argumentSource(context, "title"), context.bindings, "Picker title");
1214
+ return [{
1215
+ kind: "radioGroup",
1216
+ id: context.lowerer.id("radioGroup", context.path),
1217
+ state: bindingState(argumentSource(context, "selection"), context.bindings, "Picker"),
1218
+ options: pickerOptions(argumentClosure(context, "content")),
1219
+ accessibility: { role: "radioGroup", label: title },
1220
+ }];
1221
+ },
1222
+ "VStack.init(alignment:spacing:content:)": context => {
1223
+ const spacing = numberValue(argumentSource(context, "spacing"), defaultStackSpacing, context.bindings);
1224
+ const align = horizontalAlignment(argumentSource(context, "alignment"));
1225
+ return [{ kind: "column", id: context.lowerer.id("column", context.path), layout: { spacing, ...(align ? { alignment: align } : {}) }, accessibility: { role: "group" }, children: stackChildren(context) }];
1226
+ },
1227
+ "HStack.init(alignment:spacing:content:)": context => {
1228
+ const spacing = numberValue(argumentSource(context, "spacing"), defaultStackSpacing, context.bindings);
1229
+ const align = verticalAlignment(argumentSource(context, "alignment"));
1230
+ return [{ kind: "row", id: context.lowerer.id("row", context.path), layout: { spacing, ...(align ? { alignment: align } : {}) }, accessibility: { role: "group" }, children: stackChildren(context) }];
1231
+ },
1232
+ "ZStack.init(alignment:content:)": context => {
1233
+ const align = alignment(argumentSource(context, "alignment"), "ZStack alignment");
1234
+ return [{ kind: "overlay", id: context.lowerer.id("overlay", context.path), ...(align ? { alignment: align } : {}), accessibility: { role: "group" }, children: stackChildren(context) }];
1235
+ },
1236
+ "ScrollView.init(_:content:)": context => {
1237
+ const raw = argumentSource(context, "axes")?.replace(/^(?:Axis\.Set)?\./, "");
1238
+ if (raw !== undefined && raw !== "vertical" && raw !== "horizontal") {
1239
+ throw new SyntaxError(`ScrollView axes must be .vertical or .horizontal in native Mün: ${argumentSource(context, "axes")}`);
1240
+ }
1241
+ return [{
1242
+ kind: "scroll",
1243
+ id: context.lowerer.id("scroll", context.path),
1244
+ axis: raw === "horizontal" ? "horizontal" : "vertical",
1245
+ // A ScrollView takes the space it is offered, like SwiftUI's.
1246
+ layout: flexibleBoth,
1247
+ accessibility: { role: "group" },
1248
+ children: stackChildren(context),
1249
+ }];
1250
+ },
1251
+ "ForEach.init(_:id:content:)": context => [context.lowerer.lowerForEach(context, keyPathFromSource(argumentSource(context, "id")))],
1252
+ "ForEach.init(_:content:)": context => [context.lowerer.lowerForEach(context, ["id"])],
1253
+ "Group.init(content:)": context => stackChildren(context),
1254
+ "Rectangle.init()": context => [shapeNode(context, "rectangle")],
1255
+ "RoundedRectangle.init(cornerRadius:style:)": context => {
1256
+ cornerStyle(argumentSource(context, "style"));
1257
+ const radius = numberValue(argumentSource(context, "cornerRadius"), undefined, context.bindings);
1258
+ return [shapeNode(context, "roundedRectangle", radius)];
1259
+ },
1260
+ "Circle.init()": context => [shapeNode(context, "circle")],
1261
+ "Capsule.init(style:)": context => {
1262
+ cornerStyle(argumentSource(context, "style"));
1263
+ return [shapeNode(context, "capsule")];
1264
+ },
1265
+ };
1266
+ function textNode(context, source) {
1267
+ if (!source)
1268
+ throw new SyntaxError("Text requires content");
1269
+ const value = lowerValueExpression(source, context.bindings);
1270
+ return {
1271
+ kind: "text",
1272
+ id: context.lowerer.id("text", context.path),
1273
+ value,
1274
+ accessibility: {
1275
+ role: "text",
1276
+ ...(value.kind === "literal" && typeof value.value === "string" ? { label: value.value } : {}),
1277
+ },
1278
+ };
1279
+ }
1280
+ function actionNode(context, label, closure) {
1281
+ if (!closure)
1282
+ throw new SyntaxError("Button requires an action closure");
1283
+ return {
1284
+ kind: "action",
1285
+ id: context.lowerer.id("action", context.path),
1286
+ label,
1287
+ action: actionFromClosure(closure.bodySource, context.bindings),
1288
+ accessibility: { role: "button", label },
1289
+ };
1290
+ }
1291
+ function textFieldNode(context, title, prompt, secure = false) {
1292
+ const placeholder = prompt ?? title;
1293
+ return {
1294
+ kind: "textField",
1295
+ id: context.lowerer.id("textField", context.path),
1296
+ state: bindingState(argumentSource(context, "text"), context.bindings, secure ? "SecureField" : "TextField"),
1297
+ ...(placeholder ? { placeholder } : {}),
1298
+ ...(secure ? { secure } : {}),
1299
+ // A TextField takes the width it is offered, like SwiftUI's.
1300
+ layout: { maxWidth: "infinity" },
1301
+ accessibility: { role: "textField", ...(title ? { label: title } : {}) },
1302
+ };
1303
+ }
1304
+ function toggleNode(context, label) {
1305
+ return {
1306
+ kind: "toggle",
1307
+ id: context.lowerer.id("toggle", context.path),
1308
+ state: bindingState(argumentSource(context, "isOn"), context.bindings, "Toggle"),
1309
+ label,
1310
+ accessibility: { role: "checkBox", label },
1311
+ };
1312
+ }
1313
+ function progressNode(context, label) {
1314
+ const total = argumentSource(context, "total");
1315
+ return {
1316
+ kind: "progress",
1317
+ id: context.lowerer.id("progress", context.path),
1318
+ value: lowerValueExpression(argumentSource(context, "value"), context.bindings),
1319
+ ...(total !== undefined ? { total: lowerValueExpression(total, context.bindings) } : {}),
1320
+ ...(label ? { label } : {}),
1321
+ accessibility: { role: "progressIndicator", ...(label ? { label } : {}) },
1322
+ };
1323
+ }
1324
+ /** `Window(_:width:height:content:)` — the Mün desktop window extension. */
1325
+ const windowSymbols = [{
1326
+ kind: "initializer",
1327
+ index: 0,
1328
+ signature: "init(_:width:height:content:)",
1329
+ parameters: [
1330
+ { kind: "value", name: "title", labelRequired: false, required: true, type: "string" },
1331
+ { kind: "value", name: "width", label: "width", labelRequired: true, required: false, type: "number" },
1332
+ { kind: "value", name: "height", label: "height", labelRequired: true, required: false, type: "number" },
1333
+ { kind: "viewBuilder", name: "content", label: "content", labelRequired: true, required: true, trailing: true },
1334
+ ],
1335
+ }];
1336
+ /**
1337
+ * Inside-out stages of Mün's native box model. A modifier applied after a
1338
+ * later-stage one wraps the View, so SwiftUI's modifier order is observable:
1339
+ * `.padding().background(c)` paints the padding, `.background(c).padding()`
1340
+ * does not.
1341
+ */
1342
+ const modifierStages = { padding: 1, frame: 2, background: 3, cornerRadius: 4, opacity: 5, offset: 5 };
1343
+ const controlKinds = new Set(["action", "textField", "radioGroup", "toggle"]);
1344
+ const foregroundKinds = new Set(["text", "panel", "action", "textField", "toggle", "progress"]);
1345
+ function flexibleOn(node, horizontal) {
1346
+ const layout = node.layout;
1347
+ return horizontal
1348
+ ? layout?.width === undefined && layout?.maxWidth !== undefined
1349
+ : layout?.height === undefined && layout?.maxHeight !== undefined;
1350
+ }
1351
+ function childrenOf(node) {
1352
+ switch (node.kind) {
1353
+ case "column":
1354
+ case "row":
1355
+ case "overlay":
1356
+ case "scroll":
1357
+ case "forEach": return node.children;
1358
+ case "conditional": return [...node.then, ...node.otherwise];
1359
+ case "window": return [node.child];
1360
+ default: return [];
1361
+ }
1362
+ }
1363
+ function withChildren(node, map) {
1364
+ switch (node.kind) {
1365
+ case "column":
1366
+ case "row":
1367
+ case "overlay":
1368
+ case "scroll":
1369
+ case "forEach":
1370
+ return { ...node, children: node.children.map(map) };
1371
+ case "conditional":
1372
+ return { ...node, then: node.then.map(map), otherwise: node.otherwise.map(map) };
1373
+ case "window":
1374
+ return { ...node, child: map(node.child) };
1375
+ default:
1376
+ return node;
1377
+ }
1378
+ }
1379
+ /** Lexical environment values written by modifiers and inherited by descendants. */
1380
+ /** Typography set by an outer modifier reaches every Text below that has not set the same field itself. */
1381
+ function inheritTypography(node, font) {
1382
+ let current = node;
1383
+ if (current.kind === "text") {
1384
+ const merged = { ...font };
1385
+ for (const [key, value] of Object.entries(current.font ?? {}))
1386
+ if (value !== undefined)
1387
+ merged[key] = value;
1388
+ current = { ...current, font: merged };
1389
+ }
1390
+ return withChildren(current, child => inheritTypography(child, font));
1391
+ }
1392
+ function inheritEnvironment(node, environment) {
1393
+ let current = node;
1394
+ if (environment.disabled && controlKinds.has(current.kind)) {
1395
+ const enabled = { kind: "not", value: environment.disabled };
1396
+ const existing = current.accessibility?.enabled;
1397
+ current = {
1398
+ ...current,
1399
+ accessibility: {
1400
+ ...(current.accessibility ?? { role: "group" }),
1401
+ enabled: existing ? { kind: "binary", operator: "and", left: existing, right: enabled } : enabled,
1402
+ },
1403
+ };
1404
+ }
1405
+ if (environment.foreground && foregroundKinds.has(current.kind) && !current.visual?.foreground) {
1406
+ current = { ...current, visual: { ...current.visual, foreground: environment.foreground } };
1407
+ }
1408
+ return withChildren(current, child => inheritEnvironment(child, environment));
1409
+ }
1410
+ /** The innermost semantic node under compiler-made wrappers. */
1411
+ function semanticCore(node, wrappers, update) {
1412
+ if (wrappers.has(node) && node.kind === "overlay" && node.children.length === 1) {
1413
+ return { ...node, children: [semanticCore(node.children[0], wrappers, update)] };
1414
+ }
1415
+ return update(node);
1416
+ }
1417
+ class NodeComposer {
1418
+ animations;
1419
+ node;
1420
+ #stage = 0;
1421
+ #wrapperCount = 0;
1422
+ #wrappers = new Set();
1423
+ /** Modifier index at which each dynamic property was last written on the current level. */
1424
+ #setAt = new Map();
1425
+ constructor(node, animations) {
1426
+ this.animations = animations;
1427
+ this.node = node;
1428
+ }
1429
+ get stage() { return this.#stage; }
1430
+ isWrapper(node = this.node) { return this.#wrappers.has(node); }
1431
+ /** Begin a new layer around the current node. */
1432
+ wrap(alignment) {
1433
+ const inner = this.#finalize(this.node);
1434
+ const { identityKey, transition, ...rest } = inner;
1435
+ this.#wrapperCount += 1;
1436
+ const wrapper = {
1437
+ kind: "overlay",
1438
+ id: `${inner.id}~${this.#wrapperCount}`,
1439
+ ...(identityKey ? { identityKey } : {}),
1440
+ ...(transition ? { transition } : {}),
1441
+ ...(alignment && alignment !== "center" ? { alignment } : {}),
1442
+ children: [rest],
1443
+ };
1444
+ this.#wrappers.add(wrapper);
1445
+ this.node = wrapper;
1446
+ this.#stage = 0;
1447
+ this.#setAt = new Map();
1448
+ }
1449
+ enter(stage) {
1450
+ if (this.#stage > stage)
1451
+ this.wrap();
1452
+ this.#stage = Math.max(this.#stage, stage);
1453
+ }
1454
+ layout(update, index) {
1455
+ this.node = { ...this.node, layout: { ...this.node.layout, ...update } };
1456
+ if (update.width !== undefined)
1457
+ this.#setAt.set("width", index);
1458
+ if (update.height !== undefined)
1459
+ this.#setAt.set("height", index);
1460
+ }
1461
+ visual(update, index) {
1462
+ this.node = { ...this.node, visual: { ...this.node.visual, ...update } };
1463
+ if (update.opacity !== undefined)
1464
+ this.#setAt.set("opacity", index);
1465
+ if (update.translationX !== undefined)
1466
+ this.#setAt.set("translationX", index);
1467
+ if (update.translationY !== undefined)
1468
+ this.#setAt.set("translationY", index);
1469
+ }
1470
+ /** Apply to the innermost semantic node (labels, enabled state). */
1471
+ semantic(update) {
1472
+ this.node = semanticCore(this.node, this.#wrappers, update);
1473
+ }
1474
+ meta(update) {
1475
+ this.node = { ...this.node, ...update };
1476
+ }
1477
+ /** Rewrite the current node in place (environment inheritance). */
1478
+ transform(update) {
1479
+ const wrapper = this.#wrappers.has(this.node);
1480
+ this.node = update(this.node);
1481
+ if (wrapper)
1482
+ this.#wrappers.add(this.node);
1483
+ }
1484
+ /** Replace the current node with a new outer layer built from `finish()`. */
1485
+ layer(node) {
1486
+ this.node = node;
1487
+ this.#wrappers.add(node);
1488
+ this.#stage = 0;
1489
+ this.#setAt = new Map();
1490
+ }
1491
+ finish() {
1492
+ return this.#finalize(this.node);
1493
+ }
1494
+ #finalize(node) {
1495
+ const motion = [...(node.motion ?? [])];
1496
+ const candidates = [
1497
+ ["width", node.layout?.width],
1498
+ ["height", node.layout?.height],
1499
+ ["opacity", node.visual?.opacity],
1500
+ ["translationX", node.visual?.translationX],
1501
+ ["translationY", node.visual?.translationY],
1502
+ ];
1503
+ for (const [property, value] of candidates) {
1504
+ if (!expressionIsDynamic(value) || motion.some(binding => binding.property === property))
1505
+ continue;
1506
+ // The innermost `.animation(_:value:)` after the write animates it.
1507
+ const writtenAt = this.#setAt.get(property) ?? -1;
1508
+ const animation = this.animations.find(candidate => candidate.index > writtenAt);
1509
+ motion.push({
1510
+ property,
1511
+ propertyMask: munMotionPropertyBit(property),
1512
+ value,
1513
+ ...(animation?.trigger ? { trigger: animation.trigger } : {}),
1514
+ ...(animation ? { plan: animation.plan } : {}),
1515
+ });
1516
+ }
1517
+ return motion.length > 0 ? { ...node, motion } : node;
1518
+ }
1519
+ }
1520
+ function frameBound(source, label, bindings, allowInfinity) {
1521
+ if (source === undefined)
1522
+ return undefined;
1523
+ if (/^(?:\.infinity|CGFloat\.infinity|Double\.infinity)$/.test(source)) {
1524
+ if (!allowInfinity)
1525
+ throw new SyntaxError(`.frame(${label}:) must be finite`);
1526
+ return "infinity";
1527
+ }
1528
+ const value = numberValue(source, undefined, bindings);
1529
+ if (value === undefined || value < 0)
1530
+ throw new SyntaxError(`.frame(${label}:) must be a static non-negative number${allowInfinity ? " or .infinity" : ""}: ${source}`);
1531
+ return value;
1532
+ }
1533
+ function edgeInsets(edges, length) {
1534
+ if (edges === undefined)
1535
+ return length;
1536
+ const sets = paddingEdges;
1537
+ const names = edges.trim().startsWith("[")
1538
+ ? splitTopLevel(edges.trim().slice(1, -1)).map(item => item.trim())
1539
+ : [edges.trim()];
1540
+ const chosen = new Set();
1541
+ for (const name of names) {
1542
+ const edge = sets[name.replace(/^(?:Edge\.Set)?\./, "")];
1543
+ if (!edge)
1544
+ throw new SyntaxError(`padding edges must be Edge.Set members such as .horizontal or [.top, .leading]: ${edges}`);
1545
+ for (const item of edge)
1546
+ chosen.add(item);
1547
+ }
1548
+ if (chosen.size === 4)
1549
+ return length;
1550
+ return {
1551
+ top: chosen.has("top") ? length : 0,
1552
+ leading: chosen.has("leading") ? length : 0,
1553
+ bottom: chosen.has("bottom") ? length : 0,
1554
+ trailing: chosen.has("trailing") ? length : 0,
1555
+ };
1556
+ }
1557
+ function addPadding(existing, added) {
1558
+ if (existing === undefined)
1559
+ return added;
1560
+ const edges = (value) => typeof value === "number" || value === undefined
1561
+ ? { top: value ?? 0, leading: value ?? 0, bottom: value ?? 0, trailing: value ?? 0 }
1562
+ : value;
1563
+ const left = edges(existing);
1564
+ const right = edges(added);
1565
+ const sum = { top: left.top + right.top, leading: left.leading + right.leading, bottom: left.bottom + right.bottom, trailing: left.trailing + right.trailing };
1566
+ return sum.top === sum.leading && sum.top === sum.bottom && sum.top === sum.trailing ? sum.top : sum;
1567
+ }
1568
+ const isContainer = (node) => node.kind === "column" || node.kind === "row" || node.kind === "overlay" || node.kind === "scroll";
1569
+ function applyFrame(context, update, align) {
1570
+ const { composer } = context;
1571
+ const horizontal = update.width !== undefined || update.minWidth !== undefined || update.maxWidth !== undefined;
1572
+ const vertical = update.height !== undefined || update.minHeight !== undefined || update.maxHeight !== undefined;
1573
+ const node = composer.node;
1574
+ const occupied = (axis) => axis === "width"
1575
+ ? node.layout?.width !== undefined || node.layout?.minWidth !== undefined || (node.layout?.maxWidth !== undefined && !flexibleOn(node, true))
1576
+ : node.layout?.height !== undefined || node.layout?.minHeight !== undefined || (node.layout?.maxHeight !== undefined && !flexibleOn(node, false));
1577
+ // A frame merges into the View only where the result is identical: a
1578
+ // shape or color fills any frame; a View already flexible on an axis fills
1579
+ // it; a compiler wrapper is itself a frame. Everything else is wrapped so
1580
+ // the View is placed inside the frame by `alignment` (default .center).
1581
+ const fills = node.kind === "panel"
1582
+ || composer.isWrapper()
1583
+ || ((!horizontal || flexibleOn(node, true)) && (!vertical || flexibleOn(node, false)));
1584
+ const merge = fills
1585
+ && composer.stage <= 2
1586
+ && !(horizontal && occupied("width"))
1587
+ && !(vertical && occupied("height"))
1588
+ && (align === undefined || align === "center" || composer.isWrapper());
1589
+ if (!merge)
1590
+ composer.wrap(align);
1591
+ else if (align && align !== "center" && node.kind === "overlay" && composer.isWrapper()) {
1592
+ composer.transform(current => ({ ...current, alignment: align }));
1593
+ }
1594
+ composer.enter(2);
1595
+ composer.layout(update, context.index);
1596
+ }
1597
+ /**
1598
+ * Native implementations of manifest modifier overloads, keyed by signature.
1599
+ * Their keys are the compiler's implementation metadata (nativeLoweringMetadata).
1600
+ */
1601
+ const nativeModifiers = {
1602
+ "frame(width:height:alignment:)": context => {
1603
+ const width = argumentSource(context, "width");
1604
+ const height = argumentSource(context, "height");
1605
+ const update = {};
1606
+ if (width !== undefined)
1607
+ update.width = lowerValueExpression(width, context.bindings);
1608
+ if (height !== undefined)
1609
+ update.height = lowerValueExpression(height, context.bindings);
1610
+ applyFrame(context, update, alignment(argumentSource(context, "alignment"), "frame alignment"));
1611
+ },
1612
+ "frame(minWidth:idealWidth:maxWidth:minHeight:idealHeight:maxHeight:alignment:)": context => {
1613
+ const update = {};
1614
+ const minWidth = frameBound(argumentSource(context, "minWidth"), "minWidth", context.bindings, false);
1615
+ const idealWidth = frameBound(argumentSource(context, "idealWidth"), "idealWidth", context.bindings, false);
1616
+ const maxWidth = frameBound(argumentSource(context, "maxWidth"), "maxWidth", context.bindings, true);
1617
+ const minHeight = frameBound(argumentSource(context, "minHeight"), "minHeight", context.bindings, false);
1618
+ const idealHeight = frameBound(argumentSource(context, "idealHeight"), "idealHeight", context.bindings, false);
1619
+ const maxHeight = frameBound(argumentSource(context, "maxHeight"), "maxHeight", context.bindings, true);
1620
+ if (typeof minWidth === "number")
1621
+ update.minWidth = minWidth;
1622
+ if (typeof idealWidth === "number")
1623
+ update.idealWidth = idealWidth;
1624
+ if (maxWidth !== undefined)
1625
+ update.maxWidth = maxWidth;
1626
+ if (typeof minHeight === "number")
1627
+ update.minHeight = minHeight;
1628
+ if (typeof idealHeight === "number")
1629
+ update.idealHeight = idealHeight;
1630
+ if (maxHeight !== undefined)
1631
+ update.maxHeight = maxHeight;
1632
+ applyFrame(context, update, alignment(argumentSource(context, "alignment"), "frame alignment"));
1633
+ },
1634
+ "layoutPriority(_:)": context => {
1635
+ const priority = numberValue(argumentSource(context, "value"), undefined, context.bindings);
1636
+ if (priority === undefined || !Number.isFinite(priority))
1637
+ throw new SyntaxError(".layoutPriority(_:) needs a finite number");
1638
+ context.composer.layout({ layoutPriority: priority }, context.index);
1639
+ },
1640
+ "padding(_:)": context => padding(context, undefined, numberValue(argumentSource(context, "length"), undefined, context.bindings) ?? defaultPadding),
1641
+ "padding(_:_:)": context => padding(context, argumentSource(context, "edges"), numberValue(argumentSource(context, "length"), defaultPadding, context.bindings) ?? defaultPadding),
1642
+ "background(_:ignoresSafeAreaEdges:)": context => {
1643
+ const edges = argumentSource(context, "ignoresSafeAreaEdges")?.replace(/^(?:Edge\.Set)?\./, "");
1644
+ if (edges !== undefined && edges !== "all")
1645
+ throw new SyntaxError(`.background(_:ignoresSafeAreaEdges:) accepts only .all in native Mün (windows have no safe-area insets): ${argumentSource(context, "ignoresSafeAreaEdges")}`);
1646
+ const paint = lowerPaint(argumentSource(context, "style"));
1647
+ // Text and containers paint their own box; anything else (shapes,
1648
+ // controls) gets the background as a separate layer behind it.
1649
+ const node = context.composer.node;
1650
+ if (node.visual?.background || !(node.kind === "text" || isContainer(node)))
1651
+ context.composer.wrap();
1652
+ context.composer.enter(3);
1653
+ context.composer.visual({ background: paint }, context.index);
1654
+ },
1655
+ "background(alignment:content:)": context => layered(context, "background"),
1656
+ "overlay(alignment:content:)": context => layered(context, "overlay"),
1657
+ "font(_:)": context => {
1658
+ const source = argumentSource(context, "font");
1659
+ if (!source || source === "nil")
1660
+ throw new SyntaxError(".font(_:) needs a Font value such as .title or .system(size: 13)");
1661
+ context.composer.transform(node => inheritTypography(node, lowerFontValue(source)));
1662
+ },
1663
+ "fontWeight(_:)": context => {
1664
+ const source = argumentSource(context, "weight");
1665
+ if (source === undefined || source === "nil")
1666
+ throw new SyntaxError(".fontWeight(_:) needs a Font.Weight such as .semibold");
1667
+ context.composer.transform(node => inheritTypography(node, { weight: lowerFontWeight(source) }));
1668
+ },
1669
+ "bold(_:)": context => {
1670
+ const active = argumentSource(context, "isActive");
1671
+ if (active !== undefined && active !== "true" && active !== "false")
1672
+ throw new SyntaxError(".bold(_:) takes a static Bool");
1673
+ context.composer.transform(node => inheritTypography(node, { weight: active === "false" ? 400 : 700 }));
1674
+ },
1675
+ "italic(_:)": context => {
1676
+ const active = argumentSource(context, "isActive");
1677
+ if (active !== undefined && active !== "true" && active !== "false")
1678
+ throw new SyntaxError(".italic(_:) takes a static Bool");
1679
+ context.composer.transform(node => inheritTypography(node, { italic: active !== "false" }));
1680
+ },
1681
+ "lineLimit(_:)": context => {
1682
+ const source = argumentSource(context, "number");
1683
+ if (source === undefined || source === "nil")
1684
+ throw new SyntaxError(".lineLimit(_:) needs a static positive Int");
1685
+ const limit = numberValue(source, undefined, context.bindings);
1686
+ if (limit === undefined || !Number.isInteger(limit) || limit < 1)
1687
+ throw new SyntaxError(`.lineLimit(_:) needs a static positive Int: ${source}`);
1688
+ context.composer.transform(node => inheritTypography(node, { lineLimit: limit }));
1689
+ },
1690
+ "multilineTextAlignment(_:)": context => {
1691
+ const value = argumentSource(context, "alignment")?.replace(/^(?:TextAlignment)?\./, "");
1692
+ if (value !== "leading" && value !== "center" && value !== "trailing")
1693
+ throw new SyntaxError(`.multilineTextAlignment(_:) must be .leading, .center or .trailing: ${argumentSource(context, "alignment")}`);
1694
+ context.composer.transform(node => inheritTypography(node, { alignment: value }));
1695
+ },
1696
+ "foregroundStyle(_:)": context => {
1697
+ const foreground = lowerPaint(argumentSource(context, "style"));
1698
+ context.composer.transform(node => inheritEnvironment(node, { foreground }));
1699
+ },
1700
+ "fill(_:style:)": context => {
1701
+ if (context.composer.node.kind !== "panel")
1702
+ throw new SyntaxError(".fill(_:style:) applies to a Shape");
1703
+ if (context.args.has("style"))
1704
+ throw new SyntaxError(".fill(_:style:) with a FillStyle is not implemented in native Mün");
1705
+ const foreground = lowerPaint(argumentSource(context, "content"));
1706
+ context.composer.visual({ foreground }, context.index);
1707
+ },
1708
+ "cornerRadius(_:antialiased:)": context => {
1709
+ context.composer.enter(4);
1710
+ context.composer.visual({ cornerRadius: numberValue(argumentSource(context, "radius"), 0, context.bindings) }, context.index);
1711
+ },
1712
+ "opacity(_:)": context => {
1713
+ if (context.composer.node.visual?.opacity !== undefined)
1714
+ context.composer.wrap();
1715
+ context.composer.enter(5);
1716
+ context.composer.visual({ opacity: lowerValueExpression(argumentSource(context, "opacity"), context.bindings) }, context.index);
1717
+ },
1718
+ "offset(x:y:)": context => {
1719
+ if (context.composer.node.visual?.translationX !== undefined)
1720
+ context.composer.wrap();
1721
+ context.composer.enter(5);
1722
+ const x = argumentSource(context, "x");
1723
+ const y = argumentSource(context, "y");
1724
+ context.composer.visual({
1725
+ translationX: x ? lowerValueExpression(x, context.bindings) : literal(0),
1726
+ translationY: y ? lowerValueExpression(y, context.bindings) : literal(0),
1727
+ }, context.index);
1728
+ },
1729
+ "onAppear(perform:)": context => lifecycle(context, "appear"),
1730
+ "onDisappear(perform:)": context => lifecycle(context, "disappear"),
1731
+ "transition(_:)": context => context.composer.meta({ transition: lowerTransition(argumentSource(context, "transition")) }),
1732
+ // Resolved up front; it annotates the motion of what precedes it.
1733
+ "animation(_:value:)": () => { },
1734
+ "id(_:)": context => context.composer.meta({ identityKey: semanticIdentityKey(argumentSource(context, "id"), context.bindings) }),
1735
+ "disabled(_:)": context => {
1736
+ const disabled = lowerValueExpression(argumentSource(context, "disabled"), context.bindings);
1737
+ context.composer.transform(node => inheritEnvironment(node, { disabled }));
1738
+ },
1739
+ "accessibilityLabel(_:)": context => {
1740
+ const label = staticTitle(argumentSource(context, "label"), context.bindings, "accessibilityLabel");
1741
+ context.composer.semantic(node => ({ ...node, accessibility: { ...(node.accessibility ?? { role: "group" }), label } }));
1742
+ },
1743
+ "pickerStyle(_:)": context => {
1744
+ const style = argumentSource(context, "style")?.replace(/^\./, "");
1745
+ if (context.composer.node.kind !== "radioGroup")
1746
+ throw new SyntaxError(".pickerStyle(_:) applies to a Picker");
1747
+ if (style !== "radioGroup" && style !== "RadioGroupPickerStyle()") {
1748
+ throw new SyntaxError(`Native Mün renders Picker as a radio group; .pickerStyle(.${style}) is not implemented. Use .pickerStyle(.radioGroup).`);
1749
+ }
1750
+ },
1751
+ "tag(_:includeOptional:)": () => {
1752
+ throw new SyntaxError(".tag(_:) is only meaningful on Picker content rows in native Mün");
1753
+ },
1754
+ };
1755
+ /**
1756
+ * `.onAppear` / `.onDisappear`: run when the View becomes / stops being
1757
+ * semantically present. Repeated modifiers all run, in source order.
1758
+ */
1759
+ function lifecycle(context, phase) {
1760
+ const closure = argumentClosure(context, "perform");
1761
+ if (!closure)
1762
+ return;
1763
+ const action = actionFromClosure(closure.bodySource, context.bindings);
1764
+ const existing = context.composer.node.lifecycle;
1765
+ const previous = existing?.[phase];
1766
+ const combined = previous ? { kind: "sequence", actions: [previous, action] } : action;
1767
+ context.composer.meta({ lifecycle: { ...existing, [phase]: combined } });
1768
+ }
1769
+ function padding(context, edges, length) {
1770
+ const { composer } = context;
1771
+ const insets = edgeInsets(edges, length);
1772
+ // Containers inset their children; a leaf draws at its own origin, so its
1773
+ // padding is a wrapper.
1774
+ if (!isContainer(composer.node) || composer.stage > 1)
1775
+ composer.wrap();
1776
+ composer.enter(1);
1777
+ composer.layout({ padding: addPadding(composer.node.layout?.padding, insets) }, context.index);
1778
+ }
1779
+ function layered(context, layer) {
1780
+ const closure = argumentClosure(context, "content");
1781
+ const align = alignment(argumentSource(context, "alignment"), `${layer} alignment`);
1782
+ const base = context.composer.finish();
1783
+ const content = closure
1784
+ ? context.lowerer.lowerProgram(closure.body, context.bindings, [...context.path, "modifier", context.index, layer], null)
1785
+ : [];
1786
+ const layerNode = content.length === 1
1787
+ ? content[0]
1788
+ : { kind: "overlay", id: context.lowerer.id(`${layer}Content`, [...context.path, "modifier", context.index]), children: content };
1789
+ const { identityKey, transition, ...inner } = base;
1790
+ const node = {
1791
+ kind: "overlay",
1792
+ id: context.lowerer.id(layer, [...context.path, "modifier", context.index]),
1793
+ ...(identityKey ? { identityKey } : {}),
1794
+ ...(transition ? { transition } : {}),
1795
+ ...(align && align !== "center" ? { alignment: align } : {}),
1796
+ children: layer === "background" ? [layerNode, inner] : [inner, layerNode],
1797
+ };
1798
+ context.composer.layer(node);
1799
+ }
1800
+ function semanticIdentityKey(source, bindings) {
1801
+ if (!source)
1802
+ throw new SyntaxError("id requires a semantic identity value");
1803
+ const identityKey = lowerValueExpression(source, bindings);
1804
+ if (identityKey.kind === "literal"
1805
+ && ((typeof identityKey.value !== "string" && typeof identityKey.value !== "number")
1806
+ || (typeof identityKey.value === "number" && !Number.isFinite(identityKey.value)))) {
1807
+ throw new SyntaxError("Mün semantic identity keys must resolve to a string or finite number");
1808
+ }
1809
+ return identityKey;
1810
+ }
1811
+ function idModifierSource(modifier) {
1812
+ const argument = modifier.arguments[0];
1813
+ return argument?.value.kind === "raw" ? argument.value.source.trim() : undefined;
1814
+ }
1815
+ function unsupportedModifier(name) {
1816
+ const spec = swiftUIApiManifest.modifiers.find(modifier => modifier.name === name);
1817
+ if (spec && spec.signatures.length > 0) {
1818
+ return `View modifier .${spec.signatures.map(signature => signature.signature).join(" / .")} is a SwiftUI modifier implemented only by the compatibility Web graph; native Semantic UI IR does not support it`;
1819
+ }
1820
+ const extension = munExtension("modifier", name);
1821
+ if (extension)
1822
+ return `.${extension.signatures[0]} is a compatibility-only Mün spelling.${extension.replacement ? ` Use ${extension.replacement}.` : ""}`;
1823
+ if (spec)
1824
+ return `.${name}(…) is a compatibility-only Mün modifier, not SwiftUI; canonical .mun does not accept it`;
1825
+ const unsupported = swiftUIApiManifest.unsupported.modifiers.find(item => item.name === name);
1826
+ if (unsupported)
1827
+ return `.${name}(…) is a SwiftUI modifier Mün does not implement yet: ${unsupported.reason}`;
1828
+ return `.${name}(…) is not a SwiftUI View modifier known to Mün`;
1829
+ }
1830
+ function unsupportedView(name) {
1831
+ const spec = swiftUIApiManifest.views[name];
1832
+ if (spec)
1833
+ return `SwiftUI View '${name}' is implemented only by the compatibility Web graph; native Semantic UI IR does not support it`;
1834
+ const extension = munExtension("view", name);
1835
+ if (extension?.status === "compatibility")
1836
+ return `'${name}' is a compatibility-only Mün View.${extension.replacement ? ` Use ${extension.replacement}.` : ""}`;
1837
+ const unsupported = swiftUIApiManifest.unsupported.views.find(item => item.name === name);
1838
+ if (unsupported)
1839
+ return `SwiftUI View '${name}' is not implemented by Mün yet: ${unsupported.reason}`;
1840
+ return undefined;
1841
+ }
1842
+ /** The compiler's native implementation inventory, checked against the parity manifest. */
1843
+ export function nativeLoweringMetadata() {
1844
+ return {
1845
+ views: Object.keys(nativeViews).sort(),
1846
+ modifiers: Object.keys(nativeModifiers).sort(),
1847
+ values: nativeValueImplementations(),
1848
+ extensions: ["Window.init(_:width:height:content:)", "Color.init(_:)"],
1849
+ };
1850
+ }
1851
+ /**
1852
+ * Development-only cache of lowered custom View instance bodies, shared by
1853
+ * successive compiles of one project. An entry is reused only when the
1854
+ * instance's call-site inputs (bindings, identity, enclosing scopes and the
1855
+ * types of all states declared before it) are identical and every View
1856
+ * declaration it depends on is byte-identical. Production compiles never use
1857
+ * it; the cached and uncached IR are identical by construction and by test.
1858
+ */
1859
+ export class MunLoweringCache {
1860
+ #entries = new Map();
1861
+ #used = new Set();
1862
+ #instancesLowered = 0;
1863
+ #instancesReused = 0;
1864
+ #declarationsLowered = new Set();
1865
+ /** View -> Views its instance bodies depend on, from the last successful compile. */
1866
+ #graph = new Map();
1867
+ /** @internal */
1868
+ begin() {
1869
+ this.#used = new Set();
1870
+ this.#instancesLowered = 0;
1871
+ this.#instancesReused = 0;
1872
+ this.#declarationsLowered = new Set();
1873
+ }
1874
+ /** @internal Keep only entries used by this (successful) compile. */
1875
+ commit(graph) {
1876
+ for (const key of this.#entries.keys())
1877
+ if (!this.#used.has(key))
1878
+ this.#entries.delete(key);
1879
+ this.#graph = new Map(graph);
1880
+ return this.stats();
1881
+ }
1882
+ /** @internal */
1883
+ lookup(key) {
1884
+ return this.#entries.get(key);
1885
+ }
1886
+ /** @internal */
1887
+ reused(key) {
1888
+ this.#used.add(key);
1889
+ this.#instancesReused += 1;
1890
+ }
1891
+ /** @internal */
1892
+ lowered(name) {
1893
+ this.#instancesLowered += 1;
1894
+ this.#declarationsLowered.add(name);
1895
+ }
1896
+ /** @internal */
1897
+ store(key, entry) {
1898
+ this.#entries.set(key, entry);
1899
+ this.#used.add(key);
1900
+ }
1901
+ stats() {
1902
+ return {
1903
+ instancesLowered: this.#instancesLowered,
1904
+ instancesReused: this.#instancesReused,
1905
+ declarationsLowered: [...this.#declarationsLowered].sort(),
1906
+ entries: this.#entries.size,
1907
+ };
1908
+ }
1909
+ /** View -> custom Views its body uses, as observed by the last successful compile. */
1910
+ dependencyGraph() {
1911
+ return this.#graph;
1912
+ }
1913
+ /** Views whose lowering depends on any of `changed` (transitively), including `changed` themselves. */
1914
+ affectedBy(changed) {
1915
+ const dependents = new Map();
1916
+ for (const [view, dependencies] of this.#graph) {
1917
+ for (const dependency of dependencies) {
1918
+ let set = dependents.get(dependency);
1919
+ if (!set)
1920
+ dependents.set(dependency, set = new Set());
1921
+ set.add(view);
1922
+ }
1923
+ }
1924
+ const affected = new Set();
1925
+ const pending = [...changed];
1926
+ while (pending.length) {
1927
+ const view = pending.pop();
1928
+ if (affected.has(view))
1929
+ continue;
1930
+ affected.add(view);
1931
+ for (const dependent of dependents.get(view) ?? [])
1932
+ pending.push(dependent);
1933
+ }
1934
+ return affected;
1935
+ }
1936
+ clear() {
1937
+ this.#entries.clear();
1938
+ this.#graph = new Map();
1939
+ }
1940
+ }
1941
+ /** JSON replacer for cache keys: keeps -0/0, NaN/null and numbers/strings distinct. */
1942
+ function cacheKeyValue(_key, value) {
1943
+ if (typeof value === "number")
1944
+ return `\u0000n${Object.is(value, -0) ? "-0" : String(value)}`;
1945
+ if (typeof value === "string")
1946
+ return `\u0000s${value}`;
1947
+ if (value === undefined)
1948
+ return "\u0000u";
1949
+ return value;
1950
+ }
1951
+ /** 53-bit string hash (cyrb53) used for rolling cache-key digests. */
1952
+ function hashString(text, seed = 0) {
1953
+ let h1 = 0xdeadbeef ^ seed;
1954
+ let h2 = 0x41c6ce57 ^ seed;
1955
+ for (let index = 0; index < text.length; index += 1) {
1956
+ const code = text.charCodeAt(index);
1957
+ h1 = Math.imul(h1 ^ code, 2654435761);
1958
+ h2 = Math.imul(h2 ^ code, 1597334677);
1959
+ }
1960
+ h1 = Math.imul(h1 ^ (h1 >>> 16), 2246822507) ^ Math.imul(h2 ^ (h2 >>> 13), 3266489909);
1961
+ h2 = Math.imul(h2 ^ (h2 >>> 16), 2246822507) ^ Math.imul(h1 ^ (h1 >>> 13), 3266489909);
1962
+ return 4294967296 * (2097151 & h2) + (h1 >>> 0);
1963
+ }
1964
+ class UiLowerer {
1965
+ #structs;
1966
+ #qualifiedNameByDeclaration;
1967
+ #semanticViews = new Map();
1968
+ #componentStack = [];
1969
+ /** Absolute source base for the currently lowered custom View body. */
1970
+ #sourceBaseStack = [];
1971
+ #states;
1972
+ #stateTypes;
1973
+ /** Declared Mün type per state identity; development metadata only. */
1974
+ #declaredTypes = new Map();
1975
+ /** Distinct custom View declarations whose bodies were lowered this compile. */
1976
+ #loweredViewDeclarations = new Set();
1977
+ /** Development-only semantic node -> canonical source range. */
1978
+ #sourceSpans = new Map();
1979
+ /** Enclosing ForEach templates; View-local state inside them is item-scoped. */
1980
+ #forEachScopes = [];
1981
+ /** Key path per collection state, recorded by the ForEach that renders it. */
1982
+ #collectionKeyPaths = new Map();
1983
+ /** Development lowering cache and the instance bodies currently being recorded. */
1984
+ #cache;
1985
+ #captures = [];
1986
+ /**
1987
+ * Rolling digest of every state name/type declared so far, in order. Call-site
1988
+ * initializer resolution already type-checks what an instance receives; this
1989
+ * keeps reuse conservative should a body ever observe other state types.
1990
+ */
1991
+ #stateTypesDigest = 0;
1992
+ /** Digest of the declared View set: adding/removing a View can change name resolution. */
1993
+ #declarationSetKey;
1994
+ /** View -> custom Views its instance bodies used in this compile. */
1995
+ #dependencyGraph = new Map();
1996
+ constructor(structs, states, cache) {
1997
+ const declarationIndex = collectStructDeclarations(structs);
1998
+ this.#structs = declarationIndex.byQualifiedName;
1999
+ this.#qualifiedNameByDeclaration = declarationIndex.qualifiedNameByDeclaration;
2000
+ this.#states = [...states];
2001
+ this.#stateTypes = stateTypeMap(states);
2002
+ for (const [name, type] of this.#stateTypes)
2003
+ this.#digestStateType(name, type);
2004
+ for (const view of semanticViewsForStructs(structs))
2005
+ this.#semanticViews.set(view.qualifiedName, view);
2006
+ this.#cache = cache;
2007
+ this.#declarationSetKey = cache ? String(hashString([...this.#structs.keys()].sort().join("\n"))) : "";
2008
+ }
2009
+ #digestStateType(name, type) {
2010
+ this.#stateTypesDigest = hashString(`${name}\u0000${type}`, this.#stateTypesDigest % 4294967296);
2011
+ }
2012
+ #record(effect) {
2013
+ for (const capture of this.#captures)
2014
+ capture.effects.push(effect);
2015
+ }
2016
+ #depend(name, source) {
2017
+ for (const capture of this.#captures)
2018
+ capture.dependencies.set(name, source);
2019
+ }
2020
+ #addState(state, type) {
2021
+ this.#states.push(state);
2022
+ this.#stateTypes.set(state.name, type);
2023
+ this.#digestStateType(state.name, type);
2024
+ this.#record({ kind: "state", state, type });
2025
+ }
2026
+ #setDeclaredType(name, type) {
2027
+ this.#declaredTypes.set(name, type);
2028
+ this.#record({ kind: "declaredType", name, type });
2029
+ }
2030
+ #markLoweredView(name) {
2031
+ this.#loweredViewDeclarations.add(name);
2032
+ this.#record({ kind: "view", name });
2033
+ }
2034
+ #setCollectionKeyPath(state, keyPath) {
2035
+ const existing = this.#collectionKeyPaths.get(state);
2036
+ if (existing && existing.join(".") !== keyPath.join(".")) {
2037
+ throw new SyntaxError(`Collection '${state}' is rendered with conflicting ForEach id key paths`);
2038
+ }
2039
+ this.#collectionKeyPaths.set(state, keyPath);
2040
+ this.#record({ kind: "collection", state, keyPath });
2041
+ }
2042
+ /** Record a node's source span; `start`/`end` are relative to `component`'s body when it is set. */
2043
+ #recordSpan(id, start, end, component) {
2044
+ const existing = this.#sourceSpans.get(id);
2045
+ // `splitViewChain` reparses a raw expression relative to that expression,
2046
+ // then the outer node is recorded again with its true body-relative range.
2047
+ // Prefer that later span inside the same component. A child custom View,
2048
+ // however, already recorded its output against its declaration body; keep
2049
+ // that source instead of replacing it with the parent's call site.
2050
+ if (existing && existing.component !== component)
2051
+ return;
2052
+ const base = component ? this.#structs.get(component)?.bodyExpressionRange.start ?? 0 : 0;
2053
+ this.#sourceSpans.set(id, { id, start: base + start, end: base + end, ...(component ? { component } : {}) });
2054
+ if (component)
2055
+ this.#record({ kind: "span", id, component, start, end });
2056
+ }
2057
+ #replay(effect) {
2058
+ switch (effect.kind) {
2059
+ case "state":
2060
+ this.#addState(effect.state, effect.type);
2061
+ break;
2062
+ case "declaredType":
2063
+ this.#setDeclaredType(effect.name, effect.type);
2064
+ break;
2065
+ case "view":
2066
+ this.#markLoweredView(effect.name);
2067
+ break;
2068
+ case "collection":
2069
+ this.#setCollectionKeyPath(effect.state, effect.keyPath);
2070
+ break;
2071
+ case "span":
2072
+ this.#recordSpan(effect.id, effect.start, effect.end, effect.component);
2073
+ break;
2074
+ }
2075
+ }
2076
+ #addDependencies(view, dependencies) {
2077
+ let set = this.#dependencyGraph.get(view);
2078
+ if (!set)
2079
+ this.#dependencyGraph.set(view, set = new Set());
2080
+ for (const dependency of dependencies)
2081
+ if (dependency !== view)
2082
+ set.add(dependency);
2083
+ }
2084
+ /** View -> custom Views its body uses, observed while lowering this program. */
2085
+ dependencyGraph() {
2086
+ return this.#dependencyGraph;
2087
+ }
2088
+ /**
2089
+ * Lower one custom View instance body, reusing the previous compile's result
2090
+ * when every input it observed is unchanged. `lower` must perform the body's
2091
+ * whole lowering (local state binding included).
2092
+ */
2093
+ #lowerInstance(qualifiedName, declaration, inputs, lower) {
2094
+ const cache = this.#cache;
2095
+ this.#depend(qualifiedName, declaration.source);
2096
+ if (!cache)
2097
+ return lower();
2098
+ const key = [
2099
+ qualifiedName,
2100
+ this.#declarationSetKey,
2101
+ this.#componentStack.join(">"),
2102
+ this.#forEachScopes.at(-1) ?? "",
2103
+ this.#stateTypesDigest,
2104
+ inputs,
2105
+ ].join("\u0001");
2106
+ const entry = cache.lookup(key);
2107
+ if (entry && [...entry.dependencies].every(([name, source]) => this.#structs.get(name)?.source === source)) {
2108
+ for (const effect of entry.effects)
2109
+ this.#replay(effect);
2110
+ for (const [name, source] of entry.dependencies)
2111
+ this.#depend(name, source);
2112
+ this.#addDependencies(qualifiedName, entry.dependencies.keys());
2113
+ cache.reused(key);
2114
+ return entry.node;
2115
+ }
2116
+ const capture = { dependencies: new Map([[qualifiedName, declaration.source]]), effects: [] };
2117
+ this.#captures.push(capture);
2118
+ let node;
2119
+ try {
2120
+ node = lower();
2121
+ }
2122
+ finally {
2123
+ this.#captures.pop();
2124
+ }
2125
+ cache.lowered(qualifiedName);
2126
+ this.#addDependencies(qualifiedName, capture.dependencies.keys());
2127
+ cache.store(key, { dependencies: capture.dependencies, node, effects: capture.effects });
2128
+ return node;
2129
+ }
2130
+ resolveComponent(name) {
2131
+ const scope = this.#componentStack.at(-1);
2132
+ for (const candidate of semanticViewLookupCandidates(name, scope)) {
2133
+ const declaration = this.#structs.get(candidate);
2134
+ const semanticView = this.#semanticViews.get(candidate);
2135
+ if (declaration && semanticView) {
2136
+ this.#depend(candidate, declaration.source);
2137
+ return { declaration, semanticView };
2138
+ }
2139
+ }
2140
+ return undefined;
2141
+ }
2142
+ qualifiedName(declaration) {
2143
+ const qualifiedName = this.#qualifiedNameByDeclaration.get(declaration);
2144
+ if (!qualifiedName)
2145
+ throw new SyntaxError(`Native View '${declaration.name}' has no qualified semantic identity`);
2146
+ return qualifiedName;
2147
+ }
2148
+ declaredStateTypes() {
2149
+ return this.#declaredTypes;
2150
+ }
2151
+ loweredViewDeclarations() {
2152
+ return this.#loweredViewDeclarations;
2153
+ }
2154
+ sourceSpans() {
2155
+ return [...this.#sourceSpans.values()];
2156
+ }
2157
+ recordSource(nodes, node) {
2158
+ const component = this.#componentStack.at(-1);
2159
+ const base = this.#sourceBaseStack.at(-1) ?? 0;
2160
+ const componentBase = component ? this.#structs.get(component)?.bodyExpressionRange.start ?? 0 : 0;
2161
+ for (const output of nodes) {
2162
+ this.#recordSpan(output.id, base - componentBase + node.range.start, base - componentBase + node.range.end, component);
2163
+ }
2164
+ }
2165
+ states() {
2166
+ return this.#states;
2167
+ }
2168
+ collectionKeyPath(state) {
2169
+ return this.#collectionKeyPaths.get(state) ?? ["id"];
2170
+ }
2171
+ lowerForEach(context, keyPath) {
2172
+ const collectionSource = argumentSource(context, "data");
2173
+ if (!collectionSource)
2174
+ throw new SyntaxError("ForEach requires a collection");
2175
+ const closure = argumentClosure(context, "content");
2176
+ if (!closure?.parameter) {
2177
+ throw new SyntaxError("ForEach requires a content closure with an item parameter: ForEach(items, id: \\.id) { item in ... }");
2178
+ }
2179
+ const { bindings, path, statePath } = context;
2180
+ const id = this.id("forEach", path);
2181
+ const collection = lowerValueExpression(collectionSource, bindings);
2182
+ let source = collection;
2183
+ while (source.kind === "filter")
2184
+ source = source.collection;
2185
+ if (source.kind === "state") {
2186
+ this.#setCollectionKeyPath(source.state, keyPath);
2187
+ }
2188
+ else if (source.kind !== "item") {
2189
+ throw new SyntaxError(`ForEach collection must be @State, an item field, or a filter of one: ${collectionSource}`);
2190
+ }
2191
+ const itemBindings = new Map(bindings);
2192
+ itemBindings.set(closure.parameter, { kind: "item", forEach: id, path: [] });
2193
+ // Template identities are static; the runtime composes each instance with
2194
+ // its item key. Item-scoped View state therefore keeps a static template
2195
+ // path here and is instantiated per key by the runtime.
2196
+ this.#forEachScopes.push(id);
2197
+ try {
2198
+ return {
2199
+ kind: "forEach",
2200
+ id,
2201
+ collection,
2202
+ keyPath,
2203
+ children: this.lowerProgram(closure.body, itemBindings, [...path, "each"], statePath ? [...statePath, "each"] : [...path, "each"]),
2204
+ };
2205
+ }
2206
+ finally {
2207
+ this.#forEachScopes.pop();
2208
+ }
2209
+ }
2210
+ id(prefix, path) {
2211
+ return `@node/${identityPathKey([...path, "kind", prefix])}`;
2212
+ }
2213
+ bindLocalStates(declaration, bindings, instancePath) {
2214
+ const fields = declaration.fields.filter(field => field.kind === "state");
2215
+ if (fields.length === 0)
2216
+ return;
2217
+ if (!instancePath) {
2218
+ throw new SyntaxError(`Stateful native View '${declaration.name}' cannot use a dynamic .id(_:) identity until runtime-owned state scopes are available`);
2219
+ }
2220
+ const instanceId = identityPathKey(instancePath);
2221
+ for (const field of fields) {
2222
+ if (field.initializer === undefined) {
2223
+ throw new SyntaxError(`Native @State member '${declaration.name}.${field.name}' requires an initial value`);
2224
+ }
2225
+ assertWellFormedValueSource(field.initializer, `Native @State member '${declaration.name}.${field.name}'`);
2226
+ const initial = lowerValueExpression(field.initializer, bindings);
2227
+ if (initial.kind !== "literal") {
2228
+ throw new SyntaxError(`Native @State member '${declaration.name}.${field.name}' requires a scalar initial value for now`);
2229
+ }
2230
+ const stateName = `@component/${instanceId}/${field.name}`;
2231
+ if (field.type) {
2232
+ const declared = parseMunType(field.type, { canonical: false, what: `${declaration.name}.${field.name}` });
2233
+ this.#setDeclaredType(stateName, displayMunType(declared));
2234
+ if (!valueMatchesType(initial.value, declared)) {
2235
+ throw new SyntaxError(`@State '${declaration.name}.${field.name}' is declared ${displayMunType(declared)} but its initial value is ${describeValueType(initial.value)}`);
2236
+ }
2237
+ }
2238
+ else {
2239
+ this.#setDeclaredType(stateName, initial.value === null ? "nil" : Array.isArray(initial.value) ? "Array" : typeof initial.value);
2240
+ }
2241
+ const scope = this.#forEachScopes.at(-1);
2242
+ this.#addState({ name: stateName, initial: initial.value, ...(scope ? { scope } : {}) }, initial.value === null ? "null" : Array.isArray(initial.value) ? "array" : typeof initial.value);
2243
+ bindings.set(field.name, { kind: "state", state: stateName });
2244
+ }
2245
+ }
2246
+ lowerEntry(declaration) {
2247
+ const bindings = new Map();
2248
+ for (const field of declaration.fields) {
2249
+ if (field.kind === "binding") {
2250
+ throw new SyntaxError(`Native entry View '${declaration.name}' member '${field.name}' uses @Binding without an owning parent`);
2251
+ }
2252
+ if (field.kind === "stored") {
2253
+ if (field.initializer === undefined) {
2254
+ throw new SyntaxError(`Native entry View '${declaration.name}' stored member '${field.name}' requires a default value`);
2255
+ }
2256
+ bindings.set(field.name, lowerValueExpression(field.initializer, bindings));
2257
+ }
2258
+ }
2259
+ const qualifiedName = this.qualifiedName(declaration);
2260
+ const instancePath = ["entry", qualifiedName];
2261
+ // The entry body is always lowered (it is the root instance); its
2262
+ // dependencies are still recorded for the project dependency graph.
2263
+ const capture = { dependencies: new Map([[qualifiedName, declaration.source]]), effects: [] };
2264
+ this.#captures.push(capture);
2265
+ try {
2266
+ this.bindLocalStates(declaration, bindings, instancePath);
2267
+ this.#cache?.lowered(qualifiedName);
2268
+ this.#componentStack.push(qualifiedName);
2269
+ try {
2270
+ return this.lowerBody(declaration, bindings, [...instancePath, "body"]);
2271
+ }
2272
+ finally {
2273
+ this.#componentStack.pop();
2274
+ }
2275
+ }
2276
+ finally {
2277
+ this.#captures.pop();
2278
+ this.#addDependencies(qualifiedName, capture.dependencies.keys());
2279
+ }
2280
+ }
2281
+ lowerBody(declaration, bindings, path, statePath = path) {
2282
+ this.#markLoweredView(this.qualifiedName(declaration));
2283
+ const base = declaration.bodyExpressionRange.start;
2284
+ this.#sourceBaseStack.push(base);
2285
+ try {
2286
+ let program;
2287
+ try {
2288
+ // Builder transforms such as modifier-chain parsing naturally operate
2289
+ // relative to the custom View body. Keep every builder range in that
2290
+ // coordinate space and add the absolute declaration base only when
2291
+ // emitting development source metadata.
2292
+ program = parseMunBuilder(declaration.bodyExpressionSource, 0);
2293
+ }
2294
+ catch (error) {
2295
+ if (typeof error?.offset === "number") {
2296
+ ;
2297
+ error.offset += base;
2298
+ }
2299
+ throw error;
2300
+ }
2301
+ const nodes = this.lowerProgram(program, bindings, path, statePath);
2302
+ if (nodes.length !== 1) {
2303
+ throw new SyntaxError(`Native custom View '${declaration.name}' body produces ${nodes.length} root views; wrap them in a VStack, HStack or ZStack`);
2304
+ }
2305
+ return nodes[0];
2306
+ }
2307
+ finally {
2308
+ this.#sourceBaseStack.pop();
2309
+ }
2310
+ }
2311
+ lowerNodes(node, bindings, path, statePath = path) {
2312
+ if (node.kind === "raw") {
2313
+ const color = colorViewChain(node.source);
2314
+ const chain = color ?? splitViewChain(node.source);
2315
+ if (chain.base.kind === "raw" && !color) {
2316
+ throw new SyntaxError(`Unsupported native view expression: ${chain.base.source}`);
2317
+ }
2318
+ const scopedPath = nodeIdentityPathForModifiers(path, chain.modifiers, bindings);
2319
+ const scopedStatePath = stateIdentityPathForModifiers(statePath, chain.modifiers, bindings);
2320
+ let bases;
2321
+ if (color) {
2322
+ bases = [colorView(this, color.colorSource, scopedPath)];
2323
+ }
2324
+ else {
2325
+ // `splitViewChain` reparses `node.source` from offset zero. Descendant
2326
+ // builder ranges are therefore relative to this raw expression rather
2327
+ // than the enclosing custom View body. Carry the raw node's body-relative
2328
+ // start while lowering that reparsed base so source metadata remains exact.
2329
+ const sourceBase = (this.#sourceBaseStack.at(-1) ?? 0) + node.range.start;
2330
+ this.#sourceBaseStack.push(sourceBase);
2331
+ try {
2332
+ bases = this.lowerNodes(chain.base, bindings, scopedPath, scopedStatePath);
2333
+ }
2334
+ finally {
2335
+ this.#sourceBaseStack.pop();
2336
+ }
2337
+ }
2338
+ // Modifiers on a Group apply to each of its Views, as in SwiftUI.
2339
+ const outputs = bases.map((base, index) => this.applyModifiers(base, chain.modifiers, bindings, bases.length > 1 ? [...scopedPath, "group", index] : scopedPath));
2340
+ this.recordSource(outputs, node);
2341
+ return outputs;
2342
+ }
2343
+ if (node.kind === "conditional") {
2344
+ const outputs = [this.lowerConditional(node, bindings, path, statePath)];
2345
+ this.recordSource(outputs, node);
2346
+ return outputs;
2347
+ }
2348
+ const outputs = this.lowerCall(node, bindings, path, statePath);
2349
+ this.recordSource(outputs, node);
2350
+ return outputs;
2351
+ }
2352
+ lower(node, bindings = emptyBindings, path, statePath = path) {
2353
+ const nodes = this.lowerNodes(node, bindings, path, statePath);
2354
+ if (nodes.length !== 1)
2355
+ throw new SyntaxError("Expected exactly one View here; a Group expands to several");
2356
+ return nodes[0];
2357
+ }
2358
+ lowerProgram(program, bindings, path, statePath = path) {
2359
+ return program.statements.flatMap((statement, index) => this.lowerNodes(statement, bindings, [...path, "child", index], childIdentityPath(statePath, "child", index)));
2360
+ }
2361
+ lowerConditional(node, bindings, path, statePath) {
2362
+ const otherwise = node.otherwise;
2363
+ return {
2364
+ kind: "conditional",
2365
+ id: this.id("conditional", path),
2366
+ condition: lowerValueExpression(node.condition.source, bindings),
2367
+ then: this.lowerProgram(node.then, bindings, [...path, "then"], childIdentityPath(statePath, "then")),
2368
+ otherwise: !otherwise
2369
+ ? []
2370
+ : otherwise.kind === "program"
2371
+ ? this.lowerProgram(otherwise, bindings, [...path, "otherwise"], childIdentityPath(statePath, "otherwise"))
2372
+ : [this.lowerConditional(otherwise, bindings, [...path, "otherwise"], childIdentityPath(statePath, "otherwise"))],
2373
+ };
2374
+ }
2375
+ applyModifiers(node, modifiers, bindings, path) {
2376
+ if (modifiers.length === 0)
2377
+ return node;
2378
+ const steps = modifiers.map(modifier => {
2379
+ const symbols = nativeModifierSymbols(modifier.name);
2380
+ if (!symbols)
2381
+ throw new SyntaxError(unsupportedModifier(modifier.name));
2382
+ const supplied = modifier.arguments.map(argument => componentSemanticArgument(argument, bindings, this.#stateTypes));
2383
+ if (modifier.trailing)
2384
+ supplied.push({ type: "function", trailing: true, trailingClosure: modifier.trailing });
2385
+ const resolution = resolveContractCall(symbols, supplied, { kind: "modifier", owner: modifier.name, unsupported: swiftUIUnsupportedModifierSignatures(modifier.name) });
2386
+ if (!nativeModifiers[resolution.signature])
2387
+ throw new SyntaxError(`Internal error: no native implementation for .${resolution.signature}`);
2388
+ return { modifier, signature: resolution.signature, args: resolution.arguments };
2389
+ });
2390
+ const animations = steps.flatMap((step, index) => {
2391
+ if (step.signature !== "animation(_:value:)")
2392
+ return [];
2393
+ const plan = animationPlan(argumentSource(step, "animation"));
2394
+ const trigger = argumentSource(step, "value");
2395
+ return [{ index, plan, ...(trigger ? { trigger: lowerValueExpression(trigger, bindings) } : {}) }];
2396
+ });
2397
+ const composer = new NodeComposer(node, animations);
2398
+ steps.forEach((step, index) => {
2399
+ nativeModifiers[step.signature]({ lowerer: this, composer, args: step.args, bindings, index, modifier: step.modifier, path });
2400
+ });
2401
+ return composer.finish();
2402
+ }
2403
+ lowerComponent(call, declaration, semanticView, callerBindings, path, statePath) {
2404
+ const qualifiedName = semanticView.qualifiedName;
2405
+ if (this.#componentStack.includes(qualifiedName)) {
2406
+ throw new SyntaxError(`Recursive native View expansion is not supported: ${[...this.#componentStack, qualifiedName].join(" -> ")}`);
2407
+ }
2408
+ const supplied = call.arguments.map(argument => componentSemanticArgument(argument, callerBindings, this.#stateTypes));
2409
+ if (call.trailing) {
2410
+ supplied.push({
2411
+ type: "function",
2412
+ trailing: true,
2413
+ trailingBodySource: call.trailing.bodySource,
2414
+ });
2415
+ }
2416
+ const result = resolveSemanticInitializer(semanticView.symbol.initializers, supplied, semanticView.genericParameters);
2417
+ if (!result.ok) {
2418
+ const hidden = call.arguments.find(argument => argument.label !== undefined && declaration.fields.some(field => field.name === argument.label && (field.access === "private" || field.access === "fileprivate" || field.kind === "state")));
2419
+ if (hidden?.label) {
2420
+ const field = declaration.fields.find(item => item.name === hidden.label);
2421
+ throw new SyntaxError(field.kind === "state"
2422
+ ? `'${declaration.name}.${hidden.label}' is @State, owned by the View; a caller cannot initialize it (pass a @Binding instead)`
2423
+ : `'${declaration.name}.${hidden.label}' is ${field.access}; a caller cannot initialize it`);
2424
+ }
2425
+ const candidates = result.failure.candidates.map(candidate => candidate.signature).join("; ");
2426
+ const prefix = result.failure.kind === "ambiguous"
2427
+ ? "Ambiguous initializer"
2428
+ : "No matching initializer";
2429
+ throw new SyntaxError(`${prefix} for native View '${declaration.name}'.${candidates ? ` Available initializers: ${candidates}.` : ""}`);
2430
+ }
2431
+ const selected = semanticView.initializers[result.resolution.initializerIndex];
2432
+ if (!selected) {
2433
+ throw new SyntaxError(`Native View '${declaration.name}' resolved an unknown initializer`);
2434
+ }
2435
+ const fieldBindings = new Map();
2436
+ if (selected.synthesized === "memberwise") {
2437
+ for (let index = 0; index < selected.parameters.length; index += 1) {
2438
+ const parameter = selected.parameters[index];
2439
+ const field = declaration.fields.find(candidate => candidate.name === parameter.name);
2440
+ if (!field)
2441
+ continue;
2442
+ const normalized = result.resolution.arguments[index];
2443
+ const sourceArgument = normalized?.sourceArgument;
2444
+ if (field.kind === "binding" && sourceArgument?.value.kind === "raw") {
2445
+ const binding = bindingStateExpression(sourceArgument.value.source, callerBindings);
2446
+ const actualType = this.#stateTypes.get(binding.state);
2447
+ if (!actualType) {
2448
+ throw new SyntaxError(`Native @Binding '${declaration.name}.${field.name}' does not reference known state '${binding.state}'`);
2449
+ }
2450
+ const expectedType = field.type?.trim();
2451
+ if (expectedType && !bindingTypeMatches(expectedType, actualType)) {
2452
+ throw new SyntaxError(`Native @Binding '${declaration.name}.${field.name}' expects ${expectedType} state, received ${swiftTypeName(actualType)}`);
2453
+ }
2454
+ fieldBindings.set(field.name, binding);
2455
+ continue;
2456
+ }
2457
+ if (sourceArgument?.value.kind === "raw") {
2458
+ fieldBindings.set(field.name, lowerValueExpression(sourceArgument.value.source, callerBindings));
2459
+ continue;
2460
+ }
2461
+ if (field.initializer !== undefined) {
2462
+ fieldBindings.set(field.name, lowerValueExpression(field.initializer, fieldBindings));
2463
+ continue;
2464
+ }
2465
+ throw new SyntaxError(`Initializer ${selected.signature} did not bind required field '${field.name}'`);
2466
+ }
2467
+ // Private stored members are not parameters; they keep their defaults.
2468
+ for (const field of declaration.fields) {
2469
+ if (field.kind === "stored" && !fieldBindings.has(field.name) && field.initializer !== undefined) {
2470
+ fieldBindings.set(field.name, lowerValueExpression(field.initializer, fieldBindings));
2471
+ }
2472
+ }
2473
+ }
2474
+ else {
2475
+ const initializer = declaration.initializers[selected.index];
2476
+ if (!initializer) {
2477
+ throw new SyntaxError(`Native View '${declaration.name}' resolved an unknown explicit initializer`);
2478
+ }
2479
+ const parameterBindings = new Map();
2480
+ const defaults = initializerDefaultSources(initializer.parametersSource, selected.parameters);
2481
+ for (let index = 0; index < selected.parameters.length; index += 1) {
2482
+ const parameter = selected.parameters[index];
2483
+ const name = parameter.name;
2484
+ if (!name)
2485
+ throw new SyntaxError(`Native initializer ${selected.signature} has an unnamed parameter`);
2486
+ const normalized = result.resolution.arguments[index];
2487
+ const sourceArgument = normalized?.sourceArgument;
2488
+ const source = sourceArgument?.value.kind === "raw"
2489
+ ? sourceArgument.value.source
2490
+ : defaults.get(name);
2491
+ if (!source) {
2492
+ throw new SyntaxError(`Native initializer ${selected.signature} could not resolve parameter '${name}'`);
2493
+ }
2494
+ if (parameter.kind === "binding") {
2495
+ const binding = bindingStateExpression(source, callerBindings);
2496
+ const actualType = this.#stateTypes.get(binding.state);
2497
+ if (!actualType) {
2498
+ throw new SyntaxError(`Native initializer binding '${name}' does not reference known state '${binding.state}'`);
2499
+ }
2500
+ const expectedType = parameter.type?.trim();
2501
+ if (expectedType && !bindingTypeMatches(expectedType, actualType)) {
2502
+ throw new SyntaxError(`Native initializer binding '${name}' expects ${expectedType} state, received ${actualType}`);
2503
+ }
2504
+ parameterBindings.set(name, binding);
2505
+ }
2506
+ else {
2507
+ const scope = new Map([...callerBindings, ...parameterBindings]);
2508
+ parameterBindings.set(name, lowerValueExpression(source, scope));
2509
+ }
2510
+ }
2511
+ const initializerScope = new Map([...callerBindings, ...parameterBindings]);
2512
+ for (const [fieldName, expression] of explicitInitializerAssignments(initializer.bodySource)) {
2513
+ const field = declaration.fields.find(candidate => candidate.name === fieldName);
2514
+ if (!field) {
2515
+ throw new SyntaxError(`Native initializer ${selected.signature} assigns unknown field '${fieldName}'`);
2516
+ }
2517
+ if (field.kind === "state") {
2518
+ throw new SyntaxError(`Native initializer ${selected.signature} cannot replace @State storage '${fieldName}'`);
2519
+ }
2520
+ const value = lowerValueExpression(expression, initializerScope);
2521
+ if (field.kind === "binding" && value.kind !== "state") {
2522
+ throw new SyntaxError(`Native initializer ${selected.signature} must bind @Binding field '${fieldName}' to state`);
2523
+ }
2524
+ fieldBindings.set(fieldName, value);
2525
+ }
2526
+ for (const field of declaration.fields) {
2527
+ if (field.kind === "state" || fieldBindings.has(field.name))
2528
+ continue;
2529
+ const parameterValue = parameterBindings.get(field.name);
2530
+ if (parameterValue) {
2531
+ fieldBindings.set(field.name, parameterValue);
2532
+ continue;
2533
+ }
2534
+ if (field.initializer !== undefined) {
2535
+ const scope = new Map([...parameterBindings, ...fieldBindings]);
2536
+ fieldBindings.set(field.name, lowerValueExpression(field.initializer, scope));
2537
+ continue;
2538
+ }
2539
+ throw new SyntaxError(`Initializer ${selected.signature} did not initialize field '${field.name}'`);
2540
+ }
2541
+ }
2542
+ const instancePath = childIdentityPath(statePath, "component", qualifiedName);
2543
+ // Everything below depends only on these inputs, the lowerer state the
2544
+ // cache key digests, and the declarations recorded as dependencies.
2545
+ const inputs = this.#cache
2546
+ ? JSON.stringify([identityPathKey(path), instancePath ? identityPathKey(instancePath) : null, [...fieldBindings]], cacheKeyValue)
2547
+ : "";
2548
+ return this.#lowerInstance(qualifiedName, declaration, inputs, () => {
2549
+ this.bindLocalStates(declaration, fieldBindings, instancePath);
2550
+ this.#componentStack.push(qualifiedName);
2551
+ try {
2552
+ return this.lowerBody(declaration, fieldBindings, [...path, "component", qualifiedName, "body"], childIdentityPath(instancePath, "body"));
2553
+ }
2554
+ finally {
2555
+ this.#componentStack.pop();
2556
+ }
2557
+ });
2558
+ }
2559
+ lowerCall(call, bindings, path, statePath) {
2560
+ const component = this.resolveComponent(call.callee);
2561
+ if (component) {
2562
+ return [this.lowerComponent(call, component.declaration, component.semanticView, bindings, path, statePath)];
2563
+ }
2564
+ const supplied = call.arguments.map(argument => componentSemanticArgument(argument, bindings, this.#stateTypes));
2565
+ if (call.trailing)
2566
+ supplied.push({ type: "function", trailing: true, trailingClosure: call.trailing });
2567
+ if (call.callee === "Color")
2568
+ return [colorView(this, rawCallSource(call), path)];
2569
+ if (call.callee === "Window") {
2570
+ const resolution = resolveContractCall(windowSymbols, supplied, { kind: "view", owner: "Window" });
2571
+ const context = { lowerer: this, call, args: resolution.arguments, bindings, path, statePath };
2572
+ const title = staticTitle(argumentSource(context, "title"), bindings, "Window title");
2573
+ const children = stackChildren(context);
2574
+ if (children.length !== 1)
2575
+ throw new SyntaxError("Window requires exactly one root content view");
2576
+ return [{
2577
+ kind: "window",
2578
+ id: this.id("window", path),
2579
+ title,
2580
+ layout: {
2581
+ width: lowerValueExpression(argumentSource(context, "width") ?? "640", bindings),
2582
+ height: lowerValueExpression(argumentSource(context, "height") ?? "420", bindings),
2583
+ },
2584
+ accessibility: { role: "window", label: title },
2585
+ child: children[0],
2586
+ }];
2587
+ }
2588
+ const symbols = nativeViewInitializerSymbols(call.callee);
2589
+ if (symbols) {
2590
+ const resolution = resolveContractCall(symbols, supplied, {
2591
+ kind: "view",
2592
+ owner: call.callee,
2593
+ unsupported: swiftUIUnsupportedInitializerSignatures(call.callee),
2594
+ });
2595
+ const implementation = nativeViews[`${call.callee}.${resolution.signature}`];
2596
+ if (!implementation)
2597
+ throw new SyntaxError(`Internal error: no native implementation for ${call.callee}.${resolution.signature}`);
2598
+ return implementation({ lowerer: this, call, args: resolution.arguments, bindings, path, statePath });
2599
+ }
2600
+ throw new SyntaxError(unsupportedView(call.callee)
2601
+ ?? `View '${call.callee}' is neither a SwiftUI View implemented by Mün nor a View declared in this file`);
2602
+ }
2603
+ }
2604
+ /** `Color.red`, `Color(red: …)`, `Color.red.opacity(0.5)` used as a View, followed by View modifiers. */
2605
+ function colorViewChain(source) {
2606
+ const text = source.trim();
2607
+ if (!/^Color\b/.test(text))
2608
+ return undefined;
2609
+ const chain = parseMemberChain(text);
2610
+ if (!chain)
2611
+ return undefined;
2612
+ // Color members (named colors, opacity) bind to the Color; the rest are View modifiers.
2613
+ let consumed = 0;
2614
+ if (!chain.ownerCall) {
2615
+ if (!chain.members[0] || chain.members[0].arguments)
2616
+ return undefined;
2617
+ consumed = 1;
2618
+ }
2619
+ while (chain.members[consumed]?.name === "opacity" && consumed > 0 && !chain.ownerCall)
2620
+ consumed += 1;
2621
+ const colorLength = colorPrefixLength(text, chain.ownerCall ? 0 : consumed);
2622
+ const colorSource = text.slice(0, colorLength);
2623
+ const rest = text.slice(colorLength);
2624
+ const modifiers = rest.trim() ? splitViewChain(`M()${rest}`).modifiers : [];
2625
+ return { base: { kind: "raw", source: colorSource, range: { start: 0, end: colorLength } }, colorSource, modifiers };
2626
+ }
2627
+ function colorPrefixLength(text, members) {
2628
+ let cursor = "Color".length;
2629
+ if (text[cursor] === "(")
2630
+ cursor = findMatchingParenthesis(text, cursor) + 1;
2631
+ for (let index = 0; index < members; index += 1) {
2632
+ const name = /^\.[A-Za-z_]\w*/.exec(text.slice(cursor));
2633
+ if (!name)
2634
+ break;
2635
+ cursor += name[0].length;
2636
+ if (text[cursor] === "(")
2637
+ cursor = findMatchingParenthesis(text, cursor) + 1;
2638
+ }
2639
+ return cursor;
2640
+ }
2641
+ function rawCallSource(call) {
2642
+ return `Color(${call.arguments.map(argument => `${argument.label ? `${argument.label}: ` : ""}${argument.value.kind === "raw" ? argument.value.source.trim() : ""}`).join(", ")})`;
2643
+ }
2644
+ /** A SwiftUI Color used as a View: a rectangle filled with the color that fills its space. */
2645
+ function colorView(lowerer, source, path) {
2646
+ return {
2647
+ kind: "panel",
2648
+ id: lowerer.id("panel", path),
2649
+ shape: "rectangle",
2650
+ layout: flexibleBoth,
2651
+ visual: { foreground: { kind: "solid", color: lowerColor(source) } },
2652
+ };
2653
+ }
2654
+ function stampAction(action, lowerer) {
2655
+ if (action.kind === "collection")
2656
+ return { ...action, keyPath: lowerer.collectionKeyPath(action.state) };
2657
+ if (action.kind === "sequence") {
2658
+ return { ...action, actions: action.actions.map(item => stampAction(item, lowerer)) };
2659
+ }
2660
+ return action;
2661
+ }
2662
+ /** Give every collection mutation the key path of the ForEach rendering it. */
2663
+ function withCollectionKeyPaths(node, lowerer) {
2664
+ const visit = (current) => {
2665
+ switch (current.kind) {
2666
+ case "action":
2667
+ return { ...current, action: stampAction(current.action, lowerer) };
2668
+ case "window":
2669
+ return { ...current, child: visit(current.child) };
2670
+ case "conditional":
2671
+ return { ...current, then: current.then.map(visit), otherwise: current.otherwise.map(visit) };
2672
+ case "column":
2673
+ case "row":
2674
+ case "overlay":
2675
+ case "scroll":
2676
+ case "forEach":
2677
+ return { ...current, children: current.children.map(visit) };
2678
+ default:
2679
+ return current;
2680
+ }
2681
+ };
2682
+ return visit(node);
2683
+ }
2684
+ /**
2685
+ * Lower canonical Mün source into renderer-independent semantic UI IR.
2686
+ *
2687
+ * This pass intentionally runs from Mün's parsed builder/struct representation,
2688
+ * before the legacy web compiler materializes div/span/style templates.
2689
+ */
2690
+ export function compileMunUiProgram(source, fileName = "mun-source.mun", options = {}) {
2691
+ return lowerMunUiProgram(source, fileName, options).program;
2692
+ }
2693
+ function countStructDeclarations(structs) {
2694
+ return structs.reduce((count, declaration) => count + 1 + countStructDeclarations(declaration.nested ?? []), 0);
2695
+ }
2696
+ function devCompileResult(program, lowerer, declarationsChecked, lowering) {
2697
+ const types = lowerer.declaredStateTypes();
2698
+ return {
2699
+ program,
2700
+ metadata: {
2701
+ states: program.states.map(state => ({
2702
+ name: state.name,
2703
+ type: types.get(state.name) ?? (state.initial === null ? "nil" : typeof state.initial),
2704
+ ...(state.scope ? { scope: state.scope } : {}),
2705
+ })),
2706
+ nodes: lowerer.sourceSpans(),
2707
+ },
2708
+ stats: {
2709
+ declarationsChecked,
2710
+ viewDeclarationsLowered: lowerer.loweredViewDeclarations().size,
2711
+ ...(lowering ? { lowering } : {}),
2712
+ },
2713
+ };
2714
+ }
2715
+ export function compileMunDevProgram(source, fileName = "mun-source.mun", options = {}) {
2716
+ const structs = parseMunStructs(source);
2717
+ const { program, lowerer, declarationsChecked, lowering } = lowerMunUiProgram(source, fileName, options, structs);
2718
+ return devCompileResult(program, lowerer, declarationsChecked, lowering);
2719
+ }
2720
+ /**
2721
+ * Development compile using an already-parsed struct forest. Project tooling
2722
+ * uses this to keep unchanged source files out of the struct-parser hot path.
2723
+ * Ranges in the provided structs must refer to offsets in source.
2724
+ */
2725
+ export function compileMunDevProgramFromStructs(source, structs, fileName = "mun-source.mun", options = {}) {
2726
+ const { program, lowerer, declarationsChecked, lowering } = lowerMunUiProgram(source, fileName, options, structs);
2727
+ return devCompileResult(program, lowerer, declarationsChecked, lowering);
2728
+ }
2729
+ /**
2730
+ * Declaration texts that passed canonical validation. Validation of a
2731
+ * declaration depends only on its own text (offsets matter only for errors,
2732
+ * and failures are never cached), so unchanged declarations are not rechecked.
2733
+ */
2734
+ const validatedDeclarations = new Set();
2735
+ /** Validate declarations not already proven valid; returns how many were checked. */
2736
+ function validateChangedDeclarations(structs) {
2737
+ let checked = 0;
2738
+ for (const declaration of structs) {
2739
+ if (validatedDeclarations.has(declaration.source))
2740
+ continue;
2741
+ validateCanonicalDeclarations([declaration]);
2742
+ checked += countStructDeclarations([declaration]);
2743
+ if (validatedDeclarations.size >= parsedExpressionLimit)
2744
+ validatedDeclarations.clear();
2745
+ validatedDeclarations.add(declaration.source);
2746
+ }
2747
+ return checked;
2748
+ }
2749
+ function lowerMunUiProgram(source, fileName, options, preparedStructs) {
2750
+ assertCanonicalMunSource(source, fileName);
2751
+ const structs = preparedStructs ?? parseMunStructs(source);
2752
+ if (structs.length === 0)
2753
+ throw new SyntaxError("Native Mün requires a View struct entry point");
2754
+ // Canonical declaration rules (Swift type spellings, access levels). The
2755
+ // legacy compatibility pipelines keep accepting TypeScript spellings.
2756
+ const declarationsChecked = validateChangedDeclarations(structs);
2757
+ const requestedEntry = entryName(source, structs[0].name);
2758
+ const entry = structs.find(structure => structure.name === requestedEntry) ?? structs[0];
2759
+ const states = stateDeclarations(source);
2760
+ const cache = options.loweringCache;
2761
+ cache?.begin();
2762
+ const lowerer = new UiLowerer(structs, states, cache);
2763
+ const lowered = withCollectionKeyPaths(lowerer.lowerEntry(entry), lowerer);
2764
+ const title = options.windowTitle ?? "Mün";
2765
+ const root = lowered.kind === "window"
2766
+ ? lowered
2767
+ : {
2768
+ kind: "window",
2769
+ id: "window-root",
2770
+ title,
2771
+ layout: {
2772
+ width: literal(options.windowWidth ?? 640),
2773
+ height: literal(options.windowHeight ?? 420),
2774
+ },
2775
+ accessibility: { role: "window", label: title },
2776
+ child: lowered,
2777
+ };
2778
+ return {
2779
+ program: {
2780
+ version: 1,
2781
+ sourceLanguage: "mun",
2782
+ entry: entry.name,
2783
+ states: lowerer.states(),
2784
+ root,
2785
+ },
2786
+ lowerer,
2787
+ declarationsChecked,
2788
+ // Committed only after the whole program lowered: a failed compile keeps
2789
+ // the previous entries for reuse once the error is fixed.
2790
+ ...(cache ? { lowering: cache.commit(lowerer.dependencyGraph()) } : {}),
2791
+ };
2792
+ }
2793
+ //# sourceMappingURL=ui-ir.js.map