@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.
- package/LICENSE +21 -0
- package/dist/analysis.d.ts +11 -0
- package/dist/analysis.d.ts.map +1 -0
- package/dist/analysis.js +80 -0
- package/dist/analysis.js.map +1 -0
- package/dist/ast.d.ts +121 -0
- package/dist/ast.d.ts.map +1 -0
- package/dist/ast.js +1022 -0
- package/dist/ast.js.map +1 -0
- package/dist/builtins.d.ts +47 -0
- package/dist/builtins.d.ts.map +1 -0
- package/dist/builtins.js +259 -0
- package/dist/builtins.js.map +1 -0
- package/dist/collection-specialization.d.ts +2 -0
- package/dist/collection-specialization.d.ts.map +1 -0
- package/dist/collection-specialization.js +475 -0
- package/dist/collection-specialization.js.map +1 -0
- package/dist/diagnostics.d.ts +12 -0
- package/dist/diagnostics.d.ts.map +1 -0
- package/dist/diagnostics.js +182 -0
- package/dist/diagnostics.js.map +1 -0
- package/dist/effect-analysis.d.ts +54 -0
- package/dist/effect-analysis.d.ts.map +1 -0
- package/dist/effect-analysis.js +318 -0
- package/dist/effect-analysis.js.map +1 -0
- package/dist/execution-plan.d.ts +63 -0
- package/dist/execution-plan.d.ts.map +1 -0
- package/dist/execution-plan.js +223 -0
- package/dist/execution-plan.js.map +1 -0
- package/dist/gpu-island-ir.d.ts +85 -0
- package/dist/gpu-island-ir.d.ts.map +1 -0
- package/dist/gpu-island-ir.js +159 -0
- package/dist/gpu-island-ir.js.map +1 -0
- package/dist/gpu-region.d.ts +28 -0
- package/dist/gpu-region.d.ts.map +1 -0
- package/dist/gpu-region.js +136 -0
- package/dist/gpu-region.js.map +1 -0
- package/dist/index.d.ts +29 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +56 -0
- package/dist/index.js.map +1 -0
- package/dist/kernel-ir.d.ts +13 -0
- package/dist/kernel-ir.d.ts.map +1 -0
- package/dist/kernel-ir.js +221 -0
- package/dist/kernel-ir.js.map +1 -0
- package/dist/language-catalog.d.ts +26 -0
- package/dist/language-catalog.d.ts.map +1 -0
- package/dist/language-catalog.js +27 -0
- package/dist/language-catalog.js.map +1 -0
- package/dist/lifecycle.d.ts +15 -0
- package/dist/lifecycle.d.ts.map +1 -0
- package/dist/lifecycle.js +122 -0
- package/dist/lifecycle.js.map +1 -0
- package/dist/native-contract.d.ts +27 -0
- package/dist/native-contract.d.ts.map +1 -0
- package/dist/native-contract.js +163 -0
- package/dist/native-contract.js.map +1 -0
- package/dist/native-member-contract.d.ts +13 -0
- package/dist/native-member-contract.d.ts.map +1 -0
- package/dist/native-member-contract.js +10 -0
- package/dist/native-member-contract.js.map +1 -0
- package/dist/native-values.d.ts +43 -0
- package/dist/native-values.d.ts.map +1 -0
- package/dist/native-values.js +450 -0
- package/dist/native-values.js.map +1 -0
- package/dist/observable.d.ts +19 -0
- package/dist/observable.d.ts.map +1 -0
- package/dist/observable.js +203 -0
- package/dist/observable.js.map +1 -0
- package/dist/pipeline.d.ts +11 -0
- package/dist/pipeline.d.ts.map +1 -0
- package/dist/pipeline.js +2290 -0
- package/dist/pipeline.js.map +1 -0
- package/dist/resident-fusion.d.ts +102 -0
- package/dist/resident-fusion.d.ts.map +1 -0
- package/dist/resident-fusion.js +423 -0
- package/dist/resident-fusion.js.map +1 -0
- package/dist/resident-js.d.ts +7 -0
- package/dist/resident-js.d.ts.map +1 -0
- package/dist/resident-js.js +106 -0
- package/dist/resident-js.js.map +1 -0
- package/dist/resident-planner.d.ts +58 -0
- package/dist/resident-planner.d.ts.map +1 -0
- package/dist/resident-planner.js +101 -0
- package/dist/resident-planner.js.map +1 -0
- package/dist/resident-wasm.d.ts +56 -0
- package/dist/resident-wasm.d.ts.map +1 -0
- package/dist/resident-wasm.js +867 -0
- package/dist/resident-wasm.js.map +1 -0
- package/dist/scanner.d.ts +63 -0
- package/dist/scanner.d.ts.map +1 -0
- package/dist/scanner.js +760 -0
- package/dist/scanner.js.map +1 -0
- package/dist/semantic.d.ts +100 -0
- package/dist/semantic.d.ts.map +1 -0
- package/dist/semantic.js +669 -0
- package/dist/semantic.js.map +1 -0
- package/dist/shorthand.d.ts +16 -0
- package/dist/shorthand.d.ts.map +1 -0
- package/dist/shorthand.js +324 -0
- package/dist/shorthand.js.map +1 -0
- package/dist/source-map.d.ts +26 -0
- package/dist/source-map.d.ts.map +1 -0
- package/dist/source-map.js +228 -0
- package/dist/source-map.js.map +1 -0
- package/dist/specialization.d.ts +34 -0
- package/dist/specialization.d.ts.map +1 -0
- package/dist/specialization.js +1996 -0
- package/dist/specialization.js.map +1 -0
- package/dist/state-specialization.d.ts +3 -0
- package/dist/state-specialization.d.ts.map +1 -0
- package/dist/state-specialization.js +227 -0
- package/dist/state-specialization.js.map +1 -0
- package/dist/struct-state.d.ts +39 -0
- package/dist/struct-state.d.ts.map +1 -0
- package/dist/struct-state.js +225 -0
- package/dist/struct-state.js.map +1 -0
- package/dist/types.d.ts +70 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/types.js +2 -0
- package/dist/types.js.map +1 -0
- package/dist/ui-ir.d.ts +151 -0
- package/dist/ui-ir.d.ts.map +1 -0
- package/dist/ui-ir.js +2793 -0
- package/dist/ui-ir.js.map +1 -0
- package/dist/value-types.d.ts +74 -0
- package/dist/value-types.d.ts.map +1 -0
- package/dist/value-types.js +246 -0
- package/dist/value-types.js.map +1 -0
- package/dist/vite.d.ts +33 -0
- package/dist/vite.d.ts.map +1 -0
- package/dist/vite.js +233 -0
- package/dist/vite.js.map +1 -0
- package/dist/vue-host.d.ts +25 -0
- package/dist/vue-host.d.ts.map +1 -0
- package/dist/vue-host.js +103 -0
- package/dist/vue-host.js.map +1 -0
- package/dist/web-analysis.d.ts +7 -0
- package/dist/web-analysis.d.ts.map +1 -0
- package/dist/web-analysis.js +81 -0
- package/dist/web-analysis.js.map +1 -0
- package/package.json +29 -3
- package/README.md +0 -3
package/dist/pipeline.js
ADDED
|
@@ -0,0 +1,2290 @@
|
|
|
1
|
+
import * as ts from "typescript";
|
|
2
|
+
import { parseMunBuilder, parseMunStructs, lowerMunBuilderAst } from "./ast.js";
|
|
3
|
+
import { findBuilder, findRawHtml, identifierAt, matching, previousSignificantCharacter, previousWord, regexCanStart, rawHtmlAt, skipComment, skipRegex, skipString, skipTrivia, splitStatements, splitTopLevel, syntaxError, topLevelColon, } from "./scanner.js";
|
|
4
|
+
import * as Core from "@mun-ui/core/compat";
|
|
5
|
+
import { resolveSemanticCall, swiftUIModifierLowering } from "@mun-ui/core/compat";
|
|
6
|
+
import { lowerImplicitMemberShorthand, lowerNamedAnimationFactoryCalls, lowerShorthand } from "./shorthand.js";
|
|
7
|
+
import { foldStaticResults, hoistStaticViewSubtrees, lowerCompiledViewTemplates, lowerContentTransitionArgument, lowerStaticSemanticSpecializations, staticModifierNames } from "./specialization.js";
|
|
8
|
+
import { lowerCompiledCollections } from "./collection-specialization.js";
|
|
9
|
+
import { lowerStateArrayMaps } from "./state-specialization.js";
|
|
10
|
+
import { lowerBoolToggle, lowerCollectionMembers, lowerStructStateAccess, lowerSwiftInterpolation } from "./struct-state.js";
|
|
11
|
+
import { lowerLabeledCalls, lowerObservableClasses, lowerParameters, lowerSwiftKeyPaths } from "./observable.js";
|
|
12
|
+
import { lowerBareClosureCalls, lowerLifecycleModifiers } from "./lifecycle.js";
|
|
13
|
+
import { validateWebBindings, validateWebLowering } from "./web-analysis.js";
|
|
14
|
+
import { canonicalViewSymbols } from "./semantic.js";
|
|
15
|
+
import { addNamedImports, munBuiltinSymbols, resolveMunBuiltins } from "./builtins.js";
|
|
16
|
+
import { createMunSourceMap, mapGeneratedPosition } from "./source-map.js";
|
|
17
|
+
// Nested named calls are uncommon in ordinary argument expressions. Keep the
|
|
18
|
+
// recursive lowering path behind a cheap lexical hint so every positional
|
|
19
|
+
// argument does not rescan itself with the full balanced-call scanner.
|
|
20
|
+
const nestedNamedMunCallHint = /\b(?:[A-Z][A-Za-z0-9_$]*\.)*[A-Z][A-Za-z0-9_$]*\s*\([^()\n]*:[^()\n]*\)/;
|
|
21
|
+
const validationSourceFileCache = new Map();
|
|
22
|
+
const maximumValidationSourceFiles = 32;
|
|
23
|
+
function validationSourceFile(source) {
|
|
24
|
+
const cached = validationSourceFileCache.get(source);
|
|
25
|
+
if (cached) {
|
|
26
|
+
validationSourceFileCache.delete(source);
|
|
27
|
+
validationSourceFileCache.set(source, cached);
|
|
28
|
+
return cached;
|
|
29
|
+
}
|
|
30
|
+
const file = ts.createSourceFile("mun-call-validation.ts", source, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS);
|
|
31
|
+
validationSourceFileCache.set(source, file);
|
|
32
|
+
while (validationSourceFileCache.size > maximumValidationSourceFiles) {
|
|
33
|
+
const oldest = validationSourceFileCache.keys().next().value;
|
|
34
|
+
if (oldest === undefined)
|
|
35
|
+
break;
|
|
36
|
+
validationSourceFileCache.delete(oldest);
|
|
37
|
+
}
|
|
38
|
+
return file;
|
|
39
|
+
}
|
|
40
|
+
/**
|
|
41
|
+
* Compiler-facing view metadata starts with every runtime View so Mun-native
|
|
42
|
+
* and compatibility APIs remain usable. Canonical SwiftUI Views are then
|
|
43
|
+
* replaced by the SDK-audited manifest contract, preventing runtime-only
|
|
44
|
+
* overloads from silently becoming SwiftUI source syntax.
|
|
45
|
+
*/
|
|
46
|
+
const canonicalInitializerSymbols = new Map();
|
|
47
|
+
for (const symbol of munBuiltinSymbols().values()) {
|
|
48
|
+
if (symbol.kind === "view" && symbol.initializers)
|
|
49
|
+
canonicalInitializerSymbols.set(symbol.name, symbol.initializers);
|
|
50
|
+
}
|
|
51
|
+
// Native-only canonical Views keep their contract for call validation; the
|
|
52
|
+
// built-in registry reports them as unavailable on the web.
|
|
53
|
+
for (const [name, symbol] of canonicalViewSymbols()) {
|
|
54
|
+
if (!canonicalInitializerSymbols.has(name))
|
|
55
|
+
canonicalInitializerSymbols.set(name, symbol.initializers);
|
|
56
|
+
}
|
|
57
|
+
function symbolsForCall(call, registry = canonicalInitializerSymbols) {
|
|
58
|
+
return registry.get(call.callee);
|
|
59
|
+
}
|
|
60
|
+
class MunInitializerSyntaxError extends SyntaxError {
|
|
61
|
+
code = "MUN_INITIALIZER";
|
|
62
|
+
offset;
|
|
63
|
+
constructor(message, offset) {
|
|
64
|
+
super(message);
|
|
65
|
+
this.name = "MunInitializerSyntaxError";
|
|
66
|
+
this.offset = offset;
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
function buttonInitializerMessage(call) {
|
|
70
|
+
const labels = call.arguments.flatMap(argument => argument.label ? [argument.label] : []);
|
|
71
|
+
if (labels.includes("role")) {
|
|
72
|
+
return "Button(role:) is not supported: Mün has no button roles. Style a destructive Button with .foregroundStyle(.red) instead.";
|
|
73
|
+
}
|
|
74
|
+
if (labels.includes("label") && labels.includes("action") && labels.indexOf("label") < labels.indexOf("action")) {
|
|
75
|
+
return "Button arguments must follow declaration order: action:, label:.";
|
|
76
|
+
}
|
|
77
|
+
return "Button must use either Button(\"Title\") { action } or Button(action: { ... }) { label }.";
|
|
78
|
+
}
|
|
79
|
+
function knownCallArguments(call) {
|
|
80
|
+
const arguments_ = call.arguments.flatMap((argument, argumentIndex) => {
|
|
81
|
+
if (argument.value.kind === "closure")
|
|
82
|
+
return [{ label: argument.label, type: "function" }];
|
|
83
|
+
if (call.callee === "ForEach" && argumentIndex === 1 && /^\{\s*(?:id|key)\s*:/.test(argument.value.source) && /=>/.test(argument.value.source)) {
|
|
84
|
+
return [{ label: "key", type: "function" }];
|
|
85
|
+
}
|
|
86
|
+
const named = /^namedArguments\s*\(\s*\{([\s\S]*)\}\s*\)$/.exec(argument.value.source.trim());
|
|
87
|
+
if (named)
|
|
88
|
+
return splitTopLevel(named[1]).map(value => compilerSemanticArgument(value));
|
|
89
|
+
return [compilerSemanticArgument(argument.label ? `${argument.label}: ${argument.value.source}` : argument.value.source)];
|
|
90
|
+
});
|
|
91
|
+
return call.trailing ? [...arguments_, { type: "function", trailing: true }] : arguments_;
|
|
92
|
+
}
|
|
93
|
+
function canDeferDynamicButton(call, arguments_) {
|
|
94
|
+
if (!arguments_.some(argument => argument.type === "unknown"))
|
|
95
|
+
return false;
|
|
96
|
+
if (call.trailing)
|
|
97
|
+
return call.arguments.length === 1 && (!call.arguments[0]?.label || call.arguments[0]?.label === "action");
|
|
98
|
+
const labels = call.arguments.map(argument => argument.label);
|
|
99
|
+
return labels.length === 2 && labels[0] === "action" && labels[1] === "label";
|
|
100
|
+
}
|
|
101
|
+
function resolveKnownCall(call, registry = canonicalInitializerSymbols) {
|
|
102
|
+
const symbols = symbolsForCall(call, registry);
|
|
103
|
+
if (!symbols)
|
|
104
|
+
return undefined;
|
|
105
|
+
const viewType = {
|
|
106
|
+
kind: "view",
|
|
107
|
+
name: call.callee,
|
|
108
|
+
qualifiedName: call.callee,
|
|
109
|
+
initializers: symbols,
|
|
110
|
+
fields: [],
|
|
111
|
+
};
|
|
112
|
+
const arguments_ = knownCallArguments(call);
|
|
113
|
+
const result = resolveSemanticCall(viewType, arguments_);
|
|
114
|
+
if (!result.resolvedInitializer) {
|
|
115
|
+
if (call.callee === "Button" && canDeferDynamicButton(call, arguments_))
|
|
116
|
+
return undefined;
|
|
117
|
+
if (call.callee === "Button")
|
|
118
|
+
throw new MunInitializerSyntaxError(buttonInitializerMessage(call), call.range.start);
|
|
119
|
+
if (call.trailing && canonicalInitializerSymbols.get(call.callee) !== symbols) {
|
|
120
|
+
throw new MunInitializerSyntaxError(result.diagnostics[0]?.message ?? `No matching initializer for ${call.callee}.`, call.range.start);
|
|
121
|
+
}
|
|
122
|
+
return undefined;
|
|
123
|
+
}
|
|
124
|
+
return { symbols, initializerIndex: result.resolvedInitializer.index, resolution: result };
|
|
125
|
+
}
|
|
126
|
+
/**
|
|
127
|
+
* SwiftUI spellings that compile as labeled arguments but cannot be realised on
|
|
128
|
+
* the web: SF Symbols are Apple-licensed artwork Mün does not ship. Reject them
|
|
129
|
+
* here with a clear diagnostic instead of failing when the View is created.
|
|
130
|
+
*/
|
|
131
|
+
const webUnavailableLabels = {
|
|
132
|
+
Image: { systemName: "Image(systemName:) is not supported: SF Symbols are not available on the web. Use Image(\"url\") or a vector symbol." },
|
|
133
|
+
Label: { systemImage: "Label(_:systemImage:) is not supported: SF Symbols are not available on the web. Use Label(title, icon) with an Image or vector symbol." },
|
|
134
|
+
};
|
|
135
|
+
function rejectWebUnavailable(call) {
|
|
136
|
+
const rejected = webUnavailableLabels[call.callee];
|
|
137
|
+
if (!rejected)
|
|
138
|
+
return;
|
|
139
|
+
for (const argument of call.arguments) {
|
|
140
|
+
const message = argument.label ? rejected[argument.label] : undefined;
|
|
141
|
+
if (message)
|
|
142
|
+
throw new MunInitializerSyntaxError(message, call.range.start);
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
function validateKnownCalls(program, registry = canonicalInitializerSymbols) {
|
|
146
|
+
const visit = (node) => {
|
|
147
|
+
if (node.kind === "call") {
|
|
148
|
+
rejectWebUnavailable(node);
|
|
149
|
+
if (node.callee === "Button" || node.trailing)
|
|
150
|
+
resolveKnownCall(node, registry);
|
|
151
|
+
for (const argument of node.arguments)
|
|
152
|
+
if (argument.value.kind === "closure")
|
|
153
|
+
validateKnownCalls(argument.value.body, registry);
|
|
154
|
+
if (node.trailing)
|
|
155
|
+
validateKnownCalls(node.trailing.body, registry);
|
|
156
|
+
return;
|
|
157
|
+
}
|
|
158
|
+
if (node.kind === "conditional") {
|
|
159
|
+
validateKnownCalls(node.then, registry);
|
|
160
|
+
if (node.otherwise) {
|
|
161
|
+
if (node.otherwise.kind === "conditional")
|
|
162
|
+
validateKnownCalls({ ...node.then, statements: [node.otherwise] }, registry);
|
|
163
|
+
else
|
|
164
|
+
validateKnownCalls(node.otherwise, registry);
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
};
|
|
168
|
+
for (const node of program.statements)
|
|
169
|
+
visit(node);
|
|
170
|
+
}
|
|
171
|
+
function validateKnownTypeScriptCalls(source, registry = canonicalInitializerSymbols, parsedSource) {
|
|
172
|
+
// SwiftUI-style labels/trailing closures are scanner-owned. Plain positional
|
|
173
|
+
// JS/TS calls deliberately remain the compatibility surface; only Button's
|
|
174
|
+
// constrained positional form needs this AST-side validation.
|
|
175
|
+
if (!/\bButton\s*\(/.test(source))
|
|
176
|
+
return;
|
|
177
|
+
const file = parsedSource ?? validationSourceFile(source);
|
|
178
|
+
const visit = (node) => {
|
|
179
|
+
if (ts.isCallExpression(node) && ts.isIdentifier(node.expression) && node.expression.text === "Button" && registry.has("Button")) {
|
|
180
|
+
// The Mun scanner owns trailing closures. TypeScript sees the call
|
|
181
|
+
// prefix as a complete call, so leave that shape to validateKnownCalls.
|
|
182
|
+
const callText = source.slice(node.expression.end, node.end);
|
|
183
|
+
const hasMunLabels = /(?:^|,)\s*[A-Za-z_$][A-Za-z0-9_$]*\s*:/.test(callText);
|
|
184
|
+
if (!hasMunLabels && source[skipTrivia(source, node.end)] !== "{") {
|
|
185
|
+
const callSource = `Button(${node.arguments.map(argument => argument.getText(file)).join(", ")})`;
|
|
186
|
+
const parsed = parseMunBuilder(callSource, node.expression.getStart(file)).statements[0];
|
|
187
|
+
if (parsed?.kind === "call")
|
|
188
|
+
resolveKnownCall(parsed, registry);
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
ts.forEachChild(node, visit);
|
|
192
|
+
};
|
|
193
|
+
visit(file);
|
|
194
|
+
}
|
|
195
|
+
function closureRoleForKnownCall(call, context, registry = canonicalInitializerSymbols) {
|
|
196
|
+
if ((call.callee === "withAnimation" || call.callee === "withTransaction") && context.position === "trailing")
|
|
197
|
+
return "action";
|
|
198
|
+
// This helper is also called while lowering the argument list of a call
|
|
199
|
+
// whose trailing closure has already been split off by the scanner. Such a
|
|
200
|
+
// synthetic prefix can be incomplete (notably Button(action:) before its
|
|
201
|
+
// trailing label), so role inference must fall back to manifest metadata
|
|
202
|
+
// rather than re-diagnosing the partial call.
|
|
203
|
+
let resolved;
|
|
204
|
+
try {
|
|
205
|
+
resolved = resolveKnownCall(call, registry);
|
|
206
|
+
}
|
|
207
|
+
catch (error) {
|
|
208
|
+
if (!(error instanceof MunInitializerSyntaxError))
|
|
209
|
+
throw error;
|
|
210
|
+
resolved = undefined;
|
|
211
|
+
}
|
|
212
|
+
const resolvedArgumentIndex = context.position === "trailing"
|
|
213
|
+
? Math.max(0, knownCallArguments(call).length - 1)
|
|
214
|
+
: context.label
|
|
215
|
+
? call.arguments.findIndex(argument => argument.label === context.label)
|
|
216
|
+
: context.argumentIndex ?? 0;
|
|
217
|
+
const sharedRole = resolved?.resolution.closureRoles[resolvedArgumentIndex];
|
|
218
|
+
if (sharedRole)
|
|
219
|
+
return sharedRole === "binding" ? undefined : sharedRole;
|
|
220
|
+
const symbols = resolved?.symbols ?? symbolsForCall(call, registry) ?? [];
|
|
221
|
+
const parameters = resolved?.symbols[resolved.initializerIndex]?.parameters
|
|
222
|
+
?? (context.position === "trailing"
|
|
223
|
+
? symbols.find(symbol => symbol.parameters.at(-1)?.trailing)?.parameters
|
|
224
|
+
: context.label
|
|
225
|
+
? symbols.find(symbol => symbol.parameters.some(parameter => parameter.label === context.label))?.parameters
|
|
226
|
+
: undefined)
|
|
227
|
+
?? [];
|
|
228
|
+
const role = (kind) => kind === "binding" ? undefined : kind;
|
|
229
|
+
if (context.position === "trailing")
|
|
230
|
+
return role(parameters.at(-1)?.kind);
|
|
231
|
+
if (context.label)
|
|
232
|
+
return role(parameters.find(parameter => parameter.label === context.label)?.kind);
|
|
233
|
+
const index = context.argumentIndex ?? 0;
|
|
234
|
+
let positional = 0;
|
|
235
|
+
for (const argument of call.arguments.slice(0, index))
|
|
236
|
+
if (!argument.label)
|
|
237
|
+
positional += 1;
|
|
238
|
+
return role(parameters[positional]?.kind);
|
|
239
|
+
}
|
|
240
|
+
/** Classify this closure, not actions/helpers nested inside its View content. */
|
|
241
|
+
function closureEffects(source) {
|
|
242
|
+
// The caller supplies lowered TypeScript, so nested Mun actions are ordinary
|
|
243
|
+
// function nodes and TypeScript owns the lexical function boundaries.
|
|
244
|
+
if (!/\b(?:await|const|let|var|return|throw)\b/.test(source))
|
|
245
|
+
return { asynchronous: false, statements: false };
|
|
246
|
+
const file = ts.createSourceFile("mun-closure.ts", source, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS);
|
|
247
|
+
let asynchronous = false;
|
|
248
|
+
let statements = false;
|
|
249
|
+
const visit = (node) => {
|
|
250
|
+
if (ts.isFunctionLike(node) || ts.isClassLike(node))
|
|
251
|
+
return;
|
|
252
|
+
if (ts.isAwaitExpression(node) || (ts.isForOfStatement(node) && node.awaitModifier))
|
|
253
|
+
asynchronous = true;
|
|
254
|
+
if (ts.isVariableStatement(node) || ts.isReturnStatement(node) || ts.isThrowStatement(node))
|
|
255
|
+
statements = true;
|
|
256
|
+
ts.forEachChild(node, visit);
|
|
257
|
+
};
|
|
258
|
+
visit(file);
|
|
259
|
+
return { asynchronous, statements };
|
|
260
|
+
}
|
|
261
|
+
function isViewBuilderExpression(expression) {
|
|
262
|
+
if (ts.isParenthesizedExpression(expression)
|
|
263
|
+
|| ts.isAsExpression(expression)
|
|
264
|
+
|| ts.isTypeAssertionExpression(expression)
|
|
265
|
+
|| ts.isNonNullExpression(expression)
|
|
266
|
+
|| ts.isSatisfiesExpression(expression)
|
|
267
|
+
|| ts.isAwaitExpression(expression)) {
|
|
268
|
+
return isViewBuilderExpression(expression.expression);
|
|
269
|
+
}
|
|
270
|
+
if (ts.isConditionalExpression(expression)) {
|
|
271
|
+
return isViewBuilderExpression(expression.whenTrue) || isViewBuilderExpression(expression.whenFalse);
|
|
272
|
+
}
|
|
273
|
+
if (ts.isBinaryExpression(expression)) {
|
|
274
|
+
const operator = expression.operatorToken.kind;
|
|
275
|
+
if (operator === ts.SyntaxKind.AmpersandAmpersandToken
|
|
276
|
+
|| operator === ts.SyntaxKind.BarBarToken
|
|
277
|
+
|| operator === ts.SyntaxKind.QuestionQuestionToken) {
|
|
278
|
+
return isViewBuilderExpression(expression.left) || isViewBuilderExpression(expression.right);
|
|
279
|
+
}
|
|
280
|
+
return false;
|
|
281
|
+
}
|
|
282
|
+
if (ts.isArrayLiteralExpression(expression))
|
|
283
|
+
return expression.elements.some(item => ts.isExpression(item) && isViewBuilderExpression(item));
|
|
284
|
+
if (ts.isCallExpression(expression) || ts.isNewExpression(expression))
|
|
285
|
+
return true;
|
|
286
|
+
if (ts.isIdentifier(expression) || ts.isPropertyAccessExpression(expression) || ts.isElementAccessExpression(expression))
|
|
287
|
+
return true;
|
|
288
|
+
return false;
|
|
289
|
+
}
|
|
290
|
+
function lowerViewBuilderAstStatements(source, registry, childrenName) {
|
|
291
|
+
// First lower nested Mun-only expressions (trailing closures, raw HTML,
|
|
292
|
+
// binding shorthand) so the statement tree is valid TypeScript. Then let
|
|
293
|
+
// TypeScript own control-flow parsing instead of maintaining a second,
|
|
294
|
+
// incomplete statement grammar in Mun.
|
|
295
|
+
// Labeled Mun arguments are not valid TypeScript syntax. They must be
|
|
296
|
+
// converted before the TypeScript parser sees statement-bearing builders;
|
|
297
|
+
// otherwise parser recovery rewrites `Foo(value, label: other)` into the
|
|
298
|
+
// semantically different `Foo(value, label, other)` and leaks `label` as an
|
|
299
|
+
// undeclared runtime identifier.
|
|
300
|
+
const lowered = lowerRange(lowerNamedMunCalls(source, registry), registry);
|
|
301
|
+
const wrapper = `function __mun_builder__() {\n${lowered}\n}`;
|
|
302
|
+
const file = ts.createSourceFile("mun-view-builder.ts", wrapper, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS);
|
|
303
|
+
const fn = file.statements.find(ts.isFunctionDeclaration);
|
|
304
|
+
if (!fn?.body)
|
|
305
|
+
return lowered;
|
|
306
|
+
const factory = ts.factory;
|
|
307
|
+
let activeChildrenName = childrenName;
|
|
308
|
+
let conditionalIndex = 0;
|
|
309
|
+
const pushExpression = (expression) => factory.createExpressionStatement(factory.createCallExpression(factory.createPropertyAccessExpression(factory.createIdentifier(activeChildrenName), "push"), undefined, [expression]));
|
|
310
|
+
const transformStatement = (statement) => {
|
|
311
|
+
if (ts.isExpressionStatement(statement)) {
|
|
312
|
+
return isViewBuilderExpression(statement.expression) ? pushExpression(statement.expression) : statement;
|
|
313
|
+
}
|
|
314
|
+
if (ts.isBlock(statement))
|
|
315
|
+
return factory.updateBlock(statement, statement.statements.map(transformStatement));
|
|
316
|
+
if (ts.isIfStatement(statement)) {
|
|
317
|
+
// Keep each conditional in a permanent structural slot. Flattening its
|
|
318
|
+
// children into the parent lets removing one branch renumber its siblings.
|
|
319
|
+
const index = conditionalIndex++;
|
|
320
|
+
let branchName = `${childrenName}Branch${index}`;
|
|
321
|
+
while (new RegExp(`\\b${branchName}\\b`).test(source))
|
|
322
|
+
branchName += "_";
|
|
323
|
+
const parentChildrenName = activeChildrenName;
|
|
324
|
+
activeChildrenName = branchName;
|
|
325
|
+
// SwiftUI gives the `if` and `else` content distinct identities
|
|
326
|
+
// (_ConditionalContent). Record which branch produced the children so
|
|
327
|
+
// switching branches ends one identity (state, onDisappear, removal
|
|
328
|
+
// transition) and starts another instead of patching one into the other.
|
|
329
|
+
const takenName = `${branchName}Taken`;
|
|
330
|
+
const mark = (branch, taken) => factory.createBlock([
|
|
331
|
+
factory.createExpressionStatement(factory.createBinaryExpression(factory.createIdentifier(takenName), ts.SyntaxKind.EqualsToken, factory.createNumericLiteral(taken))),
|
|
332
|
+
branch,
|
|
333
|
+
], true);
|
|
334
|
+
// An `else if` chain is one nested conditional with its own slot, so the
|
|
335
|
+
// outer else branch stays one identity and the nested id tells its arms apart.
|
|
336
|
+
const conditional = factory.updateIfStatement(statement, statement.expression, mark(transformStatement(statement.thenStatement), 1), statement.elseStatement ? mark(transformStatement(statement.elseStatement), 2) : undefined);
|
|
337
|
+
activeChildrenName = parentChildrenName;
|
|
338
|
+
const fragment = factory.createCallExpression(factory.createIdentifier("viewFragment"), undefined, [factory.createIdentifier(branchName)]);
|
|
339
|
+
return factory.createBlock([
|
|
340
|
+
factory.createVariableStatement(undefined, factory.createVariableDeclarationList([
|
|
341
|
+
factory.createVariableDeclaration(branchName, undefined, undefined, factory.createArrayLiteralExpression()),
|
|
342
|
+
], ts.NodeFlags.Const)),
|
|
343
|
+
factory.createVariableStatement(undefined, factory.createVariableDeclarationList([
|
|
344
|
+
factory.createVariableDeclaration(takenName, undefined, undefined, factory.createNumericLiteral(0)),
|
|
345
|
+
], ts.NodeFlags.Let)),
|
|
346
|
+
conditional,
|
|
347
|
+
pushExpression(factory.createCallExpression(factory.createPropertyAccessExpression(fragment, "id"), undefined, [
|
|
348
|
+
factory.createBinaryExpression(factory.createBinaryExpression(factory.createBinaryExpression(factory.createStringLiteral(`mun:conditional:${index}:`), ts.SyntaxKind.PlusToken, factory.createPropertyAccessExpression(factory.createIdentifier(parentChildrenName), "length")), ts.SyntaxKind.PlusToken, factory.createStringLiteral(":")), ts.SyntaxKind.PlusToken, factory.createIdentifier(takenName)),
|
|
349
|
+
])),
|
|
350
|
+
], true);
|
|
351
|
+
}
|
|
352
|
+
if (ts.isForStatement(statement)) {
|
|
353
|
+
return factory.updateForStatement(statement, statement.initializer, statement.condition, statement.incrementor, transformStatement(statement.statement));
|
|
354
|
+
}
|
|
355
|
+
if (ts.isForInStatement(statement)) {
|
|
356
|
+
return factory.updateForInStatement(statement, statement.initializer, statement.expression, transformStatement(statement.statement));
|
|
357
|
+
}
|
|
358
|
+
if (ts.isForOfStatement(statement)) {
|
|
359
|
+
return factory.updateForOfStatement(statement, statement.awaitModifier, statement.initializer, statement.expression, transformStatement(statement.statement));
|
|
360
|
+
}
|
|
361
|
+
if (ts.isWhileStatement(statement))
|
|
362
|
+
return factory.updateWhileStatement(statement, statement.expression, transformStatement(statement.statement));
|
|
363
|
+
if (ts.isDoStatement(statement))
|
|
364
|
+
return factory.updateDoStatement(statement, transformStatement(statement.statement), statement.expression);
|
|
365
|
+
if (ts.isSwitchStatement(statement)) {
|
|
366
|
+
const clauses = statement.caseBlock.clauses.map(clause => ts.isCaseClause(clause)
|
|
367
|
+
? factory.updateCaseClause(clause, clause.expression, clause.statements.map(transformStatement))
|
|
368
|
+
: factory.updateDefaultClause(clause, clause.statements.map(transformStatement)));
|
|
369
|
+
return factory.updateSwitchStatement(statement, statement.expression, factory.updateCaseBlock(statement.caseBlock, clauses));
|
|
370
|
+
}
|
|
371
|
+
if (ts.isTryStatement(statement)) {
|
|
372
|
+
const tryBlock = factory.updateBlock(statement.tryBlock, statement.tryBlock.statements.map(transformStatement));
|
|
373
|
+
const catchClause = statement.catchClause
|
|
374
|
+
? factory.updateCatchClause(statement.catchClause, statement.catchClause.variableDeclaration, factory.updateBlock(statement.catchClause.block, statement.catchClause.block.statements.map(transformStatement)))
|
|
375
|
+
: undefined;
|
|
376
|
+
const finallyBlock = statement.finallyBlock
|
|
377
|
+
? factory.updateBlock(statement.finallyBlock, statement.finallyBlock.statements.map(transformStatement))
|
|
378
|
+
: undefined;
|
|
379
|
+
return factory.updateTryStatement(statement, tryBlock, catchClause, finallyBlock);
|
|
380
|
+
}
|
|
381
|
+
if (ts.isLabeledStatement(statement))
|
|
382
|
+
return factory.updateLabeledStatement(statement, statement.label, transformStatement(statement.statement));
|
|
383
|
+
if (ts.isWithStatement(statement))
|
|
384
|
+
return factory.updateWithStatement(statement, statement.expression, transformStatement(statement.statement));
|
|
385
|
+
// Function/class declarations intentionally remain opaque. A Text() call
|
|
386
|
+
// inside a helper function is not a child of the surrounding ViewBuilder.
|
|
387
|
+
return statement;
|
|
388
|
+
};
|
|
389
|
+
const printer = ts.createPrinter({ newLine: ts.NewLineKind.LineFeed, removeComments: false });
|
|
390
|
+
return fn.body.statements
|
|
391
|
+
.map(transformStatement)
|
|
392
|
+
.map(statement => printer.printNode(ts.EmitHint.Unspecified, statement, file))
|
|
393
|
+
.join("\n");
|
|
394
|
+
}
|
|
395
|
+
function needsStatementAwareViewBody(source) {
|
|
396
|
+
return /\b(?:const|let|var|return|throw|if|else|switch|case|for|while|do|try|catch|finally|break|continue|debugger)\b/.test(source);
|
|
397
|
+
}
|
|
398
|
+
function lowerViewBuilderClosure(body, parameter, registry) {
|
|
399
|
+
if (!needsStatementAwareViewBody(body)) {
|
|
400
|
+
const lowered = lowerMunBuilderAst(parseMunBuilder(body), {
|
|
401
|
+
transformRaw: value => lowerRange(value, registry),
|
|
402
|
+
transformArgument: (value, call, argumentIndex) => lowerForEachIdentityOptions(value, call, argumentIndex, registry),
|
|
403
|
+
closure: (nestedBody, nestedParameter, nestedRole) => lowerAstClosure(nestedBody, nestedParameter, nestedRole, registry),
|
|
404
|
+
closureRole: (nestedCall, context) => closureRoleForKnownCall(nestedCall, context, registry),
|
|
405
|
+
}).join(", ");
|
|
406
|
+
return `${parameter ? `(${parameter})` : "()"} => [${lowered}]`;
|
|
407
|
+
}
|
|
408
|
+
const prefix = parameter ? `(${parameter})` : "()";
|
|
409
|
+
let childrenName = "__munChildren";
|
|
410
|
+
let suffix = 0;
|
|
411
|
+
while (new RegExp(`\\b${childrenName}\\b`).test(body))
|
|
412
|
+
childrenName = `__munChildren${++suffix}`;
|
|
413
|
+
const statements = lowerViewBuilderAstStatements(body, registry, childrenName);
|
|
414
|
+
return `${prefix} => { const ${childrenName} = []; ${statements} return ${childrenName}; }`;
|
|
415
|
+
}
|
|
416
|
+
function lowerClosure(value, role, registry = canonicalInitializerSymbols) {
|
|
417
|
+
const source = value.trim();
|
|
418
|
+
if (!source.startsWith("{") || matching(source, 0, "{", "}") !== source.length - 1)
|
|
419
|
+
return lowerRange(source, registry);
|
|
420
|
+
const inner = source.slice(1, -1).trim();
|
|
421
|
+
const parameterMatch = /^([A-Za-z_$][A-Za-z0-9_$]*)\s+in\s+([\s\S]*)$/.exec(inner);
|
|
422
|
+
const parameter = parameterMatch?.[1];
|
|
423
|
+
const body = parameterMatch?.[2] ?? inner;
|
|
424
|
+
if (role === "viewBuilder")
|
|
425
|
+
return lowerViewBuilderClosure(body, parameter, registry);
|
|
426
|
+
const lowered = lowerStatements(body, registry);
|
|
427
|
+
const actionBody = lowerRange(body, registry);
|
|
428
|
+
const { asynchronous, statements } = closureEffects(actionBody);
|
|
429
|
+
if (role === "action")
|
|
430
|
+
return `${asynchronous ? "async " : ""}(${parameter ?? ""}) => {${actionBody}}`;
|
|
431
|
+
if (parameter)
|
|
432
|
+
return `(${parameter}) => [${lowered}]`;
|
|
433
|
+
const action = asynchronous || statements;
|
|
434
|
+
const builder = action ? "() => []" : `() => [${lowered}]`;
|
|
435
|
+
return `overloadClosure(${builder}, ${asynchronous ? "async " : ""}() => {${actionBody}})`;
|
|
436
|
+
}
|
|
437
|
+
function lowerArguments(source, calleeName, registry = canonicalInitializerSymbols) {
|
|
438
|
+
const parsed = calleeName ? parseMunBuilder(`${calleeName}(${source})`).statements[0] : undefined;
|
|
439
|
+
const call = parsed?.kind === "call" ? parsed : undefined;
|
|
440
|
+
const positional = [];
|
|
441
|
+
const named = [];
|
|
442
|
+
for (const [argumentIndex, argument] of splitTopLevel(source).entries()) {
|
|
443
|
+
const colon = topLevelColon(argument);
|
|
444
|
+
const labelStart = skipTrivia(argument, 0);
|
|
445
|
+
if (colon >= 0 && /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(argument.slice(labelStart, colon).trim())) {
|
|
446
|
+
const label = argument.slice(labelStart, colon).trim();
|
|
447
|
+
const role = call ? closureRoleForKnownCall(call, { position: "argument", argumentIndex, label }, registry) : undefined;
|
|
448
|
+
named.push(`${label}: ${lowerClosureOrExpression(argument.slice(colon + 1), role, registry)}`);
|
|
449
|
+
}
|
|
450
|
+
else {
|
|
451
|
+
const role = call ? closureRoleForKnownCall(call, { position: "argument", argumentIndex }, registry) : undefined;
|
|
452
|
+
positional.push(lowerClosureOrExpression(argument, role, registry));
|
|
453
|
+
}
|
|
454
|
+
}
|
|
455
|
+
if (named.length === 0)
|
|
456
|
+
return positional.join(", ");
|
|
457
|
+
return [...positional, `namedArguments({ ${named.join(", ")} })`].join(", ");
|
|
458
|
+
}
|
|
459
|
+
function lowerClosureOrExpression(source, role, registry = canonicalInitializerSymbols) {
|
|
460
|
+
const value = source.trim();
|
|
461
|
+
if (value.startsWith("{") && matching(value, 0, "{", "}") === value.length - 1 && !/^(?:\s*(?:[A-Za-z_$][A-Za-z0-9_$]*|["'][^"']*["']|-?\d+(?:\.\d+)?)\s*:)/.test(value.slice(1, -1)))
|
|
462
|
+
return lowerClosure(value, role, registry);
|
|
463
|
+
// Named Mun calls can be nested inside an argument expression. Lower them
|
|
464
|
+
// from the already-isolated argument rather than restarting a global scan
|
|
465
|
+
// over the whole module for each inner call.
|
|
466
|
+
const lowered = lowerRange(value, registry);
|
|
467
|
+
return lowerImplicitMemberShorthand(lowerShorthand(nestedNamedMunCallHint.test(lowered) ? lowerNamedMunCalls(lowered, registry) : lowered));
|
|
468
|
+
}
|
|
469
|
+
function lowerForEachIdentityOptions(source, call, argumentIndex, registry) {
|
|
470
|
+
const value = source.trim();
|
|
471
|
+
if (call.callee !== "ForEach" || argumentIndex !== 1 || !value.startsWith("{") || matching(value, 0, "{", "}") !== value.length - 1) {
|
|
472
|
+
return lowerImplicitMemberShorthand(lowerRange(source, registry));
|
|
473
|
+
}
|
|
474
|
+
const entries = splitTopLevel(value.slice(1, -1)).map(entry => {
|
|
475
|
+
const colon = topLevelColon(entry);
|
|
476
|
+
return colon < 0 ? undefined : { name: entry.slice(0, colon).trim(), value: entry.slice(colon + 1).trim() };
|
|
477
|
+
}).filter((entry) => entry !== undefined);
|
|
478
|
+
const identity = entries.find(entry => entry.name === "id" || entry.name === "key");
|
|
479
|
+
if (!identity)
|
|
480
|
+
return lowerRange(source, registry);
|
|
481
|
+
return `namedArguments({ key: ${lowerRange(identity.value, registry)} })`;
|
|
482
|
+
}
|
|
483
|
+
function lowerConditional(source, registry = canonicalInitializerSymbols) {
|
|
484
|
+
const match = /^if\s*\(/.exec(source);
|
|
485
|
+
if (!match)
|
|
486
|
+
return undefined;
|
|
487
|
+
const open = source.indexOf("(", match.index + match[0].length - 1);
|
|
488
|
+
const close = matching(source, open, "(", ")");
|
|
489
|
+
const thenOpen = skipTrivia(source, close + 1);
|
|
490
|
+
if (source[thenOpen] !== "{")
|
|
491
|
+
return undefined;
|
|
492
|
+
const thenClose = matching(source, thenOpen, "{", "}");
|
|
493
|
+
const afterThen = skipTrivia(source, thenClose + 1);
|
|
494
|
+
const condition = source.slice(open + 1, close).trim();
|
|
495
|
+
const thenValue = `[${lowerStatements(source.slice(thenOpen + 1, thenClose), registry)}]`;
|
|
496
|
+
if (source.slice(afterThen, afterThen + 4) !== "else"
|
|
497
|
+
|| /[A-Za-z0-9_$]/.test(source[afterThen + 4] ?? "")) {
|
|
498
|
+
return afterThen === source.length ? `(${lowerShorthand(condition)} ? ${thenValue} : [])` : undefined;
|
|
499
|
+
}
|
|
500
|
+
const elseOpen = skipTrivia(source, afterThen + 4);
|
|
501
|
+
if (source[elseOpen] !== "{")
|
|
502
|
+
return undefined;
|
|
503
|
+
const elseClose = matching(source, elseOpen, "{", "}");
|
|
504
|
+
if (skipTrivia(source, elseClose + 1) !== source.length)
|
|
505
|
+
return undefined;
|
|
506
|
+
return `(${lowerShorthand(condition)} ? ${thenValue} : [${lowerStatements(source.slice(elseOpen + 1, elseClose), registry)}])`;
|
|
507
|
+
}
|
|
508
|
+
function lowerStatements(source, registry = canonicalInitializerSymbols) {
|
|
509
|
+
const values = [];
|
|
510
|
+
for (const statement of splitStatements(source)) {
|
|
511
|
+
const conditional = lowerConditional(statement, registry);
|
|
512
|
+
if (conditional)
|
|
513
|
+
values.push(conditional);
|
|
514
|
+
else if (/^\s*(const|let|var|return|throw)\b/.test(statement))
|
|
515
|
+
continue;
|
|
516
|
+
else
|
|
517
|
+
values.push(lowerRange(statement, registry));
|
|
518
|
+
}
|
|
519
|
+
return values.join(", ");
|
|
520
|
+
}
|
|
521
|
+
function lowerAstClosure(body, parameter, role, registry = canonicalInitializerSymbols) {
|
|
522
|
+
if (role === "viewBuilder")
|
|
523
|
+
return lowerViewBuilderClosure(body, parameter, registry);
|
|
524
|
+
const parsed = parseMunBuilder(body);
|
|
525
|
+
const lowered = lowerMunBuilderAst(parsed, {
|
|
526
|
+
transformRaw: value => lowerRange(value, registry),
|
|
527
|
+
transformArgument: (value, call, argumentIndex) => lowerForEachIdentityOptions(value, call, argumentIndex, registry),
|
|
528
|
+
closure: (nestedBody, nestedParameter, nestedRole) => lowerAstClosure(nestedBody, nestedParameter, nestedRole, registry),
|
|
529
|
+
closureRole: (nestedCall, context) => closureRoleForKnownCall(nestedCall, context, registry),
|
|
530
|
+
}).join(", ");
|
|
531
|
+
const actionBody = lowerRange(body, registry);
|
|
532
|
+
const { asynchronous, statements } = closureEffects(actionBody);
|
|
533
|
+
if (role === "action")
|
|
534
|
+
return `${asynchronous ? "async " : ""}(${parameter ?? ""}) => {${actionBody}}`;
|
|
535
|
+
if (parameter)
|
|
536
|
+
return `(${parameter}) => [${lowered}]`;
|
|
537
|
+
const action = asynchronous || statements;
|
|
538
|
+
const builder = action ? "() => []" : `() => [${lowered}]`;
|
|
539
|
+
return `overloadClosure(${builder}, ${asynchronous ? "async " : ""}() => {${actionBody}})`;
|
|
540
|
+
}
|
|
541
|
+
function lowerBuilder(call, source, registry = canonicalInitializerSymbols) {
|
|
542
|
+
const parsed = parseMunBuilder(source.slice(call.start, call.end), call.start);
|
|
543
|
+
// The scanner intentionally finds call-shaped blocks before the AST knows
|
|
544
|
+
// whether the block is a Mun closure. If it is an object/ordinary block,
|
|
545
|
+
// preserve it as source instead of feeding the same span back into
|
|
546
|
+
// lowerRange forever.
|
|
547
|
+
if (parsed.statements.length === 1 && parsed.statements[0]?.kind === "raw") {
|
|
548
|
+
return source.slice(call.start, call.end);
|
|
549
|
+
}
|
|
550
|
+
const lowered = lowerMunBuilderAst(parsed, {
|
|
551
|
+
transformRaw: value => lowerRange(value, registry),
|
|
552
|
+
transformArgument: (value, call, argumentIndex) => lowerForEachIdentityOptions(value, call, argumentIndex, registry),
|
|
553
|
+
closure: (body, parameter, role) => lowerAstClosure(body, parameter, role, registry),
|
|
554
|
+
closureRole: (nestedCall, context) => closureRoleForKnownCall(nestedCall, context, registry),
|
|
555
|
+
});
|
|
556
|
+
if (lowered.length === 1)
|
|
557
|
+
return lowered[0];
|
|
558
|
+
return `${call.name}(${lowerArguments(call.argumentSource, call.name, registry)})`;
|
|
559
|
+
}
|
|
560
|
+
function lowerRange(source, registry = canonicalInitializerSymbols) {
|
|
561
|
+
let output = "";
|
|
562
|
+
let cursor = 0;
|
|
563
|
+
let iterations = 0;
|
|
564
|
+
while (cursor < source.length) {
|
|
565
|
+
if (++iterations > source.length + 1)
|
|
566
|
+
throw syntaxError("Mun lowering did not advance past a builder expression", cursor);
|
|
567
|
+
const call = findBuilder(source, cursor);
|
|
568
|
+
const html = findRawHtml(source, cursor, value => lowerRange(value, registry));
|
|
569
|
+
if (!call && !html)
|
|
570
|
+
break;
|
|
571
|
+
if (html && (!call || html.start < call.start)) {
|
|
572
|
+
output += lowerShorthand(source.slice(cursor, html.start));
|
|
573
|
+
output += html.code;
|
|
574
|
+
cursor = html.end;
|
|
575
|
+
continue;
|
|
576
|
+
}
|
|
577
|
+
output += lowerShorthand(source.slice(cursor, call.start));
|
|
578
|
+
output += lowerBuilder(call, source, registry);
|
|
579
|
+
cursor = call.end;
|
|
580
|
+
}
|
|
581
|
+
output += lowerShorthand(source.slice(cursor));
|
|
582
|
+
return output;
|
|
583
|
+
}
|
|
584
|
+
function structParameter(source) {
|
|
585
|
+
const kind = source.includes("@ViewBuilder") ? "viewBuilder" : source.includes("@Action") ? "action" : source.includes("@Binding") ? "binding" : "value";
|
|
586
|
+
const clean = source.replace(/@(?:ViewBuilder|Action|Binding)\s*/g, "").trim();
|
|
587
|
+
const defaultIndex = topLevelEquals(clean);
|
|
588
|
+
const declaration = defaultIndex < 0 ? clean : clean.slice(0, defaultIndex).trim();
|
|
589
|
+
const defaultValue = defaultIndex < 0 ? undefined : clean.slice(defaultIndex + 1).trim();
|
|
590
|
+
const colon = topLevelColon(declaration);
|
|
591
|
+
const head = (colon < 0 ? declaration : declaration.slice(0, colon)).trim();
|
|
592
|
+
const words = head.split(/\s+/).filter(Boolean);
|
|
593
|
+
const name = words[words.length - 1]?.replace(/^_+/, "");
|
|
594
|
+
if (!name)
|
|
595
|
+
throw new SyntaxError(`Invalid struct initializer parameter: ${source}`);
|
|
596
|
+
return {
|
|
597
|
+
name,
|
|
598
|
+
label: words[0] === "_" ? undefined : words[0],
|
|
599
|
+
kind,
|
|
600
|
+
required: defaultIndex < 0,
|
|
601
|
+
defaultValue,
|
|
602
|
+
type: colon < 0 ? undefined : declaration.slice(colon + 1).trim(),
|
|
603
|
+
};
|
|
604
|
+
}
|
|
605
|
+
function topLevelEquals(source) {
|
|
606
|
+
let parens = 0;
|
|
607
|
+
let brackets = 0;
|
|
608
|
+
let braces = 0;
|
|
609
|
+
for (let cursor = 0; cursor < source.length; cursor += 1) {
|
|
610
|
+
const character = source[cursor];
|
|
611
|
+
if (character === "\"" || character === "'" || character === "`") {
|
|
612
|
+
cursor = skipString(source, cursor) - 1;
|
|
613
|
+
continue;
|
|
614
|
+
}
|
|
615
|
+
if (character === "(")
|
|
616
|
+
parens += 1;
|
|
617
|
+
else if (character === ")")
|
|
618
|
+
parens -= 1;
|
|
619
|
+
else if (character === "[")
|
|
620
|
+
brackets += 1;
|
|
621
|
+
else if (character === "]")
|
|
622
|
+
brackets -= 1;
|
|
623
|
+
else if (character === "{")
|
|
624
|
+
braces += 1;
|
|
625
|
+
else if (character === "}")
|
|
626
|
+
braces -= 1;
|
|
627
|
+
else if (character === "=" && parens === 0 && brackets === 0 && braces === 0 && source[cursor + 1] !== ">")
|
|
628
|
+
return cursor;
|
|
629
|
+
}
|
|
630
|
+
return -1;
|
|
631
|
+
}
|
|
632
|
+
function structInitializerPlans(declaration) {
|
|
633
|
+
const fields = declaration.fields.map(field => ({
|
|
634
|
+
name: field.name,
|
|
635
|
+
kind: field.kind === "state" ? "state" : field.kind === "binding" ? "binding" : "value",
|
|
636
|
+
type: field.type,
|
|
637
|
+
defaultValue: field.initializer,
|
|
638
|
+
}));
|
|
639
|
+
return declaration.initializers.length > 0
|
|
640
|
+
? declaration.initializers.map(item => structInitializerPlan(item.parametersSource, item.bodySource))
|
|
641
|
+
: [structInitializerPlan(fields.filter(field => field.kind !== "state").map(field => `${field.kind === "binding" ? "@Binding " : ""}${field.name}: unknown${field.defaultValue === undefined ? "" : ` = ${field.defaultValue}`}`).join(", "), "")];
|
|
642
|
+
}
|
|
643
|
+
function structInitializerPlan(parameterSource, bodySource) {
|
|
644
|
+
const parsedParameters = splitTopLevel(parameterSource).filter(Boolean).map(structParameter);
|
|
645
|
+
const parameters = parsedParameters.map((parameter, index) => ({
|
|
646
|
+
...parameter,
|
|
647
|
+
trailing: index === parsedParameters.length - 1 && (parameter.kind === "viewBuilder" || parameter.kind === "action"),
|
|
648
|
+
labelRequired: parameter.label !== undefined && !(index === parsedParameters.length - 1 && (parameter.kind === "viewBuilder" || parameter.kind === "action")),
|
|
649
|
+
}));
|
|
650
|
+
const assignments = structFieldAssignments(bodySource);
|
|
651
|
+
const delegationMatch = /\bself\.init\s*\(/.exec(bodySource);
|
|
652
|
+
if (!delegationMatch)
|
|
653
|
+
return { parameters, assignments };
|
|
654
|
+
const open = bodySource.indexOf("(", delegationMatch.index);
|
|
655
|
+
const close = matching(bodySource, open, "(", ")");
|
|
656
|
+
return { parameters, assignments, delegation: splitTopLevel(bodySource.slice(open + 1, close)).filter(Boolean) };
|
|
657
|
+
}
|
|
658
|
+
/**
|
|
659
|
+
* Collect `self.<field> = <value>` assignments from an initializer body with
|
|
660
|
+
* quote-, comment-, and nesting-aware value boundaries. A naive
|
|
661
|
+
* line-oriented capture corrupts single-line bodies such as
|
|
662
|
+
* `{ if (v < 0) { self.v = 0 } else { self.v = v } }` by swallowing the
|
|
663
|
+
* closing braces into the field expression.
|
|
664
|
+
*/
|
|
665
|
+
function structFieldAssignments(bodySource) {
|
|
666
|
+
const assignments = new Map();
|
|
667
|
+
let cursor = 0;
|
|
668
|
+
while (cursor < bodySource.length) {
|
|
669
|
+
const character = bodySource[cursor];
|
|
670
|
+
if (character === '"' || character === "'" || character === "`") {
|
|
671
|
+
cursor = skipString(bodySource, cursor);
|
|
672
|
+
continue;
|
|
673
|
+
}
|
|
674
|
+
if (character === "/" && (bodySource[cursor + 1] === "/" || bodySource[cursor + 1] === "*")) {
|
|
675
|
+
cursor = skipComment(bodySource, cursor);
|
|
676
|
+
continue;
|
|
677
|
+
}
|
|
678
|
+
if (character !== "s") {
|
|
679
|
+
cursor += 1;
|
|
680
|
+
continue;
|
|
681
|
+
}
|
|
682
|
+
const header = /^self\.[A-Za-z_$][A-Za-z0-9_$]*\s*=(?![=>])/.exec(bodySource.slice(cursor));
|
|
683
|
+
if (!header || (cursor > 0 && /[\w$.]/.test(bodySource[cursor - 1]))) {
|
|
684
|
+
cursor += 1;
|
|
685
|
+
continue;
|
|
686
|
+
}
|
|
687
|
+
const name = /^self\.([A-Za-z_$][A-Za-z0-9_$]*)/.exec(header.input)?.[1];
|
|
688
|
+
if (!name) {
|
|
689
|
+
cursor += 1;
|
|
690
|
+
continue;
|
|
691
|
+
}
|
|
692
|
+
let valueStart = cursor + header[0].length;
|
|
693
|
+
while (valueStart < bodySource.length && /\s/.test(bodySource[valueStart]))
|
|
694
|
+
valueStart += 1;
|
|
695
|
+
let parens = 0;
|
|
696
|
+
let brackets = 0;
|
|
697
|
+
let braces = 0;
|
|
698
|
+
let end = valueStart;
|
|
699
|
+
while (end < bodySource.length) {
|
|
700
|
+
const valueCharacter = bodySource[end];
|
|
701
|
+
if (valueCharacter === '"' || valueCharacter === "'" || valueCharacter === "`") {
|
|
702
|
+
end = skipString(bodySource, end);
|
|
703
|
+
continue;
|
|
704
|
+
}
|
|
705
|
+
if (valueCharacter === "/" && (bodySource[end + 1] === "/" || bodySource[end + 1] === "*")) {
|
|
706
|
+
end = skipComment(bodySource, end);
|
|
707
|
+
continue;
|
|
708
|
+
}
|
|
709
|
+
if (valueCharacter === "(") {
|
|
710
|
+
parens += 1;
|
|
711
|
+
}
|
|
712
|
+
else if (valueCharacter === "[") {
|
|
713
|
+
brackets += 1;
|
|
714
|
+
}
|
|
715
|
+
else if (valueCharacter === "{") {
|
|
716
|
+
braces += 1;
|
|
717
|
+
}
|
|
718
|
+
else if (valueCharacter === ")") {
|
|
719
|
+
if (parens === 0)
|
|
720
|
+
break;
|
|
721
|
+
parens -= 1;
|
|
722
|
+
}
|
|
723
|
+
else if (valueCharacter === "]") {
|
|
724
|
+
if (brackets === 0)
|
|
725
|
+
break;
|
|
726
|
+
brackets -= 1;
|
|
727
|
+
}
|
|
728
|
+
else if (valueCharacter === "}") {
|
|
729
|
+
if (braces === 0)
|
|
730
|
+
break;
|
|
731
|
+
braces -= 1;
|
|
732
|
+
}
|
|
733
|
+
else if ((valueCharacter === ";" || valueCharacter === "\n") && parens === 0 && brackets === 0 && braces === 0) {
|
|
734
|
+
if (valueCharacter !== "\n")
|
|
735
|
+
break;
|
|
736
|
+
// Continue multi-line expressions whose current line ends with a
|
|
737
|
+
// binary operator or an open assignment (`self.title = "Hello" +\n"`).
|
|
738
|
+
if (!/[+\-*/%&|^<>?:=]$/.test(bodySource.slice(valueStart, end).trimEnd()))
|
|
739
|
+
break;
|
|
740
|
+
let next = end + 1;
|
|
741
|
+
while (next < bodySource.length && /\s/.test(bodySource[next]))
|
|
742
|
+
next += 1;
|
|
743
|
+
end = next;
|
|
744
|
+
continue;
|
|
745
|
+
}
|
|
746
|
+
end += 1;
|
|
747
|
+
}
|
|
748
|
+
assignments.set(name, bodySource.slice(valueStart, end).trim());
|
|
749
|
+
cursor = Math.max(end, cursor + header[0].length);
|
|
750
|
+
}
|
|
751
|
+
return assignments;
|
|
752
|
+
}
|
|
753
|
+
function structArgument(source) {
|
|
754
|
+
const colon = topLevelColon(source);
|
|
755
|
+
if (colon < 0)
|
|
756
|
+
return { value: source.trim() };
|
|
757
|
+
return { label: source.slice(0, colon).trim(), value: source.slice(colon + 1).trim() };
|
|
758
|
+
}
|
|
759
|
+
function delegatedParameterValues(parameters, arguments_) {
|
|
760
|
+
const values = new Map();
|
|
761
|
+
const used = new Set();
|
|
762
|
+
let nextPositional = 0;
|
|
763
|
+
for (const source of arguments_) {
|
|
764
|
+
const argument = structArgument(source);
|
|
765
|
+
let index = argument.label === undefined
|
|
766
|
+
? (() => {
|
|
767
|
+
while (used.has(nextPositional))
|
|
768
|
+
nextPositional += 1;
|
|
769
|
+
return nextPositional;
|
|
770
|
+
})()
|
|
771
|
+
: parameters.findIndex(parameter => parameter.label === argument.label || parameter.name === argument.label);
|
|
772
|
+
if (index < 0 || index >= parameters.length || used.has(index))
|
|
773
|
+
return undefined;
|
|
774
|
+
used.add(index);
|
|
775
|
+
if (argument.label === undefined)
|
|
776
|
+
nextPositional = index + 1;
|
|
777
|
+
values.set(parameters[index].name, argument.value);
|
|
778
|
+
}
|
|
779
|
+
for (let index = 0; index < parameters.length; index += 1) {
|
|
780
|
+
const parameter = parameters[index];
|
|
781
|
+
if (!values.has(parameter.name)) {
|
|
782
|
+
if (parameter.required)
|
|
783
|
+
return undefined;
|
|
784
|
+
values.set(parameter.name, parameter.defaultValue ?? "undefined");
|
|
785
|
+
}
|
|
786
|
+
}
|
|
787
|
+
return values;
|
|
788
|
+
}
|
|
789
|
+
function compilerInitializerArguments(source) {
|
|
790
|
+
return splitTopLevel(source).flatMap(argument => {
|
|
791
|
+
const named = /^namedArguments\s*\(\s*\{([\s\S]*)\}\s*\)$/.exec(argument.trim());
|
|
792
|
+
return named ? splitTopLevel(named[1]) : [argument];
|
|
793
|
+
});
|
|
794
|
+
}
|
|
795
|
+
function compilerSemanticArgument(source) {
|
|
796
|
+
const argument = structArgument(source);
|
|
797
|
+
const value = argument.value.trim();
|
|
798
|
+
if (/^(?:"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'|`(?:[^`\\]|\\.)*`)$/.test(value))
|
|
799
|
+
return { label: argument.label, type: "string" };
|
|
800
|
+
if (/^-?(?:\d+(?:\.\d*)?|\.\d+)$/.test(value))
|
|
801
|
+
return { label: argument.label, type: "number" };
|
|
802
|
+
if (/^(?:true|false)$/.test(value))
|
|
803
|
+
return { label: argument.label, type: "boolean" };
|
|
804
|
+
if (/^(?:overloadClosure|function)\s*\(/.test(value) || /=>/.test(value))
|
|
805
|
+
return { label: argument.label, type: "function" };
|
|
806
|
+
if (/^Binding\s*\(/.test(value))
|
|
807
|
+
return { label: argument.label, kind: "binding", type: "binding", underlyingType: "dynamic" };
|
|
808
|
+
if (/^State\s*\(/.test(value))
|
|
809
|
+
return { label: argument.label, type: "state" };
|
|
810
|
+
return { label: argument.label, type: "unknown" };
|
|
811
|
+
}
|
|
812
|
+
function canonicalRuntimeBindings(file) {
|
|
813
|
+
const names = new Map();
|
|
814
|
+
const namespaces = new Set();
|
|
815
|
+
for (const statement of file.statements) {
|
|
816
|
+
if (!ts.isImportDeclaration(statement) || !ts.isStringLiteral(statement.moduleSpecifier))
|
|
817
|
+
continue;
|
|
818
|
+
if (statement.moduleSpecifier.text !== "@mun-ui/core/compat"
|
|
819
|
+
&& statement.moduleSpecifier.text !== "@mun-ui/react")
|
|
820
|
+
continue;
|
|
821
|
+
const clause = statement.importClause;
|
|
822
|
+
if (!clause || clause.isTypeOnly)
|
|
823
|
+
continue;
|
|
824
|
+
const bindings = clause.namedBindings;
|
|
825
|
+
if (bindings && ts.isNamespaceImport(bindings))
|
|
826
|
+
namespaces.add(bindings.name.text);
|
|
827
|
+
if (bindings && ts.isNamedImports(bindings)) {
|
|
828
|
+
for (const element of bindings.elements) {
|
|
829
|
+
if (element.isTypeOnly)
|
|
830
|
+
continue;
|
|
831
|
+
const exported = element.propertyName?.text ?? element.name.text;
|
|
832
|
+
if (canonicalInitializerSymbols.has(exported))
|
|
833
|
+
names.set(element.name.text, exported);
|
|
834
|
+
}
|
|
835
|
+
}
|
|
836
|
+
}
|
|
837
|
+
return { names, namespaces };
|
|
838
|
+
}
|
|
839
|
+
function canonicalCallName(call, bindings, shadowed) {
|
|
840
|
+
const callee = unwrapTsExpression(call.expression);
|
|
841
|
+
if (ts.isIdentifier(callee)) {
|
|
842
|
+
if (shadowed.has(callee.text))
|
|
843
|
+
return undefined;
|
|
844
|
+
const exportedName = bindings.names.get(callee.text);
|
|
845
|
+
return exportedName ? { localSource: callee.text, exportedName } : undefined;
|
|
846
|
+
}
|
|
847
|
+
if (!ts.isPropertyAccessExpression(callee))
|
|
848
|
+
return undefined;
|
|
849
|
+
const owner = unwrapTsExpression(callee.expression);
|
|
850
|
+
if (!ts.isIdentifier(owner) || shadowed.has(owner.text) || !bindings.namespaces.has(owner.text))
|
|
851
|
+
return undefined;
|
|
852
|
+
return canonicalInitializerSymbols.has(callee.name.text)
|
|
853
|
+
? { localSource: `${owner.text}.${callee.name.text}`, exportedName: callee.name.text }
|
|
854
|
+
: undefined;
|
|
855
|
+
}
|
|
856
|
+
/**
|
|
857
|
+
* Resolve the common intrinsic calls that need no TypeChecker from Mun's
|
|
858
|
+
* canonical initializer manifest. Unknown/dynamic arguments deliberately stay
|
|
859
|
+
* untouched for the semantic TypeScript pass below.
|
|
860
|
+
*/
|
|
861
|
+
function lowerStaticCanonicalCalls(source) {
|
|
862
|
+
if (!/(?:from\s*|import\s*\()\s*["'](?:mun|@mun-ui\/(?:core|react))["']/.test(source))
|
|
863
|
+
return source;
|
|
864
|
+
const file = ts.createSourceFile("mun-canonical-calls.ts", source, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS);
|
|
865
|
+
const bindings = canonicalRuntimeBindings(file);
|
|
866
|
+
if (bindings.names.size === 0 && bindings.namespaces.size === 0)
|
|
867
|
+
return source;
|
|
868
|
+
const edits = [];
|
|
869
|
+
const visit = (node, shadowed) => {
|
|
870
|
+
if (ts.isCallExpression(node)) {
|
|
871
|
+
const candidate = canonicalCallName(node, bindings, shadowed);
|
|
872
|
+
if (candidate && !node.arguments.some(argument => /^namedArguments\s*\(/.test(argument.getText(file)))) {
|
|
873
|
+
const semanticArguments = node.arguments.map(argument => compilerSemanticArgument(argument.getText(file)));
|
|
874
|
+
if (semanticArguments.every(argument => argument.type !== "unknown")) {
|
|
875
|
+
const symbols = canonicalInitializerSymbols.get(candidate.exportedName) ?? [];
|
|
876
|
+
const viewType = {
|
|
877
|
+
kind: "view",
|
|
878
|
+
name: candidate.exportedName,
|
|
879
|
+
qualifiedName: candidate.exportedName,
|
|
880
|
+
initializers: symbols,
|
|
881
|
+
fields: [],
|
|
882
|
+
};
|
|
883
|
+
const resolution = resolveSemanticCall(viewType, semanticArguments);
|
|
884
|
+
const selected = resolution.resolvedInitializer;
|
|
885
|
+
if (selected && !selected.parameters.some(parameter => parameter.variadic || parameter.kind === "viewBuilder" || parameter.kind === "binding")) {
|
|
886
|
+
edits.push({
|
|
887
|
+
start: node.getStart(file),
|
|
888
|
+
end: node.end,
|
|
889
|
+
replacement: `${candidate.localSource}.viewType.createNodeCompiled(${selected.index}, [${node.arguments.map(argument => argument.getText(file)).join(", ")}])`,
|
|
890
|
+
});
|
|
891
|
+
return;
|
|
892
|
+
}
|
|
893
|
+
}
|
|
894
|
+
}
|
|
895
|
+
}
|
|
896
|
+
if (ts.isArrowFunction(node) || ts.isFunctionExpression(node) || ts.isFunctionDeclaration(node) || ts.isMethodDeclaration(node)) {
|
|
897
|
+
const local = new Set(shadowed);
|
|
898
|
+
for (const parameter of node.parameters)
|
|
899
|
+
for (const name of bindingNames(parameter.name))
|
|
900
|
+
local.add(name);
|
|
901
|
+
if (ts.isFunctionDeclaration(node) && node.name)
|
|
902
|
+
local.add(node.name.text);
|
|
903
|
+
if (node.body)
|
|
904
|
+
visit(node.body, local);
|
|
905
|
+
return;
|
|
906
|
+
}
|
|
907
|
+
if (ts.isBlock(node)) {
|
|
908
|
+
const local = new Set(shadowed);
|
|
909
|
+
for (const name of directBlockBindings(node))
|
|
910
|
+
local.add(name);
|
|
911
|
+
ts.forEachChild(node, child => visit(child, local));
|
|
912
|
+
return;
|
|
913
|
+
}
|
|
914
|
+
if (ts.isCatchClause(node)) {
|
|
915
|
+
const local = new Set(shadowed);
|
|
916
|
+
if (node.variableDeclaration)
|
|
917
|
+
for (const name of bindingNames(node.variableDeclaration.name))
|
|
918
|
+
local.add(name);
|
|
919
|
+
visit(node.block, local);
|
|
920
|
+
return;
|
|
921
|
+
}
|
|
922
|
+
ts.forEachChild(node, child => visit(child, shadowed));
|
|
923
|
+
};
|
|
924
|
+
visit(file, new Set());
|
|
925
|
+
if (edits.length === 0)
|
|
926
|
+
return source;
|
|
927
|
+
let result = source;
|
|
928
|
+
for (const edit of edits.sort((left, right) => right.start - left.start)) {
|
|
929
|
+
result = result.slice(0, edit.start) + edit.replacement + result.slice(edit.end);
|
|
930
|
+
}
|
|
931
|
+
return result;
|
|
932
|
+
}
|
|
933
|
+
function legacyHostCoercion(type) {
|
|
934
|
+
const normalized = type?.replace(/\s+/g, "") ?? "";
|
|
935
|
+
if (/(?:^|\|)boolean(?:\||$)/.test(normalized))
|
|
936
|
+
return "boolean";
|
|
937
|
+
if (/(?:^|\|)number(?:\||$)/.test(normalized))
|
|
938
|
+
return "number";
|
|
939
|
+
return "identity";
|
|
940
|
+
}
|
|
941
|
+
function legacyHostPlanSource(plans) {
|
|
942
|
+
return `{ initializers: [${plans.map((plan, index) => `{ index: ${index}, parameters: [${plan.parameters.map(parameter => `{ name: ${JSON.stringify(parameter.name)}, label: ${parameter.label === undefined ? "undefined" : JSON.stringify(parameter.label)}, kind: ${JSON.stringify(parameter.kind)}, required: ${parameter.required}, trailing: ${parameter.trailing === true}, coercion: ${JSON.stringify(legacyHostCoercion(parameter.type))} }`).join(", ")}] }`).join(", ")}] }`;
|
|
943
|
+
}
|
|
944
|
+
function semanticInitializerSymbol(name, plan, index) {
|
|
945
|
+
return {
|
|
946
|
+
kind: "initializer",
|
|
947
|
+
index,
|
|
948
|
+
signature: `${name}(${plan.parameters.map(parameter => `${parameter.kind === "viewBuilder" ? "@ViewBuilder " : parameter.kind === "action" ? "@Action " : parameter.kind === "binding" ? "@Binding " : ""}${parameter.label ?? parameter.name}`).join(", ")})`,
|
|
949
|
+
parameters: plan.parameters,
|
|
950
|
+
};
|
|
951
|
+
}
|
|
952
|
+
function staticInitializerIndex(declaration, argumentSource, offset = 0) {
|
|
953
|
+
const plans = structInitializerPlans(declaration);
|
|
954
|
+
const arguments_ = compilerInitializerArguments(argumentSource).map(compilerSemanticArgument);
|
|
955
|
+
const initializers = plans.map((plan, index) => semanticInitializerSymbol(declaration.name, plan, index));
|
|
956
|
+
const viewType = {
|
|
957
|
+
kind: "view",
|
|
958
|
+
name: declaration.name,
|
|
959
|
+
qualifiedName: declaration.name,
|
|
960
|
+
genericParameters: declaration.genericParameters,
|
|
961
|
+
fields: [],
|
|
962
|
+
initializers,
|
|
963
|
+
};
|
|
964
|
+
const result = resolveSemanticCall(viewType, arguments_);
|
|
965
|
+
if (result.resolvedInitializer)
|
|
966
|
+
return result.resolvedInitializer.index;
|
|
967
|
+
if (result.diagnostics[0]?.code === "MUN_INITIALIZER" && arguments_.some(argument => argument.type === "unknown"))
|
|
968
|
+
return undefined;
|
|
969
|
+
throw new MunInitializerSyntaxError(result.diagnostics[0]?.message ?? `No matching initializer for ${declaration.name}.`, offset);
|
|
970
|
+
}
|
|
971
|
+
function findDelegatedInitializer(plans, arguments_, excludedIndex) {
|
|
972
|
+
for (let index = 0; index < plans.length; index += 1) {
|
|
973
|
+
if (index === excludedIndex)
|
|
974
|
+
continue;
|
|
975
|
+
const plan = plans[index];
|
|
976
|
+
const values = delegatedParameterValues(plan.parameters, arguments_);
|
|
977
|
+
if (values)
|
|
978
|
+
return { plan, values };
|
|
979
|
+
}
|
|
980
|
+
return undefined;
|
|
981
|
+
}
|
|
982
|
+
function substituteStructParameters(expression, values) {
|
|
983
|
+
let result = expression;
|
|
984
|
+
for (const [name, value] of values)
|
|
985
|
+
result = result.replace(new RegExp(`\\b${name}\\b`, "g"), `(${value})`);
|
|
986
|
+
return result;
|
|
987
|
+
}
|
|
988
|
+
function resolvedStructFields(index, plans, fields, stack = new Set()) {
|
|
989
|
+
if (stack.has(index))
|
|
990
|
+
return new Map();
|
|
991
|
+
const nextStack = new Set(stack).add(index);
|
|
992
|
+
const plan = plans[index];
|
|
993
|
+
const values = new Map();
|
|
994
|
+
if (plan.delegation) {
|
|
995
|
+
const delegated = findDelegatedInitializer(plans, plan.delegation, index);
|
|
996
|
+
if (delegated) {
|
|
997
|
+
const targetIndex = plans.indexOf(delegated.plan);
|
|
998
|
+
const targetFields = resolvedStructFields(targetIndex, plans, fields, nextStack);
|
|
999
|
+
for (const [field, expression] of targetFields)
|
|
1000
|
+
values.set(field, substituteStructParameters(expression, delegated.values));
|
|
1001
|
+
}
|
|
1002
|
+
}
|
|
1003
|
+
for (const [field, expression] of plan.assignments)
|
|
1004
|
+
values.set(field, expression);
|
|
1005
|
+
for (const field of fields) {
|
|
1006
|
+
if (values.has(field.name))
|
|
1007
|
+
continue;
|
|
1008
|
+
const parameter = plan.parameters.find(item => item.name === field.name);
|
|
1009
|
+
if (parameter)
|
|
1010
|
+
values.set(field.name, parameter.name);
|
|
1011
|
+
else if (field.defaultValue !== undefined && field.kind !== "state")
|
|
1012
|
+
values.set(field.name, `(${field.defaultValue})`);
|
|
1013
|
+
else
|
|
1014
|
+
values.set(field.name, "undefined");
|
|
1015
|
+
}
|
|
1016
|
+
return values;
|
|
1017
|
+
}
|
|
1018
|
+
function delegatedStructInitializer(name, plan, fields, plans, index) {
|
|
1019
|
+
const parameters = plan.parameters;
|
|
1020
|
+
const assignments = resolvedStructFields(index, plans, fields);
|
|
1021
|
+
const checks = parameters.map((parameter, parameterIndex) => parameter.kind === "value"
|
|
1022
|
+
? "true"
|
|
1023
|
+
: parameter.kind === "binding"
|
|
1024
|
+
? `(args[${parameterIndex}] && typeof args[${parameterIndex}] === "object" && (Object.getOwnPropertyDescriptor(args[${parameterIndex}], "value")?.get || Object.getOwnPropertyDescriptor(args[${parameterIndex}], "value")?.set))`
|
|
1025
|
+
: parameter.required
|
|
1026
|
+
? `typeof args[${parameterIndex}] === "function"`
|
|
1027
|
+
: `(args[${parameterIndex}] === undefined || typeof args[${parameterIndex}] === "function")`);
|
|
1028
|
+
const values = fields.map(field => {
|
|
1029
|
+
const expression = assignments.get(field.name) ?? "undefined";
|
|
1030
|
+
const parameter = parameters.find(item => item.name === field.name);
|
|
1031
|
+
const resolved = parameter?.kind === "viewBuilder" && (expression === `${parameter.name}()` || expression === `(${parameter.name})()`)
|
|
1032
|
+
? `resolveBuilderInput(${parameter.name})`
|
|
1033
|
+
: expression;
|
|
1034
|
+
return `${field.name}: ${resolved}`;
|
|
1035
|
+
});
|
|
1036
|
+
const signature = `${name}(${parameters.map(parameter => `${parameter.kind === "viewBuilder" ? "@ViewBuilder " : parameter.kind === "action" ? "@Action " : parameter.kind === "binding" ? "@Binding " : ""}${parameter.label ?? parameter.name}${parameter.defaultValue === undefined ? "" : ` = ${parameter.defaultValue}`}`).join(", ")})`;
|
|
1037
|
+
const metadata = `[${parameters.map(parameter => `{ name: ${JSON.stringify(parameter.name)}, kind: ${JSON.stringify(parameter.kind)}, label: ${parameter.label ? JSON.stringify(parameter.label) : "undefined"}, labelRequired: ${parameter.labelRequired === true}, required: ${parameter.required}, trailing: ${parameter.trailing === true}, type: ${parameter.type ? JSON.stringify(parameter.type) : "undefined"} }`).join(", ")}]`;
|
|
1038
|
+
const required = parameters.filter(parameter => parameter.required).length;
|
|
1039
|
+
const maximum = parameters.length;
|
|
1040
|
+
return `initializer(${JSON.stringify(signature)}, args => args.length >= ${required} && args.length <= ${maximum}${checks.length ? ` && ${checks.join(" && ")}` : ""}, args => { ${parameters.map((parameter, parameterIndex) => `const ${parameter.name} = args[${parameterIndex}]${parameter.defaultValue ? ` === undefined ? (${parameter.defaultValue}) : args[${parameterIndex}]` : ""}`).join("; ")}; return { ${values.join(", ")} } }, ${metadata})`;
|
|
1041
|
+
}
|
|
1042
|
+
function parsedCompilerExpression(source) {
|
|
1043
|
+
const file = ts.createSourceFile("mun-struct-body.ts", `const __munBody = (${source})`, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS);
|
|
1044
|
+
if ((file.parseDiagnostics?.length ?? 0) > 0)
|
|
1045
|
+
return undefined;
|
|
1046
|
+
const statement = file.statements[0];
|
|
1047
|
+
if (!statement || !ts.isVariableStatement(statement))
|
|
1048
|
+
return undefined;
|
|
1049
|
+
const initializer = statement.declarationList.declarations[0]?.initializer;
|
|
1050
|
+
return initializer ? unwrapTsExpression(initializer) : undefined;
|
|
1051
|
+
}
|
|
1052
|
+
function lowerStructDefinition(declaration, registry = canonicalInitializerSymbols, stateProof, swiftMembers = false) {
|
|
1053
|
+
const fields = declaration.fields.map(field => ({
|
|
1054
|
+
name: field.name,
|
|
1055
|
+
kind: field.kind === "state" ? "state" : field.kind === "binding" ? "binding" : "value",
|
|
1056
|
+
type: field.type,
|
|
1057
|
+
defaultValue: field.initializer,
|
|
1058
|
+
}));
|
|
1059
|
+
const plans = structInitializerPlans(declaration);
|
|
1060
|
+
const initializers = plans.map((plan, index) => delegatedStructInitializer(declaration.name, plan, fields, plans, index));
|
|
1061
|
+
const stateFields = fields.filter(field => field.kind === "state");
|
|
1062
|
+
const state = stateFields.length === 0
|
|
1063
|
+
? ""
|
|
1064
|
+
: `, state: () => ({ ${stateFields.map(field => `${field.name}: ${field.defaultValue !== undefined && /^State\s*\(/.test(field.defaultValue) ? field.defaultValue : `State(${field.defaultValue ?? "undefined"})`}`).join(", ")} })`;
|
|
1065
|
+
const rawBody = declaration.bodyExpressionSource.trim().replace(/^return\s+/, "").replace(/;\s*$/, "");
|
|
1066
|
+
// A body that is a bare `if`/`else` is a ViewBuilder statement list, not an
|
|
1067
|
+
// expression: give it a Group to build into, as SwiftUI's implicit container does.
|
|
1068
|
+
const bodySource = /^if\b/.test(rawBody) ? `Group { ${rawBody} }` : rawBody;
|
|
1069
|
+
// Struct bodies are lowered before the module-wide named-call pass. Keep
|
|
1070
|
+
// SwiftUI-style labels intact by lowering them here as well; otherwise a
|
|
1071
|
+
// call such as Button(action: ..., label: { ... }) is consumed by the
|
|
1072
|
+
// builder pass and can reach TypeScript as `Button(action, ..., label, ...)`.
|
|
1073
|
+
const stateNames = new Set(stateFields.map(field => field.name));
|
|
1074
|
+
const storageNames = new Set(fields.filter(field => field.kind !== "value").map(field => field.name));
|
|
1075
|
+
const methodNames = new Set((declaration.methods ?? []).map(method => method.name));
|
|
1076
|
+
// Swift-only member syntax becomes ordinary call syntax before builder lowering.
|
|
1077
|
+
const prepare = (source) => lowerLabeledCalls(lowerLifecycleModifiers(lowerSwiftInterpolation(source)), methodNames);
|
|
1078
|
+
// Only user-authored expressions: generated metadata such as
|
|
1079
|
+
// `dependencies: props => [props.count]` must keep its property reads.
|
|
1080
|
+
const members = (source) => swiftMembers ? lowerCollectionMembers(source) : source;
|
|
1081
|
+
const loweredBody = members(lowerBoolToggle(lowerStructStateAccess(lowerRange(lowerNamedMunCalls(prepare(bodySource), registry), registry), storageNames)));
|
|
1082
|
+
const environment = (declaration.environment ?? []).map(value => ` const ${value.name} = environmentValue(${lowerSwiftKeyPaths(value.key)});`).join("");
|
|
1083
|
+
// Methods are function declarations, so computed properties and each other may call them in any order.
|
|
1084
|
+
const methods = (declaration.methods ?? []).map(method => {
|
|
1085
|
+
const lowered = lowerStructStateAccess(`${method.asynchronous ? "async " : ""}function ${method.name}(${lowerParameters(method.parametersSource)})${method.returnType ? `: ${method.asynchronous ? `Promise<${method.returnType}>` : method.returnType}` : ""} {${lowerRange(prepare(method.bodySource), registry)}}`, storageNames);
|
|
1086
|
+
return ` ${members(lowerBoolToggle(lowered))}`;
|
|
1087
|
+
}).join("");
|
|
1088
|
+
const computed = environment + methods + lowerComputedProperties(declaration.computed ?? [], storageNames, registry, prepare, members);
|
|
1089
|
+
const bodyExpression = stateFields.length > 0 && stateProof ? parsedCompilerExpression(loweredBody) : undefined;
|
|
1090
|
+
const dependenciesComplete = bodyExpression && stateProof && computed === ""
|
|
1091
|
+
? hasCompleteStaticStateDependencies(bodyExpression, stateNames, stateNames, stateProof.values, stateProof.namespaces)
|
|
1092
|
+
: false;
|
|
1093
|
+
const dependencies = stateFields.length === 0
|
|
1094
|
+
? ""
|
|
1095
|
+
: `, dependencies: (props: any) => [${stateFields.map(field => `props.${field.name}`).join(", ")}]${dependenciesComplete ? ", dependenciesComplete: true" : ""}`;
|
|
1096
|
+
const fieldMetadata = `fields: [${declaration.fields.map(field => `{ name: ${JSON.stringify(field.name)}, kind: ${JSON.stringify(field.kind)}, type: ${field.type === undefined ? "undefined" : JSON.stringify(field.type)}, defaultValue: ${field.initializer === undefined ? "undefined" : JSON.stringify(field.initializer)} }`).join(", ")}]`;
|
|
1097
|
+
const definitionMetadata = [
|
|
1098
|
+
declaration.genericParameters === undefined ? undefined : `genericParameters: ${JSON.stringify(declaration.genericParameters)}`,
|
|
1099
|
+
fieldMetadata,
|
|
1100
|
+
`legacyHost: ${legacyHostPlanSource(plans)}`,
|
|
1101
|
+
].filter((item) => item !== undefined).join(", ");
|
|
1102
|
+
return `defineView(${JSON.stringify(declaration.name)}, { ${definitionMetadata}, initializers: [${initializers.join(", ")}]${state}${dependencies}, body: (__munProps: any) => { const { ${fields.map(field => field.name).join(", ")} } = __munProps;${computed} return ${loweredBody} } })`;
|
|
1103
|
+
}
|
|
1104
|
+
/**
|
|
1105
|
+
* Computed properties become body-local constants, evaluated after the
|
|
1106
|
+
* members they read. A single expression is the value (Swift's implicit
|
|
1107
|
+
* return); a statement body runs as an immediately invoked block.
|
|
1108
|
+
*/
|
|
1109
|
+
function lowerComputedProperties(properties, storageNames, registry, prepare, members = source => source) {
|
|
1110
|
+
if (properties.length === 0)
|
|
1111
|
+
return "";
|
|
1112
|
+
const lowered = new Map(properties.map(property => {
|
|
1113
|
+
const source = prepare(property.bodySource).trim();
|
|
1114
|
+
const statements = /^(?:return|const|let|var|if|for|while|switch|guard|throw)\b/m.test(source);
|
|
1115
|
+
const value = statements
|
|
1116
|
+
? `(() => {${lowerRange(source, registry)}})()`
|
|
1117
|
+
: `(${lowerRange(lowerNamedMunCalls(source, registry), registry)})`;
|
|
1118
|
+
return [property.name, members(lowerBoolToggle(lowerStructStateAccess(value, storageNames)))];
|
|
1119
|
+
}));
|
|
1120
|
+
const ordered = [];
|
|
1121
|
+
const visiting = new Set();
|
|
1122
|
+
const visit = (name) => {
|
|
1123
|
+
if (ordered.includes(name))
|
|
1124
|
+
return;
|
|
1125
|
+
if (visiting.has(name))
|
|
1126
|
+
throw syntaxError(`Computed property '${name}' depends on itself`, 0);
|
|
1127
|
+
visiting.add(name);
|
|
1128
|
+
for (const other of lowered.keys()) {
|
|
1129
|
+
if (other !== name && new RegExp(`(?<![\\w$.])${other.replace(/\$/g, "\\$")}(?![\\w$])`).test(lowered.get(name)))
|
|
1130
|
+
visit(other);
|
|
1131
|
+
}
|
|
1132
|
+
visiting.delete(name);
|
|
1133
|
+
ordered.push(name);
|
|
1134
|
+
};
|
|
1135
|
+
for (const name of lowered.keys())
|
|
1136
|
+
visit(name);
|
|
1137
|
+
return ordered.map(name => ` const ${name} = ${lowered.get(name)};`).join("");
|
|
1138
|
+
}
|
|
1139
|
+
function lowerStructs(source, registry = canonicalInitializerSymbols, stateProof,
|
|
1140
|
+
/** Canonical `.mun`: Swift collection members (`items.count`) in user code. */
|
|
1141
|
+
swiftMembers = false) {
|
|
1142
|
+
const declarations = parseMunStructs(source);
|
|
1143
|
+
if (declarations.length === 0)
|
|
1144
|
+
return source;
|
|
1145
|
+
const proof = stateProof ?? importedMunValueBindings(validationSourceFile(source));
|
|
1146
|
+
let output = source;
|
|
1147
|
+
for (const declaration of [...declarations].sort((left, right) => right.range.start - left.range.start)) {
|
|
1148
|
+
const definition = lowerStructDefinition(declaration, registry, proof, swiftMembers);
|
|
1149
|
+
const nested = declaration.nested ?? [];
|
|
1150
|
+
const replacement = nested.length === 0
|
|
1151
|
+
? `const ${declaration.name} = ${definition}`
|
|
1152
|
+
: `const ${declaration.name} = (() => { ${nested.map(item => `const ${item.name} = ${lowerStructDefinition(item, registry, proof, swiftMembers)}`).join("; ")}; return Object.assign(${definition}, { ${nested.map(item => item.name).join(", ")} }); })()`;
|
|
1153
|
+
output = output.slice(0, declaration.range.start) + replacement + output.slice(declaration.range.end);
|
|
1154
|
+
}
|
|
1155
|
+
return output;
|
|
1156
|
+
}
|
|
1157
|
+
function lowerStaticStructCalls(source, declarations) {
|
|
1158
|
+
if (declarations.length === 0)
|
|
1159
|
+
return source;
|
|
1160
|
+
const known = new Map();
|
|
1161
|
+
const add = (declaration) => {
|
|
1162
|
+
known.set(declaration.name, known.has(declaration.name) ? undefined : declaration);
|
|
1163
|
+
for (const nested of declaration.nested ?? [])
|
|
1164
|
+
add(nested);
|
|
1165
|
+
};
|
|
1166
|
+
for (const declaration of declarations)
|
|
1167
|
+
add(declaration);
|
|
1168
|
+
const file = ts.createSourceFile("mun-specialization.ts", source, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS);
|
|
1169
|
+
const edits = [];
|
|
1170
|
+
const simpleBuilderValue = (value) => {
|
|
1171
|
+
const expression = /^\s*\(\s*\)\s*=>\s*(\[[\s\S]*\])\s*$/.exec(value);
|
|
1172
|
+
if (expression)
|
|
1173
|
+
return expression[1];
|
|
1174
|
+
const block = /^\s*\(\s*\)\s*=>\s*\{\s*return\s+(\[[\s\S]*\])\s*;?\s*\}\s*$/.exec(value);
|
|
1175
|
+
return block?.[1];
|
|
1176
|
+
};
|
|
1177
|
+
const visit = (node) => {
|
|
1178
|
+
if (ts.isCallExpression(node) && ts.isIdentifier(node.expression)) {
|
|
1179
|
+
const declaration = known.get(node.expression.text);
|
|
1180
|
+
const initializerIndex = declaration && staticInitializerIndex(declaration, node.arguments.map(argument => argument.getText(file)).join(", "), node.expression.getStart(file));
|
|
1181
|
+
if (initializerIndex !== undefined && declaration) {
|
|
1182
|
+
const plan = structInitializerPlans(declaration)[initializerIndex];
|
|
1183
|
+
const flattened = plan
|
|
1184
|
+
? compilerInitializerArguments(node.arguments.map(argument => argument.getText(file)).join(", "))
|
|
1185
|
+
: [];
|
|
1186
|
+
const values = plan ? delegatedParameterValues(plan.parameters, flattened) : undefined;
|
|
1187
|
+
const compiled = !!plan && !!values;
|
|
1188
|
+
const argumentsSource = compiled
|
|
1189
|
+
? plan.parameters.map(parameter => {
|
|
1190
|
+
const value = values.get(parameter.name) ?? "undefined";
|
|
1191
|
+
return parameter.kind === "viewBuilder" ? simpleBuilderValue(value) ?? value : value;
|
|
1192
|
+
}).join(", ")
|
|
1193
|
+
: node.arguments.map(argument => argument.getText(file)).join(", ");
|
|
1194
|
+
const method = compiled ? "createNodeCompiled" : "createNodeSpecialized";
|
|
1195
|
+
edits.push({
|
|
1196
|
+
start: node.expression.getStart(file),
|
|
1197
|
+
end: node.end,
|
|
1198
|
+
replacement: `${node.expression.text}.viewType.${method}(${initializerIndex}, [${argumentsSource}])`,
|
|
1199
|
+
});
|
|
1200
|
+
return;
|
|
1201
|
+
}
|
|
1202
|
+
}
|
|
1203
|
+
ts.forEachChild(node, visit);
|
|
1204
|
+
};
|
|
1205
|
+
visit(file);
|
|
1206
|
+
let result = source;
|
|
1207
|
+
for (const edit of edits.sort((left, right) => right.start - left.start)) {
|
|
1208
|
+
result = result.slice(0, edit.start) + edit.replacement + result.slice(edit.end);
|
|
1209
|
+
}
|
|
1210
|
+
return result;
|
|
1211
|
+
}
|
|
1212
|
+
function isMunPackage(moduleName) {
|
|
1213
|
+
return moduleName.startsWith("@mun-ui/");
|
|
1214
|
+
}
|
|
1215
|
+
function bindingNames(name) {
|
|
1216
|
+
if (ts.isIdentifier(name))
|
|
1217
|
+
return [name.text];
|
|
1218
|
+
if (ts.isObjectBindingPattern(name) || ts.isArrayBindingPattern(name)) {
|
|
1219
|
+
return name.elements.flatMap(element => ts.isOmittedExpression(element) ? [] : bindingNames(element.name));
|
|
1220
|
+
}
|
|
1221
|
+
return [];
|
|
1222
|
+
}
|
|
1223
|
+
function munApiBindings(file) {
|
|
1224
|
+
const state = new Set();
|
|
1225
|
+
const view = new Set();
|
|
1226
|
+
const namespaces = new Set();
|
|
1227
|
+
let blockedState = false;
|
|
1228
|
+
let blockedView = false;
|
|
1229
|
+
for (const statement of file.statements) {
|
|
1230
|
+
if (ts.isImportDeclaration(statement) && ts.isStringLiteral(statement.moduleSpecifier)) {
|
|
1231
|
+
const mun = isMunPackage(statement.moduleSpecifier.text);
|
|
1232
|
+
const clause = statement.importClause;
|
|
1233
|
+
if (clause?.name) {
|
|
1234
|
+
if (!mun && clause.name.text === "State")
|
|
1235
|
+
blockedState = true;
|
|
1236
|
+
if (!mun && clause.name.text === "view")
|
|
1237
|
+
blockedView = true;
|
|
1238
|
+
}
|
|
1239
|
+
const bindings = clause?.namedBindings;
|
|
1240
|
+
if (bindings && ts.isNamespaceImport(bindings)) {
|
|
1241
|
+
if (mun)
|
|
1242
|
+
namespaces.add(bindings.name.text);
|
|
1243
|
+
continue;
|
|
1244
|
+
}
|
|
1245
|
+
if (bindings && ts.isNamedImports(bindings)) {
|
|
1246
|
+
for (const element of bindings.elements) {
|
|
1247
|
+
const imported = element.propertyName?.text ?? element.name.text;
|
|
1248
|
+
const local = element.name.text;
|
|
1249
|
+
if (mun && imported === "State")
|
|
1250
|
+
state.add(local);
|
|
1251
|
+
else if (!mun && local === "State")
|
|
1252
|
+
blockedState = true;
|
|
1253
|
+
if (mun && imported === "view")
|
|
1254
|
+
view.add(local);
|
|
1255
|
+
else if (!mun && local === "view")
|
|
1256
|
+
blockedView = true;
|
|
1257
|
+
}
|
|
1258
|
+
}
|
|
1259
|
+
continue;
|
|
1260
|
+
}
|
|
1261
|
+
const names = [];
|
|
1262
|
+
if ((ts.isFunctionDeclaration(statement) || ts.isClassDeclaration(statement)) && statement.name)
|
|
1263
|
+
names.push(statement.name.text);
|
|
1264
|
+
if (ts.isVariableStatement(statement)) {
|
|
1265
|
+
for (const declaration of statement.declarationList.declarations)
|
|
1266
|
+
names.push(...bindingNames(declaration.name));
|
|
1267
|
+
}
|
|
1268
|
+
if (names.includes("State"))
|
|
1269
|
+
blockedState = true;
|
|
1270
|
+
if (names.includes("view"))
|
|
1271
|
+
blockedView = true;
|
|
1272
|
+
}
|
|
1273
|
+
return { state, view, namespaces, blockedState, blockedView };
|
|
1274
|
+
}
|
|
1275
|
+
function unwrapTsExpression(expression) {
|
|
1276
|
+
let current = expression;
|
|
1277
|
+
while (ts.isParenthesizedExpression(current)
|
|
1278
|
+
|| ts.isAsExpression(current)
|
|
1279
|
+
|| ts.isTypeAssertionExpression(current)
|
|
1280
|
+
|| ts.isNonNullExpression(current)
|
|
1281
|
+
|| ts.isSatisfiesExpression(current)) {
|
|
1282
|
+
current = current.expression;
|
|
1283
|
+
}
|
|
1284
|
+
return current;
|
|
1285
|
+
}
|
|
1286
|
+
function isMunApiCall(call, api, bindings) {
|
|
1287
|
+
const expression = unwrapTsExpression(call.expression);
|
|
1288
|
+
const named = api === "State" ? bindings.state : bindings.view;
|
|
1289
|
+
const blocked = api === "State" ? bindings.blockedState : bindings.blockedView;
|
|
1290
|
+
if (ts.isIdentifier(expression)) {
|
|
1291
|
+
if (named.has(expression.text))
|
|
1292
|
+
return true;
|
|
1293
|
+
// `.mun.ts` supports the canonical names without an explicit import; do
|
|
1294
|
+
// not claim them when the file has provided an unrelated binding.
|
|
1295
|
+
return expression.text === api && !blocked && named.size === 0;
|
|
1296
|
+
}
|
|
1297
|
+
if (ts.isPropertyAccessExpression(expression)
|
|
1298
|
+
&& expression.name.text === api
|
|
1299
|
+
&& ts.isIdentifier(expression.expression)
|
|
1300
|
+
&& bindings.namespaces.has(expression.expression.text))
|
|
1301
|
+
return true;
|
|
1302
|
+
return false;
|
|
1303
|
+
}
|
|
1304
|
+
function collectTopLevelStates(file, bindings) {
|
|
1305
|
+
const states = [];
|
|
1306
|
+
for (const statement of file.statements) {
|
|
1307
|
+
if (!ts.isVariableStatement(statement))
|
|
1308
|
+
continue;
|
|
1309
|
+
const isConst = (statement.declarationList.flags & ts.NodeFlags.Const) !== 0;
|
|
1310
|
+
const exported = statement.modifiers?.some(modifier => modifier.kind === ts.SyntaxKind.ExportKeyword) ?? false;
|
|
1311
|
+
for (const declaration of statement.declarationList.declarations) {
|
|
1312
|
+
if (!declaration.initializer)
|
|
1313
|
+
continue;
|
|
1314
|
+
const initializer = unwrapTsExpression(declaration.initializer);
|
|
1315
|
+
if (!ts.isCallExpression(initializer) || !isMunApiCall(initializer, "State", bindings))
|
|
1316
|
+
continue;
|
|
1317
|
+
states.push({
|
|
1318
|
+
name: ts.isIdentifier(declaration.name) ? declaration.name.text : undefined,
|
|
1319
|
+
statement,
|
|
1320
|
+
declaration,
|
|
1321
|
+
initializer: declaration.initializer,
|
|
1322
|
+
eligible: isConst && !exported && ts.isIdentifier(declaration.name),
|
|
1323
|
+
});
|
|
1324
|
+
}
|
|
1325
|
+
}
|
|
1326
|
+
return states;
|
|
1327
|
+
}
|
|
1328
|
+
function isNonReferenceIdentifier(node) {
|
|
1329
|
+
const parent = node.parent;
|
|
1330
|
+
if (ts.isPropertyAccessExpression(parent) && parent.name === node)
|
|
1331
|
+
return true;
|
|
1332
|
+
if (ts.isPropertyAssignment(parent) && parent.name === node)
|
|
1333
|
+
return true;
|
|
1334
|
+
if (ts.isMethodDeclaration(parent) && parent.name === node)
|
|
1335
|
+
return true;
|
|
1336
|
+
if (ts.isPropertyDeclaration(parent) && parent.name === node)
|
|
1337
|
+
return true;
|
|
1338
|
+
if (ts.isMethodSignature(parent) && parent.name === node)
|
|
1339
|
+
return true;
|
|
1340
|
+
if (ts.isPropertySignature(parent) && parent.name === node)
|
|
1341
|
+
return true;
|
|
1342
|
+
if (ts.isVariableDeclaration(parent) && parent.name === node)
|
|
1343
|
+
return true;
|
|
1344
|
+
if (ts.isParameter(parent) && parent.name === node)
|
|
1345
|
+
return true;
|
|
1346
|
+
if (ts.isBindingElement(parent) && parent.name === node)
|
|
1347
|
+
return true;
|
|
1348
|
+
if (ts.isFunctionDeclaration(parent) && parent.name === node)
|
|
1349
|
+
return true;
|
|
1350
|
+
if (ts.isClassDeclaration(parent) && parent.name === node)
|
|
1351
|
+
return true;
|
|
1352
|
+
if (ts.isImportSpecifier(parent) || ts.isImportClause(parent) || ts.isNamespaceImport(parent))
|
|
1353
|
+
return true;
|
|
1354
|
+
return false;
|
|
1355
|
+
}
|
|
1356
|
+
function directBlockBindings(node) {
|
|
1357
|
+
const bindings = new Set();
|
|
1358
|
+
for (const statement of node.statements) {
|
|
1359
|
+
if (ts.isVariableStatement(statement)) {
|
|
1360
|
+
for (const declaration of statement.declarationList.declarations) {
|
|
1361
|
+
for (const name of bindingNames(declaration.name))
|
|
1362
|
+
bindings.add(name);
|
|
1363
|
+
}
|
|
1364
|
+
}
|
|
1365
|
+
else if ((ts.isFunctionDeclaration(statement) || ts.isClassDeclaration(statement)) && statement.name) {
|
|
1366
|
+
bindings.add(statement.name.text);
|
|
1367
|
+
}
|
|
1368
|
+
}
|
|
1369
|
+
return bindings;
|
|
1370
|
+
}
|
|
1371
|
+
function referencedStateNames(root, stateNames, skipped = new Set()) {
|
|
1372
|
+
const result = new Set();
|
|
1373
|
+
const visit = (node, shadowed) => {
|
|
1374
|
+
if (skipped.has(node))
|
|
1375
|
+
return;
|
|
1376
|
+
if (ts.isIdentifier(node) && stateNames.has(node.text) && !shadowed.has(node.text) && !isNonReferenceIdentifier(node))
|
|
1377
|
+
result.add(node.text);
|
|
1378
|
+
if (ts.isArrowFunction(node) || ts.isFunctionExpression(node) || ts.isFunctionDeclaration(node) || ts.isMethodDeclaration(node)) {
|
|
1379
|
+
const local = new Set(shadowed);
|
|
1380
|
+
for (const parameter of node.parameters)
|
|
1381
|
+
for (const name of bindingNames(parameter.name))
|
|
1382
|
+
local.add(name);
|
|
1383
|
+
if (ts.isFunctionDeclaration(node) && node.name)
|
|
1384
|
+
local.add(node.name.text);
|
|
1385
|
+
if (node.body)
|
|
1386
|
+
visit(node.body, local);
|
|
1387
|
+
return;
|
|
1388
|
+
}
|
|
1389
|
+
if (ts.isBlock(node)) {
|
|
1390
|
+
const local = new Set(shadowed);
|
|
1391
|
+
for (const name of directBlockBindings(node))
|
|
1392
|
+
local.add(name);
|
|
1393
|
+
ts.forEachChild(node, child => visit(child, local));
|
|
1394
|
+
return;
|
|
1395
|
+
}
|
|
1396
|
+
if (ts.isCatchClause(node)) {
|
|
1397
|
+
const local = new Set(shadowed);
|
|
1398
|
+
if (node.variableDeclaration)
|
|
1399
|
+
for (const name of bindingNames(node.variableDeclaration.name))
|
|
1400
|
+
local.add(name);
|
|
1401
|
+
visit(node.block, local);
|
|
1402
|
+
return;
|
|
1403
|
+
}
|
|
1404
|
+
ts.forEachChild(node, child => visit(child, shadowed));
|
|
1405
|
+
};
|
|
1406
|
+
visit(root, new Set());
|
|
1407
|
+
return result;
|
|
1408
|
+
}
|
|
1409
|
+
function collectMunViewCalls(file, bindings) {
|
|
1410
|
+
const calls = [];
|
|
1411
|
+
const visit = (node) => {
|
|
1412
|
+
if (ts.isCallExpression(node) && isMunApiCall(node, "view", bindings)) {
|
|
1413
|
+
calls.push(node);
|
|
1414
|
+
return;
|
|
1415
|
+
}
|
|
1416
|
+
ts.forEachChild(node, visit);
|
|
1417
|
+
};
|
|
1418
|
+
visit(file);
|
|
1419
|
+
return calls.sort((left, right) => left.getStart(file) - right.getStart(file));
|
|
1420
|
+
}
|
|
1421
|
+
function stateDependencies(state, stateNames) {
|
|
1422
|
+
return referencedStateNames(state.initializer, stateNames);
|
|
1423
|
+
}
|
|
1424
|
+
function importedMunValueBindings(file) {
|
|
1425
|
+
const values = new Set();
|
|
1426
|
+
const namespaces = new Set();
|
|
1427
|
+
for (const statement of file.statements) {
|
|
1428
|
+
if (!ts.isImportDeclaration(statement) || !ts.isStringLiteral(statement.moduleSpecifier) || !isMunPackage(statement.moduleSpecifier.text))
|
|
1429
|
+
continue;
|
|
1430
|
+
const clause = statement.importClause;
|
|
1431
|
+
if (!clause || clause.isTypeOnly)
|
|
1432
|
+
continue;
|
|
1433
|
+
if (clause.name)
|
|
1434
|
+
values.add(clause.name.text);
|
|
1435
|
+
const named = clause.namedBindings;
|
|
1436
|
+
if (named && ts.isNamespaceImport(named))
|
|
1437
|
+
namespaces.add(named.name.text);
|
|
1438
|
+
if (named && ts.isNamedImports(named)) {
|
|
1439
|
+
for (const element of named.elements)
|
|
1440
|
+
if (!element.isTypeOnly)
|
|
1441
|
+
values.add(element.name.text);
|
|
1442
|
+
}
|
|
1443
|
+
}
|
|
1444
|
+
return { values, namespaces };
|
|
1445
|
+
}
|
|
1446
|
+
const compilerPureCallNames = new Set([
|
|
1447
|
+
"String", "Number", "Boolean", "BigInt",
|
|
1448
|
+
"namedArguments", "overloadClosure", "resolveBuilderInput", "Element",
|
|
1449
|
+
]);
|
|
1450
|
+
const compilerAnimationFactoryNames = new Set([
|
|
1451
|
+
"linear", "easeIn", "easeOut", "easeInOut", "spring",
|
|
1452
|
+
"interactiveSpring", "smooth", "snappy", "bouncy",
|
|
1453
|
+
]);
|
|
1454
|
+
const compilerAnimationTransformNames = new Set(["delay", "speed", "repeatCount", "repeatForever"]);
|
|
1455
|
+
function isProvenAnimationExpression(expression, munValues) {
|
|
1456
|
+
const value = unwrapTsExpression(expression);
|
|
1457
|
+
if (!ts.isCallExpression(value))
|
|
1458
|
+
return false;
|
|
1459
|
+
const callee = unwrapTsExpression(value.expression);
|
|
1460
|
+
if (!ts.isPropertyAccessExpression(callee))
|
|
1461
|
+
return false;
|
|
1462
|
+
const owner = unwrapTsExpression(callee.expression);
|
|
1463
|
+
if (compilerAnimationFactoryNames.has(callee.name.text))
|
|
1464
|
+
return ts.isIdentifier(owner) && munValues.has(owner.text);
|
|
1465
|
+
return compilerAnimationTransformNames.has(callee.name.text) && isProvenAnimationExpression(owner, munValues);
|
|
1466
|
+
}
|
|
1467
|
+
function isProvenAnimationMember(expression, munValues) {
|
|
1468
|
+
const owner = unwrapTsExpression(expression.expression);
|
|
1469
|
+
if (compilerAnimationFactoryNames.has(expression.name.text))
|
|
1470
|
+
return ts.isIdentifier(owner) && munValues.has(owner.text);
|
|
1471
|
+
return compilerAnimationTransformNames.has(expression.name.text) && isProvenAnimationExpression(owner, munValues);
|
|
1472
|
+
}
|
|
1473
|
+
function valueBindingNames(root) {
|
|
1474
|
+
const names = new Set();
|
|
1475
|
+
const addBinding = (name) => {
|
|
1476
|
+
for (const value of bindingNames(name))
|
|
1477
|
+
names.add(value);
|
|
1478
|
+
};
|
|
1479
|
+
const visit = (node) => {
|
|
1480
|
+
if (ts.isVariableDeclaration(node) || ts.isParameter(node))
|
|
1481
|
+
addBinding(node.name);
|
|
1482
|
+
else if ((ts.isFunctionDeclaration(node) || ts.isClassDeclaration(node) || ts.isEnumDeclaration(node)) && node.name)
|
|
1483
|
+
names.add(node.name.text);
|
|
1484
|
+
else if (ts.isCatchClause(node) && node.variableDeclaration)
|
|
1485
|
+
addBinding(node.variableDeclaration.name);
|
|
1486
|
+
else if (ts.isImportClause(node) && node.name && !node.isTypeOnly)
|
|
1487
|
+
names.add(node.name.text);
|
|
1488
|
+
else if (ts.isNamespaceImport(node))
|
|
1489
|
+
names.add(node.name.text);
|
|
1490
|
+
else if (ts.isImportSpecifier(node) && !node.isTypeOnly)
|
|
1491
|
+
names.add(node.name.text);
|
|
1492
|
+
ts.forEachChild(node, visit);
|
|
1493
|
+
};
|
|
1494
|
+
visit(root);
|
|
1495
|
+
return names;
|
|
1496
|
+
}
|
|
1497
|
+
function isProvenMunViewExpression(expression, munValues, munNamespaces) {
|
|
1498
|
+
const value = unwrapTsExpression(expression);
|
|
1499
|
+
if (!ts.isCallExpression(value))
|
|
1500
|
+
return false;
|
|
1501
|
+
const callee = unwrapTsExpression(value.expression);
|
|
1502
|
+
if (ts.isIdentifier(callee))
|
|
1503
|
+
return munValues.has(callee.text) && canonicalInitializerSymbols.has(callee.text);
|
|
1504
|
+
if (!ts.isPropertyAccessExpression(callee))
|
|
1505
|
+
return false;
|
|
1506
|
+
const owner = unwrapTsExpression(callee.expression);
|
|
1507
|
+
if (staticModifierNames.has(callee.name.text))
|
|
1508
|
+
return isProvenMunViewExpression(owner, munValues, munNamespaces);
|
|
1509
|
+
return ts.isIdentifier(owner)
|
|
1510
|
+
&& munNamespaces.has(owner.text)
|
|
1511
|
+
&& canonicalInitializerSymbols.has(callee.name.text);
|
|
1512
|
+
}
|
|
1513
|
+
/**
|
|
1514
|
+
* Prove a deliberately small closed world for State reads. A false result is
|
|
1515
|
+
* not an error; it simply keeps runtime dependency discovery enabled. This
|
|
1516
|
+
* avoids unsoundly skipping a shared/module State that is read through an
|
|
1517
|
+
* opaque helper, getter, or other user-controlled call.
|
|
1518
|
+
*/
|
|
1519
|
+
function hasCompleteStaticStateDependencies(root, ownedStateNames, allStateNames, munValues, munNamespaces, shadowedPureCalls = new Set()) {
|
|
1520
|
+
const directlyReferenced = referencedStateNames(root, allStateNames);
|
|
1521
|
+
if ([...directlyReferenced].some(name => !ownedStateNames.has(name)))
|
|
1522
|
+
return false;
|
|
1523
|
+
const localBindings = valueBindingNames(root);
|
|
1524
|
+
const pureCallAllowed = (name) => compilerPureCallNames.has(name)
|
|
1525
|
+
&& !shadowedPureCalls.has(name)
|
|
1526
|
+
&& !localBindings.has(name);
|
|
1527
|
+
let safe = true;
|
|
1528
|
+
const visit = (node) => {
|
|
1529
|
+
if (!safe)
|
|
1530
|
+
return;
|
|
1531
|
+
if (ts.isPropertyAccessExpression(node)) {
|
|
1532
|
+
const expression = unwrapTsExpression(node.expression);
|
|
1533
|
+
const ownedStateValue = node.name.text === "value" && ts.isIdentifier(expression) && ownedStateNames.has(expression.text);
|
|
1534
|
+
const munNamespaceMember = ts.isIdentifier(expression) && munNamespaces.has(expression.text);
|
|
1535
|
+
const provenViewModifier = staticModifierNames.has(node.name.text)
|
|
1536
|
+
&& isProvenMunViewExpression(node.expression, munValues, munNamespaces);
|
|
1537
|
+
const provenAnimationMember = isProvenAnimationMember(node, munValues);
|
|
1538
|
+
// Modifier names alone are not enough: a user object may expose an
|
|
1539
|
+
// `opacity()`/`padding()` method. Only a chain rooted in an imported Mun
|
|
1540
|
+
// View constructor is admitted into the static dependency proof. Immutable
|
|
1541
|
+
// Animation factory/configuration chains are also closed and pure.
|
|
1542
|
+
if (!ownedStateValue && !munNamespaceMember && !provenViewModifier && !provenAnimationMember) {
|
|
1543
|
+
safe = false;
|
|
1544
|
+
return;
|
|
1545
|
+
}
|
|
1546
|
+
}
|
|
1547
|
+
if (ts.isElementAccessExpression(node)) {
|
|
1548
|
+
safe = false;
|
|
1549
|
+
return;
|
|
1550
|
+
}
|
|
1551
|
+
if (ts.isCallExpression(node)) {
|
|
1552
|
+
const callee = unwrapTsExpression(node.expression);
|
|
1553
|
+
if (ts.isIdentifier(callee)) {
|
|
1554
|
+
if (!munValues.has(callee.text) && !pureCallAllowed(callee.text)) {
|
|
1555
|
+
safe = false;
|
|
1556
|
+
return;
|
|
1557
|
+
}
|
|
1558
|
+
}
|
|
1559
|
+
else if (ts.isPropertyAccessExpression(callee)) {
|
|
1560
|
+
const owner = unwrapTsExpression(callee.expression);
|
|
1561
|
+
const namespaceCall = ts.isIdentifier(owner) && munNamespaces.has(owner.text);
|
|
1562
|
+
const modifierCall = staticModifierNames.has(callee.name.text)
|
|
1563
|
+
&& isProvenMunViewExpression(owner, munValues, munNamespaces);
|
|
1564
|
+
const animationCall = isProvenAnimationMember(callee, munValues);
|
|
1565
|
+
if (!namespaceCall && !modifierCall && !animationCall) {
|
|
1566
|
+
safe = false;
|
|
1567
|
+
return;
|
|
1568
|
+
}
|
|
1569
|
+
}
|
|
1570
|
+
else {
|
|
1571
|
+
safe = false;
|
|
1572
|
+
return;
|
|
1573
|
+
}
|
|
1574
|
+
}
|
|
1575
|
+
ts.forEachChild(node, visit);
|
|
1576
|
+
};
|
|
1577
|
+
visit(root);
|
|
1578
|
+
return safe;
|
|
1579
|
+
}
|
|
1580
|
+
function transitiveStateClosure(initial, eligible, dependencies) {
|
|
1581
|
+
const result = new Set();
|
|
1582
|
+
const queue = [...initial];
|
|
1583
|
+
while (queue.length > 0) {
|
|
1584
|
+
const name = queue.pop();
|
|
1585
|
+
if (!eligible.has(name) || result.has(name))
|
|
1586
|
+
continue;
|
|
1587
|
+
result.add(name);
|
|
1588
|
+
for (const dependency of dependencies.get(name) ?? [])
|
|
1589
|
+
queue.push(dependency);
|
|
1590
|
+
}
|
|
1591
|
+
return result;
|
|
1592
|
+
}
|
|
1593
|
+
function lowerTopLevelState(source) {
|
|
1594
|
+
// Aliases still contain the exported name in their import declaration
|
|
1595
|
+
// (`State as LocalState`), so this is a safe conservative preflight.
|
|
1596
|
+
if (!/\bState\b/.test(source))
|
|
1597
|
+
return source;
|
|
1598
|
+
const file = ts.createSourceFile("mun-state.ts", source, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS);
|
|
1599
|
+
const bindings = munApiBindings(file);
|
|
1600
|
+
const munValues = importedMunValueBindings(file);
|
|
1601
|
+
const fileValueBindings = valueBindingNames(file);
|
|
1602
|
+
const states = collectTopLevelStates(file, bindings);
|
|
1603
|
+
const eligibleStates = states.filter((state) => state.eligible && state.name !== undefined);
|
|
1604
|
+
if (eligibleStates.length === 0)
|
|
1605
|
+
return source;
|
|
1606
|
+
const byName = new Map(eligibleStates.map(state => [state.name, state]));
|
|
1607
|
+
const eligibleNames = new Set(byName.keys());
|
|
1608
|
+
const allNames = new Set(states.flatMap(state => state.name ? [state.name] : []));
|
|
1609
|
+
const dependencies = new Map();
|
|
1610
|
+
for (const state of eligibleStates)
|
|
1611
|
+
dependencies.set(state.name, stateDependencies(state, allNames));
|
|
1612
|
+
const views = collectMunViewCalls(file, bindings);
|
|
1613
|
+
if (views.length === 0)
|
|
1614
|
+
return source;
|
|
1615
|
+
const viewSet = new Set(views);
|
|
1616
|
+
// Any reference outside a Mun view keeps that State module-scoped. This
|
|
1617
|
+
// includes helper functions and ineligible/exported/mutable State factories.
|
|
1618
|
+
const directOutside = new Set();
|
|
1619
|
+
const stateDeclarations = new Set(states.map(state => state.declaration));
|
|
1620
|
+
for (const statement of file.statements) {
|
|
1621
|
+
if (ts.isVariableStatement(statement)) {
|
|
1622
|
+
for (const declaration of statement.declarationList.declarations) {
|
|
1623
|
+
if (stateDeclarations.has(declaration)) {
|
|
1624
|
+
const state = states.find(item => item.declaration === declaration);
|
|
1625
|
+
if (state && !state.eligible) {
|
|
1626
|
+
for (const dependency of referencedStateNames(state.initializer, allNames))
|
|
1627
|
+
directOutside.add(dependency);
|
|
1628
|
+
}
|
|
1629
|
+
continue;
|
|
1630
|
+
}
|
|
1631
|
+
if (declaration.initializer)
|
|
1632
|
+
for (const name of referencedStateNames(declaration.initializer, allNames, viewSet))
|
|
1633
|
+
directOutside.add(name);
|
|
1634
|
+
}
|
|
1635
|
+
continue;
|
|
1636
|
+
}
|
|
1637
|
+
for (const name of referencedStateNames(statement, allNames, viewSet))
|
|
1638
|
+
directOutside.add(name);
|
|
1639
|
+
}
|
|
1640
|
+
const outside = transitiveStateClosure(directOutside, eligibleNames, dependencies);
|
|
1641
|
+
const owners = new Map();
|
|
1642
|
+
const statesByView = new Map();
|
|
1643
|
+
views.forEach((view, index) => {
|
|
1644
|
+
const direct = referencedStateNames(view.arguments[0] ?? view, allNames);
|
|
1645
|
+
const closure = transitiveStateClosure(direct, eligibleNames, dependencies);
|
|
1646
|
+
for (const name of closure) {
|
|
1647
|
+
const set = owners.get(name) ?? new Set();
|
|
1648
|
+
set.add(index);
|
|
1649
|
+
owners.set(name, set);
|
|
1650
|
+
}
|
|
1651
|
+
});
|
|
1652
|
+
for (const state of eligibleStates) {
|
|
1653
|
+
const stateOwners = owners.get(state.name);
|
|
1654
|
+
if (outside.has(state.name) || stateOwners?.size !== 1)
|
|
1655
|
+
continue;
|
|
1656
|
+
const owner = [...stateOwners][0];
|
|
1657
|
+
const list = statesByView.get(owner) ?? [];
|
|
1658
|
+
list.push(state);
|
|
1659
|
+
statesByView.set(owner, list);
|
|
1660
|
+
}
|
|
1661
|
+
if (statesByView.size === 0)
|
|
1662
|
+
return source;
|
|
1663
|
+
const hoisted = new Set([...statesByView.values()].flat().map(state => state.declaration));
|
|
1664
|
+
const hoistedSpans = [];
|
|
1665
|
+
const removalEdits = [];
|
|
1666
|
+
// Remove each hoisted declarator individually instead of rewriting the whole
|
|
1667
|
+
// variable statement from original source text. A whole-statement rewrite
|
|
1668
|
+
// clobbers any nested view() replacement inside a preserved sibling
|
|
1669
|
+
// declarator (e.g. `const count = State(0), app = view(() => Text(count))`).
|
|
1670
|
+
for (const statement of file.statements) {
|
|
1671
|
+
if (!ts.isVariableStatement(statement))
|
|
1672
|
+
continue;
|
|
1673
|
+
const declarations = statement.declarationList.declarations;
|
|
1674
|
+
const removedIndexes = declarations.map((declaration, index) => hoisted.has(declaration) ? index : -1).filter(index => index >= 0);
|
|
1675
|
+
if (removedIndexes.length === 0)
|
|
1676
|
+
continue;
|
|
1677
|
+
const hasPreserved = declarations.some(declaration => !hoisted.has(declaration));
|
|
1678
|
+
if (!hasPreserved) {
|
|
1679
|
+
removalEdits.push({ start: statement.getStart(file), end: statement.end, replacement: "" });
|
|
1680
|
+
for (const declaration of declarations) {
|
|
1681
|
+
if (!hoisted.has(declaration))
|
|
1682
|
+
continue;
|
|
1683
|
+
hoistedSpans.push({ start: declaration.getStart(file), end: declaration.end });
|
|
1684
|
+
}
|
|
1685
|
+
continue;
|
|
1686
|
+
}
|
|
1687
|
+
for (const index of removedIndexes) {
|
|
1688
|
+
const declaration = declarations[index];
|
|
1689
|
+
let start = declaration.getStart(file);
|
|
1690
|
+
let end = declaration.end;
|
|
1691
|
+
const trailingSeparator = /^\s*,/.exec(source.slice(end));
|
|
1692
|
+
if (trailingSeparator)
|
|
1693
|
+
end += trailingSeparator[0].length;
|
|
1694
|
+
else {
|
|
1695
|
+
const leadingSeparator = /,\s*$/.exec(source.slice(0, start));
|
|
1696
|
+
if (leadingSeparator)
|
|
1697
|
+
start -= leadingSeparator[0].length;
|
|
1698
|
+
}
|
|
1699
|
+
removalEdits.push({ start, end, replacement: "" });
|
|
1700
|
+
hoistedSpans.push({ start: declaration.getStart(file), end: declaration.end });
|
|
1701
|
+
}
|
|
1702
|
+
}
|
|
1703
|
+
// A view replacement lexically inside a removed State declarator cannot be
|
|
1704
|
+
// applied safely alongside the removal; leave that call on the runtime path.
|
|
1705
|
+
const viewEdits = [...statesByView]
|
|
1706
|
+
.flatMap(([viewIndex]) => {
|
|
1707
|
+
const call = views[viewIndex];
|
|
1708
|
+
if (!call)
|
|
1709
|
+
return [];
|
|
1710
|
+
if (hoistedSpans.some(span => call.getStart(file) < span.end && span.start < call.end))
|
|
1711
|
+
return [];
|
|
1712
|
+
return [viewIndex];
|
|
1713
|
+
})
|
|
1714
|
+
.map(viewIndex => {
|
|
1715
|
+
const call = views[viewIndex];
|
|
1716
|
+
const argument = call.arguments[0];
|
|
1717
|
+
if (!argument || call.arguments.length !== 1)
|
|
1718
|
+
return undefined;
|
|
1719
|
+
const callee = call.expression.getText(file);
|
|
1720
|
+
const body = argument.getText(file);
|
|
1721
|
+
const unwrapped = unwrapTsExpression(argument);
|
|
1722
|
+
const functionBody = ts.isArrowFunction(unwrapped) || ts.isFunctionExpression(unwrapped);
|
|
1723
|
+
const hasProps = functionBody && unwrapped.parameters.length > 0;
|
|
1724
|
+
const names = statesByView.get(viewIndex).map(state => state.name);
|
|
1725
|
+
const declarations = statesByView.get(viewIndex)
|
|
1726
|
+
.sort((left, right) => left.declaration.getStart(file) - right.declaration.getStart(file))
|
|
1727
|
+
.map(state => `const ${state.name} = ${state.initializer.getText(file)};`)
|
|
1728
|
+
.join(" ");
|
|
1729
|
+
const renderedBody = functionBody ? `((${body})(${hasProps ? "props" : ""}))` : `(${body})`;
|
|
1730
|
+
const bodyParameters = hasProps ? `({ ${names.join(", ")} }, props)` : `({ ${names.join(", ")} })`;
|
|
1731
|
+
const dependencyParameters = `({ ${names.join(", ")} })`;
|
|
1732
|
+
const ownedNames = new Set(names);
|
|
1733
|
+
const dependenciesComplete = !hasProps && hasCompleteStaticStateDependencies(argument, ownedNames, allNames, munValues.values, munValues.namespaces, fileValueBindings);
|
|
1734
|
+
const completeness = dependenciesComplete ? `, dependenciesComplete: true` : "";
|
|
1735
|
+
const replacement = `${callee}({ state: () => { ${declarations} return { ${names.join(", ")} } }, dependencies: ${dependencyParameters} => [${names.join(", ")}]${completeness}, body: ${bodyParameters} => ${renderedBody} })`;
|
|
1736
|
+
return { start: call.getStart(file), end: call.end, replacement };
|
|
1737
|
+
})
|
|
1738
|
+
.filter((edit) => edit !== undefined);
|
|
1739
|
+
const edits = [...removalEdits, ...viewEdits].sort((left, right) => right.start - left.start);
|
|
1740
|
+
let result = source;
|
|
1741
|
+
for (const edit of edits)
|
|
1742
|
+
result = result.slice(0, edit.start) + edit.replacement + result.slice(edit.end);
|
|
1743
|
+
return result;
|
|
1744
|
+
}
|
|
1745
|
+
/**
|
|
1746
|
+
* `.mun` modules resolve built-ins statically: every free identifier of the
|
|
1747
|
+
* lowered module is looked up in the shared registry after lexical scoping, so
|
|
1748
|
+
* local declarations and explicit imports shadow built-ins and only the
|
|
1749
|
+
* built-ins actually read become (tree-shakable) named imports.
|
|
1750
|
+
*/
|
|
1751
|
+
function importMunBuiltins(source, lowered, fileName, externalScope) {
|
|
1752
|
+
const file = ts.createSourceFile(fileName + ".ts", lowered, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS);
|
|
1753
|
+
// A module TypeScript cannot parse is reported by validateWebLowering with
|
|
1754
|
+
// the parser's own message; scope analysis of a broken tree would only add noise.
|
|
1755
|
+
if ((file.parseDiagnostics ?? []).length > 0)
|
|
1756
|
+
return lowered;
|
|
1757
|
+
const resolution = resolveMunBuiltins(file);
|
|
1758
|
+
const unresolved = externalScope ? undefined : resolution.unresolved[0];
|
|
1759
|
+
if (unresolved) {
|
|
1760
|
+
const position = file.getLineAndCharacterOfPosition(unresolved.offset);
|
|
1761
|
+
const mapped = mapGeneratedPosition(createMunSourceMap(source, lowered, fileName), { line: position.line + 1, column: position.character + 1 });
|
|
1762
|
+
const offset = source.split("\n").slice(0, mapped.line - 1).reduce((sum, line) => sum + line.length + 1, 0) + mapped.column - 1;
|
|
1763
|
+
throw Object.assign(new SyntaxError(unresolved.message), { offset, code: "MUN_SYNTAX" });
|
|
1764
|
+
}
|
|
1765
|
+
let result = lowered;
|
|
1766
|
+
for (const [module, names] of [...resolution.imports].reverse())
|
|
1767
|
+
result = addNamedImports(result, module, names);
|
|
1768
|
+
return result;
|
|
1769
|
+
}
|
|
1770
|
+
function ensureImports(source, includeViewBuiltins = false) {
|
|
1771
|
+
const callableRequired = ["defineView", "initializer", "resolveBuilderInput", "namedArguments", "overloadClosure", "viewFragment", "withAnimation", "withTransaction", "Binding", "State", "Element", "modifiedContent", "modifiedContentCompiled", "compiledTemplate", "defineCompiledTemplate", "Observable", "environmentValue"]
|
|
1772
|
+
.filter(name => new RegExp(`\\b${name}(?:<[^()\\n]*>)?\\s*\\(`).test(source) || (name === "defineView" && /const\s+[A-Z]\w*\s*=\s*defineView/.test(source)));
|
|
1773
|
+
const valueRequired = ["Transition", "Animation", "ContentTransition", "SymbolEffect", "Color", "Font"].filter(name => {
|
|
1774
|
+
if (!new RegExp(`\\b${name}\\s*\\.`).test(source))
|
|
1775
|
+
return false;
|
|
1776
|
+
return !new RegExp(`\\b(?:const|let|var|class|function|enum|namespace)\\s+${name}\\b`).test(source);
|
|
1777
|
+
});
|
|
1778
|
+
const viewRequired = includeViewBuiltins
|
|
1779
|
+
? [...canonicalInitializerSymbols.keys()].filter(name => {
|
|
1780
|
+
if (!new RegExp(`\\b${name}\\s*\\(`).test(source))
|
|
1781
|
+
return false;
|
|
1782
|
+
return !new RegExp(`\\b(?:const|let|var|class|function|enum|namespace)\\s+${name}\\b`).test(source);
|
|
1783
|
+
})
|
|
1784
|
+
: [];
|
|
1785
|
+
const required = [...new Set([...callableRequired, ...valueRequired, ...viewRequired])];
|
|
1786
|
+
let result = source;
|
|
1787
|
+
const internalRequired = ["compiledCollectionContent", "mapStateArrayData"].filter(name => new RegExp(`\\b${name}\\s*\\(`).test(source));
|
|
1788
|
+
if (required.length === 0 && internalRequired.length === 0)
|
|
1789
|
+
return result;
|
|
1790
|
+
const imports = [...result.matchAll(/import\s*\{([^}]*)\}\s*from\s*(["'])(@mun-ui\/core\/compat|@mun-ui\/react)\2[\t ]*;?/g)];
|
|
1791
|
+
// Respect local named bindings from every entrypoint, including @mun-ui/core
|
|
1792
|
+
// and @mun-ui/ui, so adding implicit helpers cannot duplicate explicit imports.
|
|
1793
|
+
const imported = new Set([...result.matchAll(/import\s*\{([^}]*)\}\s*from\s*["'][^"']+["']/g)]
|
|
1794
|
+
.flatMap(match => match[1].split(",").map(value => value.trim()).filter(value => value && !/^type\s/.test(value))
|
|
1795
|
+
.map(value => value.split(/\s+as\s+/).at(-1))));
|
|
1796
|
+
const missing = required.filter(name => !imported.has(name));
|
|
1797
|
+
if (missing.length > 0) {
|
|
1798
|
+
const existingCore = imports.find(match => match[3] === "@mun-ui/core/compat");
|
|
1799
|
+
if (!existingCore)
|
|
1800
|
+
result = `import { ${missing.join(", ")} } from "@mun-ui/core/compat"\n${result}`;
|
|
1801
|
+
else {
|
|
1802
|
+
const names = existingCore[1].split(",").map(value => value.trim()).filter(Boolean);
|
|
1803
|
+
for (const name of missing)
|
|
1804
|
+
if (!names.includes(name))
|
|
1805
|
+
names.push(name);
|
|
1806
|
+
const replacement = `import { ${names.join(", ")} } from ${existingCore[2]}@mun-ui/core/compat${existingCore[2]}`;
|
|
1807
|
+
result = result.slice(0, existingCore.index) + replacement + result.slice(existingCore.index + existingCore[0].length);
|
|
1808
|
+
}
|
|
1809
|
+
}
|
|
1810
|
+
if (internalRequired.length > 0) {
|
|
1811
|
+
const internalImport = /import\s*\{([^}]*)\}\s*from\s*(["'])@mun-ui\/core\/internal\/runtime\2[\t ]*;?/.exec(result);
|
|
1812
|
+
if (!internalImport)
|
|
1813
|
+
result = `import { ${internalRequired.join(", ")} } from "@mun-ui/core/internal/runtime"\n${result}`;
|
|
1814
|
+
else {
|
|
1815
|
+
const names = internalImport[1].split(",").map(value => value.trim()).filter(Boolean);
|
|
1816
|
+
for (const name of internalRequired)
|
|
1817
|
+
if (!names.includes(name))
|
|
1818
|
+
names.push(name);
|
|
1819
|
+
const replacement = `import { ${names.join(", ")} } from ${internalImport[2]}@mun-ui/core/internal/runtime${internalImport[2]}`;
|
|
1820
|
+
result = result.slice(0, internalImport.index) + replacement + result.slice(internalImport.index + internalImport[0].length);
|
|
1821
|
+
}
|
|
1822
|
+
}
|
|
1823
|
+
return result;
|
|
1824
|
+
}
|
|
1825
|
+
function lowerNamedMunCalls(source, registry = canonicalInitializerSymbols) {
|
|
1826
|
+
// A labeled call must contain a colon. Most host TypeScript modules do not,
|
|
1827
|
+
// so avoid even collecting uppercase call candidates in that common case.
|
|
1828
|
+
if (!source.includes(":"))
|
|
1829
|
+
return source;
|
|
1830
|
+
const candidates = [];
|
|
1831
|
+
for (const match of source.matchAll(/\b(?:[A-Z][A-Za-z0-9_$]*\.)*[A-Z][A-Za-z0-9_$]*\s*\(/g)) {
|
|
1832
|
+
const start = match.index ?? 0;
|
|
1833
|
+
const callee = /^(?:[A-Z][A-Za-z0-9_$]*\.)*[A-Z][A-Za-z0-9_$]*/.exec(match[0])?.[0];
|
|
1834
|
+
if (!callee)
|
|
1835
|
+
continue;
|
|
1836
|
+
const previous = previousSignificantCharacter(source, start);
|
|
1837
|
+
const word = previousWord(source, start);
|
|
1838
|
+
const wordBeforeStar = previous === "*" ? previousWord(source, start - 2) : undefined;
|
|
1839
|
+
if (previous === "." || word === "function" || word === "class" || word === "interface" || word === "type" || word === "new" || wordBeforeStar === "function")
|
|
1840
|
+
continue;
|
|
1841
|
+
const open = source.indexOf("(", start + callee.length);
|
|
1842
|
+
const close = matching(source, open, "(", ")");
|
|
1843
|
+
const argumentSource = source.slice(open + 1, close);
|
|
1844
|
+
if (!splitTopLevel(argumentSource).some(argument => topLevelColon(argument) >= 0))
|
|
1845
|
+
continue;
|
|
1846
|
+
candidates.push({ start, end: close + 1, callee, open, close });
|
|
1847
|
+
}
|
|
1848
|
+
if (candidates.length === 0)
|
|
1849
|
+
return source;
|
|
1850
|
+
if (candidates.length === 1) {
|
|
1851
|
+
const candidate = candidates[0];
|
|
1852
|
+
const value = `${candidate.callee}(${lowerArguments(source.slice(candidate.open + 1, candidate.close), candidate.callee.split(".").at(-1), registry)})`;
|
|
1853
|
+
return source.slice(0, candidate.start) + value + source.slice(candidate.end);
|
|
1854
|
+
}
|
|
1855
|
+
// An outer labeled call owns any nested labeled calls in its arguments.
|
|
1856
|
+
// lowerArguments recursively lowers those isolated expressions, so only
|
|
1857
|
+
// the maximal candidates become edits and no overlapping slices are kept.
|
|
1858
|
+
const maximal = [];
|
|
1859
|
+
const active = [];
|
|
1860
|
+
for (const candidate of candidates) {
|
|
1861
|
+
while (active.length > 0 && candidate.start >= active.at(-1).end)
|
|
1862
|
+
active.pop();
|
|
1863
|
+
if (active.length === 0)
|
|
1864
|
+
maximal.push(candidate);
|
|
1865
|
+
active.push(candidate);
|
|
1866
|
+
}
|
|
1867
|
+
const edits = maximal
|
|
1868
|
+
.map(candidate => ({
|
|
1869
|
+
start: candidate.start,
|
|
1870
|
+
end: candidate.end,
|
|
1871
|
+
value: `${candidate.callee}(${lowerArguments(source.slice(candidate.open + 1, candidate.close), candidate.callee.split(".").at(-1), registry)})`,
|
|
1872
|
+
}))
|
|
1873
|
+
.sort((left, right) => right.start - left.start);
|
|
1874
|
+
let output = source;
|
|
1875
|
+
for (const edit of edits)
|
|
1876
|
+
output = output.slice(0, edit.start) + edit.value + output.slice(edit.end);
|
|
1877
|
+
return output;
|
|
1878
|
+
}
|
|
1879
|
+
/**
|
|
1880
|
+
* `.transition(_:)` takes an AnyTransition written with implicit members:
|
|
1881
|
+
* `.opacity`, `.move(edge: .top)`, `.scale.combined(with: .opacity)`,
|
|
1882
|
+
* `.asymmetric(insertion: .scale, removal: .opacity)`. Resolve the leading
|
|
1883
|
+
* member against `Transition` and drop the labels, so the runtime receives a
|
|
1884
|
+
* real Transition rather than a string it cannot animate.
|
|
1885
|
+
*/
|
|
1886
|
+
function lowerTransitionArgument(value) {
|
|
1887
|
+
const source = value.trim().replace(/^AnyTransition(?=\.)/, "");
|
|
1888
|
+
if (!source.startsWith("."))
|
|
1889
|
+
return value;
|
|
1890
|
+
let output = "Transition";
|
|
1891
|
+
let cursor = 0;
|
|
1892
|
+
while (cursor < source.length) {
|
|
1893
|
+
const member = /^\.([A-Za-z_$][A-Za-z0-9_$]*)/.exec(source.slice(cursor));
|
|
1894
|
+
if (!member)
|
|
1895
|
+
return value;
|
|
1896
|
+
output += member[0];
|
|
1897
|
+
cursor += member[0].length;
|
|
1898
|
+
if (source[cursor] !== "(") {
|
|
1899
|
+
// SwiftUI spells the default scale and blur as properties; the runtime factories are calls.
|
|
1900
|
+
if (member[1] === "scale" || member[1] === "blur")
|
|
1901
|
+
output += "()";
|
|
1902
|
+
continue;
|
|
1903
|
+
}
|
|
1904
|
+
const close = matching(source, cursor, "(", ")");
|
|
1905
|
+
const lowered = splitTopLevel(source.slice(cursor + 1, close)).filter(argument => argument.trim()).map(argument => {
|
|
1906
|
+
const colon = topLevelColon(argument);
|
|
1907
|
+
const label = colon < 0 ? undefined : argument.slice(0, colon).trim();
|
|
1908
|
+
const labeled = label !== undefined && /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(label);
|
|
1909
|
+
const inner = (labeled ? argument.slice(colon + 1) : argument).trim();
|
|
1910
|
+
if (member[1] === "combined" || member[1] === "asymmetric")
|
|
1911
|
+
return lowerTransitionArgument(inner);
|
|
1912
|
+
if (member[1] === "animation") {
|
|
1913
|
+
if (!inner.startsWith("."))
|
|
1914
|
+
return inner;
|
|
1915
|
+
// `.default` is a value; the timing curves are factories with defaulted durations.
|
|
1916
|
+
return /^\.[A-Za-z_$][A-Za-z0-9_$]*$/.test(inner) && inner !== ".default" ? `Animation${inner}()` : `Animation${inner}`;
|
|
1917
|
+
}
|
|
1918
|
+
return /^\.[A-Za-z_$][A-Za-z0-9_$]*$/.test(inner) ? JSON.stringify(inner.slice(1)) : inner;
|
|
1919
|
+
});
|
|
1920
|
+
output += `(${lowered.join(", ")})`;
|
|
1921
|
+
cursor = close + 1;
|
|
1922
|
+
}
|
|
1923
|
+
return output;
|
|
1924
|
+
}
|
|
1925
|
+
/**
|
|
1926
|
+
* SwiftUI modifiers use argument labels even though their JavaScript runtime
|
|
1927
|
+
* implementation ultimately receives positional values or an option record.
|
|
1928
|
+
* Lower those labels before the source reaches TypeScript so authoring syntax
|
|
1929
|
+
* can stay SwiftUI-shaped without teaching TypeScript a second call grammar.
|
|
1930
|
+
*/
|
|
1931
|
+
function lowerNamedModifierCalls(source) {
|
|
1932
|
+
let output = source;
|
|
1933
|
+
let iterations = 0;
|
|
1934
|
+
while (true) {
|
|
1935
|
+
if (++iterations > output.length + 1)
|
|
1936
|
+
throw syntaxError("Mun modifier argument lowering did not advance", 0);
|
|
1937
|
+
let candidate;
|
|
1938
|
+
for (let cursor = 0; cursor < output.length; cursor += 1) {
|
|
1939
|
+
const character = output[cursor];
|
|
1940
|
+
if (character === "\"" || character === "'" || character === "`") {
|
|
1941
|
+
cursor = skipString(output, cursor) - 1;
|
|
1942
|
+
continue;
|
|
1943
|
+
}
|
|
1944
|
+
// Raw HTML may contain closing tags (`</span>`). Treat the complete tag
|
|
1945
|
+
// as an opaque token before the generic slash/regex scanner sees the
|
|
1946
|
+
// closing slash as a regular-expression opener.
|
|
1947
|
+
if (character === "<") {
|
|
1948
|
+
const html = rawHtmlAt(output, cursor);
|
|
1949
|
+
if (html) {
|
|
1950
|
+
cursor = html.end - 1;
|
|
1951
|
+
continue;
|
|
1952
|
+
}
|
|
1953
|
+
}
|
|
1954
|
+
if (character === "/" && (output[cursor + 1] === "/" || output[cursor + 1] === "*")) {
|
|
1955
|
+
cursor = skipComment(output, cursor) - 1;
|
|
1956
|
+
continue;
|
|
1957
|
+
}
|
|
1958
|
+
if (character === "/" && regexCanStart(output, cursor)) {
|
|
1959
|
+
cursor = skipRegex(output, cursor) - 1;
|
|
1960
|
+
continue;
|
|
1961
|
+
}
|
|
1962
|
+
if (character !== ".")
|
|
1963
|
+
continue;
|
|
1964
|
+
const identifier = identifierAt(output, cursor + 1);
|
|
1965
|
+
if (!identifier || !staticModifierNames.has(identifier.name))
|
|
1966
|
+
continue;
|
|
1967
|
+
const open = skipTrivia(output, identifier.end);
|
|
1968
|
+
if (output[open] !== "(")
|
|
1969
|
+
continue;
|
|
1970
|
+
const close = matching(output, open, "(", ")");
|
|
1971
|
+
const argumentsSource = output.slice(open + 1, close);
|
|
1972
|
+
const contentTransitionShorthand = identifier.name === "contentTransition" && /^\s*\./.test(argumentsSource);
|
|
1973
|
+
const argumentsList = splitTopLevel(argumentsSource);
|
|
1974
|
+
const swiftClosure = argumentsList.some(argument => /^\s*\{\s*[A-Za-z_$][A-Za-z0-9_$]*\s+in\b/.test(argument));
|
|
1975
|
+
// A positional implicit member is not valid TypeScript: resolve it
|
|
1976
|
+
// before the TypeScript parser sees .font(.title) or .foregroundStyle(.blue).
|
|
1977
|
+
// Angle members (`.degrees(45)`) and array literals of members (`[.top, .leading]`) too.
|
|
1978
|
+
const implicitMember = argumentsList.some(argument => /^\s*\.[A-Za-z_$][A-Za-z0-9_$]*\s*$/.test(argument) || /^\s*\.(?:degrees|radians)\s*\(/.test(argument) || /^\s*\[\s*\./.test(argument))
|
|
1979
|
+
// `.font(.system(size: 13, weight: .bold))` / `.font(Font.system(size:))`
|
|
1980
|
+
// carry Swift labels inside the member call.
|
|
1981
|
+
|| (identifier.name === "font" && /^\s*(?:Font)?\.system\s*\([^)]*\bsize\s*:/.test(argumentsSource))
|
|
1982
|
+
// `.transition(.move(edge: .top))`, `.transition(.scale.combined(with: .opacity))`
|
|
1983
|
+
|| (identifier.name === "transition" && /^\s*(?:AnyTransition)?\./.test(argumentsSource));
|
|
1984
|
+
if ((!swiftUIModifierLowering(identifier.name) && !swiftClosure && !implicitMember)
|
|
1985
|
+
|| (!swiftClosure && !contentTransitionShorthand && !implicitMember && !argumentsList.some(argument => topLevelColon(argument) >= 0))) {
|
|
1986
|
+
cursor = close;
|
|
1987
|
+
continue;
|
|
1988
|
+
}
|
|
1989
|
+
candidate = { name: identifier.name, open, close };
|
|
1990
|
+
cursor = close;
|
|
1991
|
+
}
|
|
1992
|
+
if (!candidate)
|
|
1993
|
+
return output;
|
|
1994
|
+
const lowering = swiftUIModifierLowering(candidate.name);
|
|
1995
|
+
const entries = splitTopLevel(output.slice(candidate.open + 1, candidate.close)).map(source => {
|
|
1996
|
+
const colon = topLevelColon(source);
|
|
1997
|
+
const label = colon < 0 ? undefined : source.slice(skipTrivia(source, 0), colon).trim();
|
|
1998
|
+
const validLabel = label && /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(label) ? label : undefined;
|
|
1999
|
+
return {
|
|
2000
|
+
label: validLabel,
|
|
2001
|
+
value: (validLabel ? source.slice(colon + 1) : source).trim(),
|
|
2002
|
+
};
|
|
2003
|
+
});
|
|
2004
|
+
const lowerCallback = (value, parameterized) => {
|
|
2005
|
+
const source = value.trim();
|
|
2006
|
+
if (!source.startsWith("{") || matching(source, 0, "{", "}") !== source.length - 1) {
|
|
2007
|
+
return lowerImplicitMemberShorthand(lowerShorthand(source));
|
|
2008
|
+
}
|
|
2009
|
+
const body = source.slice(1, -1).trim();
|
|
2010
|
+
if (parameterized) {
|
|
2011
|
+
const match = /^([A-Za-z_$][A-Za-z0-9_$]*)\s+in\s+([\s\S]*)$/.exec(body);
|
|
2012
|
+
if (match)
|
|
2013
|
+
return `(${match[1]}) => {${lowerRange(match[2])}}`;
|
|
2014
|
+
}
|
|
2015
|
+
return `() => {${lowerRange(body)}}`;
|
|
2016
|
+
};
|
|
2017
|
+
const lowerModifierValue = (value, label) => {
|
|
2018
|
+
if (/^\s*\{\s*[A-Za-z_$][A-Za-z0-9_$]*\s+in\b/.test(value))
|
|
2019
|
+
return lowerCallback(value, true);
|
|
2020
|
+
if (candidate.name === "contentTransition")
|
|
2021
|
+
return lowerContentTransitionArgument(value);
|
|
2022
|
+
if (candidate.name === "transition")
|
|
2023
|
+
return lowerTransitionArgument(value);
|
|
2024
|
+
if (candidate.name === "onTapGesture" && label === "perform")
|
|
2025
|
+
return lowerCallback(value, false);
|
|
2026
|
+
if (candidate.name === "onLongPressGesture" && label === "perform")
|
|
2027
|
+
return lowerCallback(value, false);
|
|
2028
|
+
if (candidate.name === "onLongPressGesture" && label === "onPressingChanged")
|
|
2029
|
+
return lowerCallback(value, true);
|
|
2030
|
+
if (candidate.name === "onHover" && label === "perform")
|
|
2031
|
+
return lowerCallback(value, true);
|
|
2032
|
+
// Font values keep their Swift labels (`.system(size:weight:design:)`)
|
|
2033
|
+
// until the Font-specific lowering reads them.
|
|
2034
|
+
if (candidate.name === "font")
|
|
2035
|
+
return lowerImplicitMemberShorthand(value, "Font");
|
|
2036
|
+
return lowerImplicitMemberShorthand(lowerShorthand(value), ["foregroundStyle", "foreground", "background", "fill", "stroke"].includes(candidate.name) ? "ShapeStyle" : undefined);
|
|
2037
|
+
};
|
|
2038
|
+
const positional = entries.filter(entry => !entry.label).map(entry => lowerModifierValue(entry.value));
|
|
2039
|
+
const named = new Map();
|
|
2040
|
+
for (const entry of entries) {
|
|
2041
|
+
if (!entry.label)
|
|
2042
|
+
continue;
|
|
2043
|
+
if (named.has(entry.label))
|
|
2044
|
+
throw syntaxError(`Duplicate labeled argument ${entry.label}: in .${candidate.name}(...)`, candidate.open);
|
|
2045
|
+
named.set(entry.label, lowerModifierValue(entry.value, entry.label));
|
|
2046
|
+
}
|
|
2047
|
+
let lowered;
|
|
2048
|
+
if (!lowering || named.size === 0) {
|
|
2049
|
+
lowered = positional.join(", ");
|
|
2050
|
+
}
|
|
2051
|
+
else if (lowering.kind === "object") {
|
|
2052
|
+
if (positional.length > 0)
|
|
2053
|
+
throw syntaxError(`.${candidate.name}(...) does not mix positional and labeled arguments in this overload`, candidate.open);
|
|
2054
|
+
for (const label of named.keys())
|
|
2055
|
+
if (!lowering.labels.includes(label))
|
|
2056
|
+
throw syntaxError(`Unknown labeled argument ${label}: in .${candidate.name}(...)`, candidate.open);
|
|
2057
|
+
lowered = `{ ${lowering.labels.flatMap(label => named.has(label) ? [`${label}: ${named.get(label)}`] : []).join(", ")} }`;
|
|
2058
|
+
}
|
|
2059
|
+
else if (lowering.kind === "ordered") {
|
|
2060
|
+
for (const label of named.keys())
|
|
2061
|
+
if (!lowering.labels.includes(label))
|
|
2062
|
+
throw syntaxError(`Unknown labeled argument ${label}: in .${candidate.name}(...)`, candidate.open);
|
|
2063
|
+
lowered = [...positional, ...lowering.labels.flatMap(label => named.has(label) ? [named.get(label)] : [])].join(", ");
|
|
2064
|
+
}
|
|
2065
|
+
else if (lowering.kind === "slots") {
|
|
2066
|
+
const allowed = new Set(lowering.labels.filter((label) => label !== null));
|
|
2067
|
+
for (const label of named.keys())
|
|
2068
|
+
if (!allowed.has(label))
|
|
2069
|
+
throw syntaxError(`Unknown labeled argument ${label}: in .${candidate.name}(...)`, candidate.open);
|
|
2070
|
+
// Fill explicitly: sparse Array holes are skipped by .map(), which used
|
|
2071
|
+
// to serialize omitted leading Swift defaults as `.shadow(, 8)` instead
|
|
2072
|
+
// of the intentional `.shadow(undefined, 8)` runtime call.
|
|
2073
|
+
const slots = new Array(lowering.labels.length).fill(undefined);
|
|
2074
|
+
let positionalIndex = 0;
|
|
2075
|
+
for (let index = 0; index < lowering.labels.length; index += 1) {
|
|
2076
|
+
const label = lowering.labels[index];
|
|
2077
|
+
if (label !== null && named.has(label))
|
|
2078
|
+
slots[index] = named.get(label);
|
|
2079
|
+
else if (label === null && positionalIndex < positional.length)
|
|
2080
|
+
slots[index] = positional[positionalIndex++];
|
|
2081
|
+
}
|
|
2082
|
+
if (positionalIndex < positional.length)
|
|
2083
|
+
throw syntaxError(`Too many positional arguments in .${candidate.name}(...)`, candidate.open);
|
|
2084
|
+
let last = slots.length - 1;
|
|
2085
|
+
while (last >= 0 && slots[last] === undefined)
|
|
2086
|
+
last -= 1;
|
|
2087
|
+
lowered = Array.from({ length: last + 1 }, (_value, index) => slots[index] ?? "undefined").join(", ");
|
|
2088
|
+
}
|
|
2089
|
+
else {
|
|
2090
|
+
const allowed = new Set([...lowering.objectLabels, ...lowering.orderedLabels]);
|
|
2091
|
+
for (const label of named.keys())
|
|
2092
|
+
if (!allowed.has(label))
|
|
2093
|
+
throw syntaxError(`Unknown labeled argument ${label}: in .${candidate.name}(...)`, candidate.open);
|
|
2094
|
+
const objectEntries = lowering.objectLabels.flatMap(label => named.has(label) ? [`${label}: ${named.get(label)}`] : []);
|
|
2095
|
+
if (objectEntries.length > 0 && positional.length > 0)
|
|
2096
|
+
throw syntaxError(`.${candidate.name}(...) cannot mix its x/y labeled overload with a positional scale`, candidate.open);
|
|
2097
|
+
lowered = [
|
|
2098
|
+
...(objectEntries.length > 0 ? [`{ ${objectEntries.join(", ")} }`] : positional),
|
|
2099
|
+
...lowering.orderedLabels.flatMap(label => named.has(label) ? [named.get(label)] : []),
|
|
2100
|
+
].join(", ");
|
|
2101
|
+
}
|
|
2102
|
+
output = output.slice(0, candidate.open + 1) + lowered + output.slice(candidate.close);
|
|
2103
|
+
}
|
|
2104
|
+
}
|
|
2105
|
+
function initializerRegistryFor(declarations) {
|
|
2106
|
+
const registry = new Map(canonicalInitializerSymbols);
|
|
2107
|
+
const add = (declaration) => {
|
|
2108
|
+
registry.set(declaration.name, structInitializerPlans(declaration).map((plan, index) => semanticInitializerSymbol(declaration.name, plan, index)));
|
|
2109
|
+
for (const nested of declaration.nested ?? [])
|
|
2110
|
+
add(nested);
|
|
2111
|
+
};
|
|
2112
|
+
for (const declaration of declarations)
|
|
2113
|
+
add(declaration);
|
|
2114
|
+
return registry;
|
|
2115
|
+
}
|
|
2116
|
+
function lowerVueComponentImports(source) {
|
|
2117
|
+
if (!/\.vue["']/.test(source))
|
|
2118
|
+
return source;
|
|
2119
|
+
const file = ts.createSourceFile("mun-vue-imports.ts", source, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS);
|
|
2120
|
+
const existingNames = new Set();
|
|
2121
|
+
const collectNames = (node) => {
|
|
2122
|
+
if (ts.isIdentifier(node))
|
|
2123
|
+
existingNames.add(node.text);
|
|
2124
|
+
ts.forEachChild(node, collectNames);
|
|
2125
|
+
};
|
|
2126
|
+
collectNames(file);
|
|
2127
|
+
const replacements = [];
|
|
2128
|
+
let index = 0;
|
|
2129
|
+
for (const statement of file.statements) {
|
|
2130
|
+
if (!ts.isImportDeclaration(statement) || !ts.isStringLiteral(statement.moduleSpecifier))
|
|
2131
|
+
continue;
|
|
2132
|
+
if (!/\.vue$/i.test(statement.moduleSpecifier.text) || statement.importClause?.isTypeOnly)
|
|
2133
|
+
continue;
|
|
2134
|
+
const importedName = statement.importClause?.name?.text
|
|
2135
|
+
?? (statement.importClause?.namedBindings && ts.isNamedImports(statement.importClause.namedBindings)
|
|
2136
|
+
? statement.importClause.namedBindings.elements.find(element => element.propertyName?.text === "default")?.name.text
|
|
2137
|
+
: undefined);
|
|
2138
|
+
if (!importedName)
|
|
2139
|
+
continue;
|
|
2140
|
+
let adapterName = `__munForeignComponent${index++}`;
|
|
2141
|
+
while (existingNames.has(adapterName))
|
|
2142
|
+
adapterName = `__munForeignComponent${index++}`;
|
|
2143
|
+
existingNames.add(adapterName);
|
|
2144
|
+
const quote = source[statement.moduleSpecifier.getStart(file)];
|
|
2145
|
+
const module = statement.moduleSpecifier.text;
|
|
2146
|
+
const lineStart = source.lastIndexOf("\n", statement.getStart(file) - 1) + 1;
|
|
2147
|
+
const indent = source.slice(lineStart, statement.getStart(file)).match(/^[ \t]*/)?.[0] ?? "";
|
|
2148
|
+
replacements.push({
|
|
2149
|
+
start: statement.getStart(file),
|
|
2150
|
+
end: statement.end,
|
|
2151
|
+
value: `${indent}import ${adapterName} from ${quote}${module}${quote}\n${indent}const ${importedName} = __munForeignComponent(${adapterName})`,
|
|
2152
|
+
});
|
|
2153
|
+
}
|
|
2154
|
+
if (replacements.length === 0)
|
|
2155
|
+
return source;
|
|
2156
|
+
let result = source;
|
|
2157
|
+
for (const replacement of replacements.reverse())
|
|
2158
|
+
result = result.slice(0, replacement.start) + replacement.value + result.slice(replacement.end);
|
|
2159
|
+
return `import { foreignComponent as __munForeignComponent } from "@mun-ui/vue"\n${result}`;
|
|
2160
|
+
}
|
|
2161
|
+
function lowerReactComponentImports(source) {
|
|
2162
|
+
if (!/\.(?:tsx|jsx)["']/.test(source))
|
|
2163
|
+
return source;
|
|
2164
|
+
const file = ts.createSourceFile("mun-react-imports.ts", source, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);
|
|
2165
|
+
const existingNames = new Set();
|
|
2166
|
+
const collectNames = (node) => {
|
|
2167
|
+
if (ts.isIdentifier(node))
|
|
2168
|
+
existingNames.add(node.text);
|
|
2169
|
+
ts.forEachChild(node, collectNames);
|
|
2170
|
+
};
|
|
2171
|
+
collectNames(file);
|
|
2172
|
+
const replacements = [];
|
|
2173
|
+
let index = 0;
|
|
2174
|
+
for (const statement of file.statements) {
|
|
2175
|
+
if (!ts.isImportDeclaration(statement) || !ts.isStringLiteral(statement.moduleSpecifier))
|
|
2176
|
+
continue;
|
|
2177
|
+
if (!/\.(?:tsx|jsx)$/i.test(statement.moduleSpecifier.text) || statement.importClause?.isTypeOnly)
|
|
2178
|
+
continue;
|
|
2179
|
+
const importedName = statement.importClause?.name?.text;
|
|
2180
|
+
if (!importedName)
|
|
2181
|
+
continue;
|
|
2182
|
+
let adapterName = `__munReactComponent${index++}`;
|
|
2183
|
+
while (existingNames.has(adapterName))
|
|
2184
|
+
adapterName = `__munReactComponent${index++}`;
|
|
2185
|
+
existingNames.add(adapterName);
|
|
2186
|
+
const quote = source[statement.moduleSpecifier.getStart(file)];
|
|
2187
|
+
const module = statement.moduleSpecifier.text;
|
|
2188
|
+
const lineStart = source.lastIndexOf("\n", statement.getStart(file) - 1) + 1;
|
|
2189
|
+
const indent = source.slice(lineStart, statement.getStart(file)).match(/^[ \t]*/)?.[0] ?? "";
|
|
2190
|
+
replacements.push({
|
|
2191
|
+
start: statement.getStart(file),
|
|
2192
|
+
end: statement.end,
|
|
2193
|
+
value: `${indent}import ${adapterName} from ${quote}${module}${quote}\n${indent}const ${importedName} = __munReactComponent(${adapterName})`,
|
|
2194
|
+
});
|
|
2195
|
+
}
|
|
2196
|
+
if (replacements.length === 0)
|
|
2197
|
+
return source;
|
|
2198
|
+
let result = source;
|
|
2199
|
+
for (const replacement of replacements.reverse())
|
|
2200
|
+
result = result.slice(0, replacement.start) + replacement.value + result.slice(replacement.end);
|
|
2201
|
+
return `import { reactComponent as __munReactComponent } from "@mun-ui/react"\n${result}`;
|
|
2202
|
+
}
|
|
2203
|
+
export function transformMunSource(authoredSource, fileName = "mun-source.ts", options = {}) {
|
|
2204
|
+
const source = /\.mun$/i.test(fileName) ? lowerBareClosureCalls(authoredSource) : authoredSource;
|
|
2205
|
+
if (/\.mun$/i.test(fileName)) {
|
|
2206
|
+
const originalDeclarations = parseMunStructs(source);
|
|
2207
|
+
validateWebBindings(originalDeclarations, initializerRegistryFor(originalDeclarations));
|
|
2208
|
+
}
|
|
2209
|
+
const withVueImports = lowerVueComponentImports(lowerSwiftKeyPaths(lowerObservableClasses(source)));
|
|
2210
|
+
const withForeignImports = lowerReactComponentImports(withVueImports);
|
|
2211
|
+
const withAnimationArguments = lowerNamedAnimationFactoryCalls(withForeignImports);
|
|
2212
|
+
const withModifierArguments = lowerNamedModifierCalls(withAnimationArguments);
|
|
2213
|
+
const declarations = parseMunStructs(withModifierArguments);
|
|
2214
|
+
const registry = initializerRegistryFor(declarations);
|
|
2215
|
+
// Button validation and struct dependency proof both need the same pre-lowered
|
|
2216
|
+
// TypeScript syntax snapshot. Build it at most once and share it rather than
|
|
2217
|
+
// reparsing the module independently in two compiler stages.
|
|
2218
|
+
const needsValidationSyntax = declarations.length > 0 || /\bButton\s*\(/.test(withModifierArguments);
|
|
2219
|
+
const validationSyntax = needsValidationSyntax ? validationSourceFile(withModifierArguments) : undefined;
|
|
2220
|
+
validateKnownCalls(parseMunBuilder(withModifierArguments), registry);
|
|
2221
|
+
validateKnownTypeScriptCalls(withModifierArguments, registry, validationSyntax);
|
|
2222
|
+
for (const declaration of declarations) {
|
|
2223
|
+
validateKnownCalls(parseMunBuilder(declaration.bodyExpressionSource, declaration.bodyExpressionRange.start), registry);
|
|
2224
|
+
}
|
|
2225
|
+
const structStateProof = declarations.length > 0 && validationSyntax
|
|
2226
|
+
? importedMunValueBindings(validationSyntax)
|
|
2227
|
+
: undefined;
|
|
2228
|
+
const withStructs = lowerStructs(withModifierArguments, registry, structStateProof, /\.mun$/i.test(fileName));
|
|
2229
|
+
const withNamedArguments = lowerNamedMunCalls(withStructs, registry);
|
|
2230
|
+
const withBuilderSyntax = lowerRange(withNamedArguments, registry);
|
|
2231
|
+
// State ownership is resolved only after Mun-only syntax has become valid
|
|
2232
|
+
// TypeScript. This lets the TypeScript AST see complete view() arguments
|
|
2233
|
+
// instead of truncating them at trailing builder blocks.
|
|
2234
|
+
const lowered = lowerTopLevelState(withBuilderSyntax);
|
|
2235
|
+
// Capture common authored collection rows before any later specialization
|
|
2236
|
+
// turns Text/Element calls into more opaque compiled templates. A second
|
|
2237
|
+
// collection pass below still picks up shapes exposed by constant folding
|
|
2238
|
+
// or static struct specialization.
|
|
2239
|
+
const withStateArrayMaps = lowerStateArrayMaps(lowered);
|
|
2240
|
+
const withAuthoredCollections = lowerCompiledCollections(withStateArrayMaps);
|
|
2241
|
+
const withStaticResults = foldStaticResults(withAuthoredCollections);
|
|
2242
|
+
const withStaticStructCalls = lowerStaticStructCalls(withStaticResults, declarations);
|
|
2243
|
+
// Collection planning must see authored Text/Element rows before general
|
|
2244
|
+
// semantic specialization lowers those calls into templates. Otherwise
|
|
2245
|
+
// making a core View canonical can accidentally disable the faster keyed
|
|
2246
|
+
// flat-row plan. The fallback closure may still be specialized afterwards.
|
|
2247
|
+
const withCompiledCollections = lowerCompiledCollections(withStaticStructCalls);
|
|
2248
|
+
const withCanonicalCalls = lowerStaticCanonicalCalls(withCompiledCollections);
|
|
2249
|
+
const withSemanticSpecializations = lowerStaticSemanticSpecializations(withCanonicalCalls, fileName);
|
|
2250
|
+
const withCompiledTemplates = lowerCompiledViewTemplates(withSemanticSpecializations);
|
|
2251
|
+
// Hoisting only needs the imports authored/retained by the source. Injecting
|
|
2252
|
+
// compiler helper imports first makes the final static pass parse a larger
|
|
2253
|
+
// module and can only add irrelevant bindings to its candidate set.
|
|
2254
|
+
const withStaticHoists = hoistStaticViewSubtrees(withCompiledTemplates);
|
|
2255
|
+
const output = /\.mun$/i.test(fileName) ? importMunBuiltins(source, withStaticHoists, fileName, options.externalScope === true) : ensureImports(withStaticHoists);
|
|
2256
|
+
if (/\.mun$/i.test(fileName))
|
|
2257
|
+
validateWebLowering(source, output, fileName);
|
|
2258
|
+
return output;
|
|
2259
|
+
}
|
|
2260
|
+
function hasNamedMunArguments(source) {
|
|
2261
|
+
const calls = /\b[A-Z][A-Za-z0-9_$]*\s*\(/g;
|
|
2262
|
+
let match;
|
|
2263
|
+
while ((match = calls.exec(source))) {
|
|
2264
|
+
const open = source.indexOf("(", match.index);
|
|
2265
|
+
const close = matching(source, open, "(", ")");
|
|
2266
|
+
if (previousWord(source, match.index) === "function") {
|
|
2267
|
+
calls.lastIndex = close + 1;
|
|
2268
|
+
continue;
|
|
2269
|
+
}
|
|
2270
|
+
if (splitTopLevel(source.slice(open + 1, close)).some(argument => topLevelColon(argument) >= 0))
|
|
2271
|
+
return true;
|
|
2272
|
+
calls.lastIndex = close + 1;
|
|
2273
|
+
}
|
|
2274
|
+
return false;
|
|
2275
|
+
}
|
|
2276
|
+
function hasBindingShorthand(source) {
|
|
2277
|
+
return lowerShorthand(source) !== source;
|
|
2278
|
+
}
|
|
2279
|
+
function hasStaticModifierSyntax(source) {
|
|
2280
|
+
return Array.from(staticModifierNames).some(name => new RegExp(`\\.${name}\\s*\\(`).test(source));
|
|
2281
|
+
}
|
|
2282
|
+
export function hasMunSyntax(source, allowRawHtml = true) {
|
|
2283
|
+
return /\bstruct\s+[A-Z][A-Za-z0-9_$]*(?:\s*<[^>{}]*>)?\s*:\s*View/.test(source)
|
|
2284
|
+
|| (allowRawHtml && findRawHtml(source) !== undefined)
|
|
2285
|
+
|| findBuilder(source, 0, true) !== undefined
|
|
2286
|
+
|| hasBindingShorthand(source)
|
|
2287
|
+
|| hasNamedMunArguments(source)
|
|
2288
|
+
|| hasStaticModifierSyntax(source);
|
|
2289
|
+
}
|
|
2290
|
+
//# sourceMappingURL=pipeline.js.map
|