@codehz/json-expr 0.6.1 → 0.6.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.mjs +540 -243
- package/dist/index.mjs.map +1 -1
- package/package.json +11 -11
package/dist/index.mjs
CHANGED
|
@@ -63,8 +63,8 @@ function createGenerateContext() {
|
|
|
63
63
|
/**
|
|
64
64
|
* 从 AST 生成规范化的代码
|
|
65
65
|
*/
|
|
66
|
-
function generate(node) {
|
|
67
|
-
return generateWithContext(node, createGenerateContext());
|
|
66
|
+
function generate(node, options = {}) {
|
|
67
|
+
return generateWithContext(node, createGenerateContext(), options);
|
|
68
68
|
}
|
|
69
69
|
/** 需要空格分隔的关键字运算符 */
|
|
70
70
|
const KEYWORD_BINARY_OPERATORS = new Set(["in", "instanceof"]);
|
|
@@ -72,46 +72,47 @@ const KEYWORD_UNARY_OPERATORS = new Set(["typeof", "void"]);
|
|
|
72
72
|
/**
|
|
73
73
|
* 带上下文的代码生成
|
|
74
74
|
*/
|
|
75
|
-
function generateWithContext(node, ctx) {
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
case "
|
|
79
|
-
case "
|
|
75
|
+
function generateWithContext(node, ctx, options = {}) {
|
|
76
|
+
const rewritten = options.rewriteNode?.(node, ctx) ?? node;
|
|
77
|
+
switch (rewritten.type) {
|
|
78
|
+
case "NumberLiteral": return rewritten.raw;
|
|
79
|
+
case "StringLiteral": return JSON.stringify(rewritten.value);
|
|
80
|
+
case "BooleanLiteral": return rewritten.value ? "true" : "false";
|
|
80
81
|
case "NullLiteral": return "null";
|
|
81
|
-
case "Identifier": return
|
|
82
|
-
case "Placeholder": return ctx.paramMapping.get(
|
|
82
|
+
case "Identifier": return rewritten.name;
|
|
83
|
+
case "Placeholder": return ctx.paramMapping.get(rewritten.id) ?? `$$${rewritten.id.description}$$`;
|
|
83
84
|
case "BinaryExpr": {
|
|
84
|
-
const left = wrapIfNeededWithContext(
|
|
85
|
-
const right = wrapIfNeededWithContext(
|
|
86
|
-
const sep = KEYWORD_BINARY_OPERATORS.has(
|
|
87
|
-
return `${left}${sep}${
|
|
85
|
+
const left = wrapIfNeededWithContext(rewritten.left, rewritten, "left", ctx, options);
|
|
86
|
+
const right = wrapIfNeededWithContext(rewritten.right, rewritten, "right", ctx, options);
|
|
87
|
+
const sep = KEYWORD_BINARY_OPERATORS.has(rewritten.operator) ? " " : "";
|
|
88
|
+
return `${left}${sep}${rewritten.operator}${sep}${right}`;
|
|
88
89
|
}
|
|
89
90
|
case "UnaryExpr": {
|
|
90
|
-
if (!
|
|
91
|
-
const arg = wrapIfNeededWithContext(
|
|
92
|
-
const sep = KEYWORD_UNARY_OPERATORS.has(
|
|
93
|
-
return `${
|
|
91
|
+
if (!rewritten.prefix) return generateWithContext(rewritten.argument, ctx, options) + rewritten.operator;
|
|
92
|
+
const arg = wrapIfNeededWithContext(rewritten.argument, rewritten, "argument", ctx, options);
|
|
93
|
+
const sep = KEYWORD_UNARY_OPERATORS.has(rewritten.operator) ? " " : "";
|
|
94
|
+
return `${rewritten.operator}${sep}${arg}`;
|
|
94
95
|
}
|
|
95
|
-
case "ConditionalExpr": return `${wrapIfNeededWithContext(
|
|
96
|
+
case "ConditionalExpr": return `${wrapIfNeededWithContext(rewritten.test, rewritten, "test", ctx, options)}?${wrapIfNeededWithContext(rewritten.consequent, rewritten, "consequent", ctx, options)}:${wrapIfNeededWithContext(rewritten.alternate, rewritten, "alternate", ctx, options)}`;
|
|
96
97
|
case "MemberExpr": {
|
|
97
|
-
const object = wrapIfNeededWithContext(
|
|
98
|
-
const property = generateWithContext(
|
|
99
|
-
const accessor =
|
|
100
|
-
return
|
|
98
|
+
const object = wrapIfNeededWithContext(rewritten.object, rewritten, "object", ctx, options);
|
|
99
|
+
const property = generateWithContext(rewritten.property, ctx, options);
|
|
100
|
+
const accessor = rewritten.optional ? "?." : rewritten.computed ? "" : ".";
|
|
101
|
+
return rewritten.computed ? `${object}${accessor}[${property}]` : `${object}${accessor}${property}`;
|
|
101
102
|
}
|
|
102
103
|
case "CallExpr": {
|
|
103
|
-
const callee = wrapIfNeededWithContext(
|
|
104
|
-
const args =
|
|
105
|
-
return `${
|
|
106
|
-
}
|
|
107
|
-
case "ArrayExpr": return `[${
|
|
108
|
-
case "ObjectExpr": return `{${
|
|
109
|
-
if (prop.shorthand) return generateWithContext(prop.key, ctx);
|
|
110
|
-
return `${prop.computed ? `[${generateWithContext(prop.key, ctx)}]` : generateWithContext(prop.key, ctx)}:${generateWithContext(prop.value, ctx)}`;
|
|
104
|
+
const callee = wrapIfNeededWithContext(rewritten.callee, rewritten, "callee", ctx, options);
|
|
105
|
+
const args = rewritten.arguments.map((arg) => generateWithContext(arg, ctx, options)).join(",");
|
|
106
|
+
return `${rewritten.callee.type === "Identifier" && BUILTIN_CONSTRUCTORS.has(rewritten.callee.name) ? "new " : ""}${callee}${rewritten.optional ? "?." : ""}(${args})`;
|
|
107
|
+
}
|
|
108
|
+
case "ArrayExpr": return `[${rewritten.elements.map((el) => generateWithContext(el, ctx, options)).join(",")}]`;
|
|
109
|
+
case "ObjectExpr": return `{${rewritten.properties.map((prop) => {
|
|
110
|
+
if (prop.shorthand) return generateWithContext(prop.key, ctx, options);
|
|
111
|
+
return `${prop.computed ? `[${generateWithContext(prop.key, ctx, options)}]` : generateWithContext(prop.key, ctx, options)}:${generateWithContext(prop.value, ctx, options)}`;
|
|
111
112
|
}).join(",")}}`;
|
|
112
|
-
case "ArrowFunctionExpr": return generateArrowFunction(
|
|
113
|
+
case "ArrowFunctionExpr": return generateArrowFunction(rewritten, ctx, options);
|
|
113
114
|
default: {
|
|
114
|
-
const unknownNode =
|
|
115
|
+
const unknownNode = rewritten;
|
|
115
116
|
throw new Error(`Unknown node type: ${unknownNode.type ?? "unknown"}`);
|
|
116
117
|
}
|
|
117
118
|
}
|
|
@@ -120,7 +121,7 @@ function generateWithContext(node, ctx) {
|
|
|
120
121
|
* 生成箭头函数代码
|
|
121
122
|
* 为 Placeholder 参数分配唯一名称,避免嵌套 lambda 冲突
|
|
122
123
|
*/
|
|
123
|
-
function generateArrowFunction(node, ctx) {
|
|
124
|
+
function generateArrowFunction(node, ctx, options) {
|
|
124
125
|
const allocatedParams = [];
|
|
125
126
|
const paramNames = [];
|
|
126
127
|
for (const param of node.params) if (param.type === "Identifier") paramNames.push(param.name);
|
|
@@ -135,7 +136,7 @@ function generateArrowFunction(node, ctx) {
|
|
|
135
136
|
ctx.paramMapping.set(param.id, name);
|
|
136
137
|
}
|
|
137
138
|
const paramsStr = paramNames.length === 1 ? paramNames[0] : `(${paramNames.join(",")})`;
|
|
138
|
-
const bodyStr = node.body.type === "ObjectExpr" ? `(${generateWithContext(node.body, ctx)})` : generateWithContext(node.body, ctx);
|
|
139
|
+
const bodyStr = node.body.type === "ObjectExpr" ? `(${generateWithContext(node.body, ctx, options)})` : generateWithContext(node.body, ctx, options);
|
|
139
140
|
for (const { id, name } of allocatedParams) {
|
|
140
141
|
ctx.paramMapping.delete(id);
|
|
141
142
|
ctx.usedParamNames.delete(name);
|
|
@@ -153,9 +154,10 @@ function allocateUniqueName(usedNames) {
|
|
|
153
154
|
/**
|
|
154
155
|
* 判断是否需要括号包裹,并生成代码(带上下文版本)
|
|
155
156
|
*/
|
|
156
|
-
function wrapIfNeededWithContext(child, parent, position, ctx) {
|
|
157
|
-
const
|
|
158
|
-
|
|
157
|
+
function wrapIfNeededWithContext(child, parent, position, ctx, options = {}) {
|
|
158
|
+
const rewrittenChild = options.rewriteNode?.(child, ctx) ?? child;
|
|
159
|
+
const code = generateWithContext(rewrittenChild, ctx, options);
|
|
160
|
+
if (needsParens(rewrittenChild, parent, position)) return `(${code})`;
|
|
159
161
|
return code;
|
|
160
162
|
}
|
|
161
163
|
/**
|
|
@@ -199,121 +201,258 @@ function transformIdentifiers(node, transform) {
|
|
|
199
201
|
switch (node.type) {
|
|
200
202
|
case "Identifier": {
|
|
201
203
|
const result = transform(node.name);
|
|
202
|
-
|
|
204
|
+
if (typeof result !== "string") return result;
|
|
205
|
+
return result === node.name ? node : {
|
|
203
206
|
...node,
|
|
204
207
|
name: result
|
|
205
|
-
}
|
|
208
|
+
};
|
|
206
209
|
}
|
|
207
210
|
case "Placeholder": return node;
|
|
208
|
-
case "BinaryExpr":
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
right
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
}
|
|
217
|
-
case "
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
211
|
+
case "BinaryExpr": {
|
|
212
|
+
const left = transformIdentifiers(node.left, transform);
|
|
213
|
+
const right = transformIdentifiers(node.right, transform);
|
|
214
|
+
return left === node.left && right === node.right ? node : {
|
|
215
|
+
...node,
|
|
216
|
+
left,
|
|
217
|
+
right
|
|
218
|
+
};
|
|
219
|
+
}
|
|
220
|
+
case "UnaryExpr": {
|
|
221
|
+
const argument = transformIdentifiers(node.argument, transform);
|
|
222
|
+
return argument === node.argument ? node : {
|
|
223
|
+
...node,
|
|
224
|
+
argument
|
|
225
|
+
};
|
|
226
|
+
}
|
|
227
|
+
case "ConditionalExpr": {
|
|
228
|
+
const test = transformIdentifiers(node.test, transform);
|
|
229
|
+
const consequent = transformIdentifiers(node.consequent, transform);
|
|
230
|
+
const alternate = transformIdentifiers(node.alternate, transform);
|
|
231
|
+
return test === node.test && consequent === node.consequent && alternate === node.alternate ? node : {
|
|
232
|
+
...node,
|
|
233
|
+
test,
|
|
234
|
+
consequent,
|
|
235
|
+
alternate
|
|
236
|
+
};
|
|
237
|
+
}
|
|
238
|
+
case "MemberExpr": {
|
|
239
|
+
const object = transformIdentifiers(node.object, transform);
|
|
240
|
+
const property = node.computed ? transformIdentifiers(node.property, transform) : node.property;
|
|
241
|
+
return object === node.object && property === node.property ? node : {
|
|
242
|
+
...node,
|
|
243
|
+
object,
|
|
244
|
+
property
|
|
245
|
+
};
|
|
246
|
+
}
|
|
247
|
+
case "CallExpr": {
|
|
248
|
+
const callee = transformIdentifiers(node.callee, transform);
|
|
249
|
+
const arguments_ = mapAstNodes$1(node.arguments, (arg) => transformIdentifiers(arg, transform));
|
|
250
|
+
return callee === node.callee && arguments_ === node.arguments ? node : {
|
|
251
|
+
...node,
|
|
252
|
+
callee,
|
|
253
|
+
arguments: arguments_
|
|
254
|
+
};
|
|
255
|
+
}
|
|
256
|
+
case "ArrayExpr": {
|
|
257
|
+
const elements = mapAstNodes$1(node.elements, (el) => transformIdentifiers(el, transform));
|
|
258
|
+
return elements === node.elements ? node : {
|
|
259
|
+
...node,
|
|
260
|
+
elements
|
|
261
|
+
};
|
|
262
|
+
}
|
|
263
|
+
case "ObjectExpr": {
|
|
264
|
+
const properties = mapObjectProperties$1(node.properties, (prop) => {
|
|
265
|
+
const key = prop.computed ? transformIdentifiers(prop.key, transform) : prop.key;
|
|
266
|
+
const value = transformIdentifiers(prop.value, transform);
|
|
267
|
+
return key === prop.key && value === prop.value ? prop : {
|
|
268
|
+
...prop,
|
|
269
|
+
key,
|
|
270
|
+
value
|
|
271
|
+
};
|
|
272
|
+
});
|
|
273
|
+
return properties === node.properties ? node : {
|
|
274
|
+
...node,
|
|
275
|
+
properties
|
|
276
|
+
};
|
|
277
|
+
}
|
|
245
278
|
case "ArrowFunctionExpr": {
|
|
246
279
|
const paramNames = new Set(node.params.filter((p) => p.type === "Identifier").map((p) => p.name));
|
|
247
|
-
|
|
280
|
+
const body = transformIdentifiers(node.body, (name) => paramNames.has(name) ? name : transform(name));
|
|
281
|
+
return body === node.body ? node : {
|
|
248
282
|
...node,
|
|
249
|
-
body
|
|
283
|
+
body
|
|
250
284
|
};
|
|
251
285
|
}
|
|
252
286
|
default: return node;
|
|
253
287
|
}
|
|
254
288
|
}
|
|
255
289
|
/**
|
|
256
|
-
*
|
|
257
|
-
* 回调函数接收 symbol,返回 Identifier 节点的名称
|
|
258
|
-
* 如果返回 null/undefined,则保留原始 Placeholder 节点
|
|
290
|
+
* expr() 专用:将 context 中的变量替换为 Placeholder。
|
|
259
291
|
*/
|
|
260
|
-
function
|
|
292
|
+
function transformExprVariables(node, nameToId) {
|
|
293
|
+
return transformIdentifiers(node, (name) => {
|
|
294
|
+
const id = nameToId.get(name);
|
|
295
|
+
return id ? {
|
|
296
|
+
type: "Placeholder",
|
|
297
|
+
id
|
|
298
|
+
} : name;
|
|
299
|
+
});
|
|
300
|
+
}
|
|
301
|
+
/**
|
|
302
|
+
* expr() 专用:单次遍历完成变量替换、子表达式引用计数和延迟编译收集。
|
|
303
|
+
*/
|
|
304
|
+
function transformExprIdentifiers(node, nameToId, nameToExprAST) {
|
|
305
|
+
const refCounts = /* @__PURE__ */ new Map();
|
|
306
|
+
const candidateRefs = /* @__PURE__ */ new Map();
|
|
307
|
+
const ast = transformExprIdentifiersWithScope(node, nameToId, nameToExprAST, refCounts, candidateRefs);
|
|
308
|
+
let deferredAsts;
|
|
309
|
+
for (const [name, refs] of candidateRefs) {
|
|
310
|
+
if ((refCounts.get(name) ?? 0) <= 1) {
|
|
311
|
+
replaceNode(refs[0], nameToExprAST.get(name));
|
|
312
|
+
continue;
|
|
313
|
+
}
|
|
314
|
+
if (!deferredAsts) deferredAsts = /* @__PURE__ */ new Map();
|
|
315
|
+
deferredAsts.set(name, nameToExprAST.get(name));
|
|
316
|
+
}
|
|
317
|
+
return {
|
|
318
|
+
ast,
|
|
319
|
+
deferredAsts
|
|
320
|
+
};
|
|
321
|
+
}
|
|
322
|
+
function mapAstNodes$1(nodes, transform) {
|
|
323
|
+
let result;
|
|
324
|
+
for (let i = 0; i < nodes.length; i++) {
|
|
325
|
+
const node = nodes[i];
|
|
326
|
+
const transformed = transform(node);
|
|
327
|
+
if (result) {
|
|
328
|
+
result.push(transformed);
|
|
329
|
+
continue;
|
|
330
|
+
}
|
|
331
|
+
if (transformed !== node) {
|
|
332
|
+
result = nodes.slice(0, i);
|
|
333
|
+
result.push(transformed);
|
|
334
|
+
}
|
|
335
|
+
}
|
|
336
|
+
return result ?? nodes;
|
|
337
|
+
}
|
|
338
|
+
function mapObjectProperties$1(properties, transform) {
|
|
339
|
+
let result;
|
|
340
|
+
for (let i = 0; i < properties.length; i++) {
|
|
341
|
+
const property = properties[i];
|
|
342
|
+
const transformed = transform(property);
|
|
343
|
+
if (result) {
|
|
344
|
+
result.push(transformed);
|
|
345
|
+
continue;
|
|
346
|
+
}
|
|
347
|
+
if (transformed !== property) {
|
|
348
|
+
result = properties.slice(0, i);
|
|
349
|
+
result.push(transformed);
|
|
350
|
+
}
|
|
351
|
+
}
|
|
352
|
+
return result ?? properties;
|
|
353
|
+
}
|
|
354
|
+
function transformExprIdentifiersWithScope(node, nameToId, nameToExprAST, refCounts, candidateRefs, shadowedNames) {
|
|
261
355
|
switch (node.type) {
|
|
262
|
-
case "
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
356
|
+
case "Identifier": {
|
|
357
|
+
if (shadowedNames?.has(node.name)) return node;
|
|
358
|
+
const id = nameToId.get(node.name);
|
|
359
|
+
if (id) return {
|
|
360
|
+
type: "Placeholder",
|
|
361
|
+
id
|
|
362
|
+
};
|
|
363
|
+
if (!nameToExprAST.get(node.name)) return node;
|
|
364
|
+
refCounts.set(node.name, (refCounts.get(node.name) ?? 0) + 1);
|
|
365
|
+
const candidateNode = { ...node };
|
|
366
|
+
const refs = candidateRefs.get(node.name);
|
|
367
|
+
if (refs) refs.push(candidateNode);
|
|
368
|
+
else candidateRefs.set(node.name, [candidateNode]);
|
|
369
|
+
return candidateNode;
|
|
370
|
+
}
|
|
371
|
+
case "Placeholder": return node;
|
|
372
|
+
case "BinaryExpr": {
|
|
373
|
+
const left = transformExprIdentifiersWithScope(node.left, nameToId, nameToExprAST, refCounts, candidateRefs, shadowedNames);
|
|
374
|
+
const right = transformExprIdentifiersWithScope(node.right, nameToId, nameToExprAST, refCounts, candidateRefs, shadowedNames);
|
|
375
|
+
return left === node.left && right === node.right ? node : {
|
|
376
|
+
...node,
|
|
377
|
+
left,
|
|
378
|
+
right
|
|
379
|
+
};
|
|
380
|
+
}
|
|
381
|
+
case "UnaryExpr": {
|
|
382
|
+
const argument = transformExprIdentifiersWithScope(node.argument, nameToId, nameToExprAST, refCounts, candidateRefs, shadowedNames);
|
|
383
|
+
return argument === node.argument ? node : {
|
|
384
|
+
...node,
|
|
385
|
+
argument
|
|
386
|
+
};
|
|
387
|
+
}
|
|
388
|
+
case "ConditionalExpr": {
|
|
389
|
+
const test = transformExprIdentifiersWithScope(node.test, nameToId, nameToExprAST, refCounts, candidateRefs, shadowedNames);
|
|
390
|
+
const consequent = transformExprIdentifiersWithScope(node.consequent, nameToId, nameToExprAST, refCounts, candidateRefs, shadowedNames);
|
|
391
|
+
const alternate = transformExprIdentifiersWithScope(node.alternate, nameToId, nameToExprAST, refCounts, candidateRefs, shadowedNames);
|
|
392
|
+
return test === node.test && consequent === node.consequent && alternate === node.alternate ? node : {
|
|
393
|
+
...node,
|
|
394
|
+
test,
|
|
395
|
+
consequent,
|
|
396
|
+
alternate
|
|
397
|
+
};
|
|
398
|
+
}
|
|
399
|
+
case "MemberExpr": {
|
|
400
|
+
const object = transformExprIdentifiersWithScope(node.object, nameToId, nameToExprAST, refCounts, candidateRefs, shadowedNames);
|
|
401
|
+
const property = node.computed ? transformExprIdentifiersWithScope(node.property, nameToId, nameToExprAST, refCounts, candidateRefs, shadowedNames) : node.property;
|
|
402
|
+
return object === node.object && property === node.property ? node : {
|
|
403
|
+
...node,
|
|
404
|
+
object,
|
|
405
|
+
property
|
|
406
|
+
};
|
|
407
|
+
}
|
|
408
|
+
case "CallExpr": {
|
|
409
|
+
const callee = transformExprIdentifiersWithScope(node.callee, nameToId, nameToExprAST, refCounts, candidateRefs, shadowedNames);
|
|
410
|
+
const arguments_ = mapAstNodes$1(node.arguments, (arg) => transformExprIdentifiersWithScope(arg, nameToId, nameToExprAST, refCounts, candidateRefs, shadowedNames));
|
|
411
|
+
return callee === node.callee && arguments_ === node.arguments ? node : {
|
|
412
|
+
...node,
|
|
413
|
+
callee,
|
|
414
|
+
arguments: arguments_
|
|
415
|
+
};
|
|
416
|
+
}
|
|
417
|
+
case "ArrayExpr": {
|
|
418
|
+
const elements = mapAstNodes$1(node.elements, (el) => transformExprIdentifiersWithScope(el, nameToId, nameToExprAST, refCounts, candidateRefs, shadowedNames));
|
|
419
|
+
return elements === node.elements ? node : {
|
|
420
|
+
...node,
|
|
421
|
+
elements
|
|
422
|
+
};
|
|
423
|
+
}
|
|
424
|
+
case "ObjectExpr": {
|
|
425
|
+
const properties = mapObjectProperties$1(node.properties, (prop) => {
|
|
426
|
+
const key = prop.computed ? transformExprIdentifiersWithScope(prop.key, nameToId, nameToExprAST, refCounts, candidateRefs, shadowedNames) : prop.key;
|
|
427
|
+
const value = transformExprIdentifiersWithScope(prop.value, nameToId, nameToExprAST, refCounts, candidateRefs, shadowedNames);
|
|
428
|
+
return key === prop.key && value === prop.value ? prop : {
|
|
429
|
+
...prop,
|
|
430
|
+
key,
|
|
431
|
+
value
|
|
432
|
+
};
|
|
433
|
+
});
|
|
434
|
+
return properties === node.properties ? node : {
|
|
435
|
+
...node,
|
|
436
|
+
properties
|
|
437
|
+
};
|
|
268
438
|
}
|
|
269
|
-
case "Identifier": return node;
|
|
270
|
-
case "BinaryExpr": return {
|
|
271
|
-
...node,
|
|
272
|
-
left: transformPlaceholders(node.left, transform),
|
|
273
|
-
right: transformPlaceholders(node.right, transform)
|
|
274
|
-
};
|
|
275
|
-
case "UnaryExpr": return {
|
|
276
|
-
...node,
|
|
277
|
-
argument: transformPlaceholders(node.argument, transform)
|
|
278
|
-
};
|
|
279
|
-
case "ConditionalExpr": return {
|
|
280
|
-
...node,
|
|
281
|
-
test: transformPlaceholders(node.test, transform),
|
|
282
|
-
consequent: transformPlaceholders(node.consequent, transform),
|
|
283
|
-
alternate: transformPlaceholders(node.alternate, transform)
|
|
284
|
-
};
|
|
285
|
-
case "MemberExpr": return {
|
|
286
|
-
...node,
|
|
287
|
-
object: transformPlaceholders(node.object, transform),
|
|
288
|
-
property: node.computed ? transformPlaceholders(node.property, transform) : node.property
|
|
289
|
-
};
|
|
290
|
-
case "CallExpr": return {
|
|
291
|
-
...node,
|
|
292
|
-
callee: transformPlaceholders(node.callee, transform),
|
|
293
|
-
arguments: node.arguments.map((arg) => transformPlaceholders(arg, transform))
|
|
294
|
-
};
|
|
295
|
-
case "ArrayExpr": return {
|
|
296
|
-
...node,
|
|
297
|
-
elements: node.elements.map((el) => transformPlaceholders(el, transform))
|
|
298
|
-
};
|
|
299
|
-
case "ObjectExpr": return {
|
|
300
|
-
...node,
|
|
301
|
-
properties: node.properties.map((prop) => ({
|
|
302
|
-
...prop,
|
|
303
|
-
key: prop.computed ? transformPlaceholders(prop.key, transform) : prop.key,
|
|
304
|
-
value: transformPlaceholders(prop.value, transform)
|
|
305
|
-
}))
|
|
306
|
-
};
|
|
307
439
|
case "ArrowFunctionExpr": {
|
|
308
|
-
const
|
|
309
|
-
|
|
440
|
+
const paramNames = node.params.filter((p) => p.type === "Identifier");
|
|
441
|
+
const nextShadowedNames = paramNames.length === 0 ? shadowedNames : new Set([...shadowedNames ?? [], ...paramNames.map((param) => param.name)]);
|
|
442
|
+
const body = transformExprIdentifiersWithScope(node.body, nameToId, nameToExprAST, refCounts, candidateRefs, nextShadowedNames);
|
|
443
|
+
return body === node.body ? node : {
|
|
310
444
|
...node,
|
|
311
|
-
body
|
|
445
|
+
body
|
|
312
446
|
};
|
|
313
447
|
}
|
|
314
448
|
default: return node;
|
|
315
449
|
}
|
|
316
450
|
}
|
|
451
|
+
function replaceNode(target, replacement) {
|
|
452
|
+
const record = target;
|
|
453
|
+
for (const key of Object.keys(record)) delete record[key];
|
|
454
|
+
Object.assign(record, replacement);
|
|
455
|
+
}
|
|
317
456
|
|
|
318
457
|
//#endregion
|
|
319
458
|
//#region src/core/parser/constants.ts
|
|
@@ -1208,12 +1347,13 @@ function createProxyVariable(id) {
|
|
|
1208
1347
|
* @param deps - 依赖集合
|
|
1209
1348
|
* @returns Proxy 包装的 Expression
|
|
1210
1349
|
*/
|
|
1211
|
-
function createProxyExpressionWithAST(ast, deps) {
|
|
1350
|
+
function createProxyExpressionWithAST(ast, deps, deferredAsts) {
|
|
1212
1351
|
const proxy = new Proxy(function() {}, createProxyHandler(ast, deps));
|
|
1213
1352
|
setProxyMetadata(proxy, {
|
|
1214
1353
|
type: "expression",
|
|
1215
1354
|
ast,
|
|
1216
|
-
dependencies: deps
|
|
1355
|
+
dependencies: deps,
|
|
1356
|
+
deferredAsts
|
|
1217
1357
|
});
|
|
1218
1358
|
return proxy;
|
|
1219
1359
|
}
|
|
@@ -1286,6 +1426,7 @@ function expr(context) {
|
|
|
1286
1426
|
return (source) => {
|
|
1287
1427
|
const deps = /* @__PURE__ */ new Set();
|
|
1288
1428
|
const nameToId = /* @__PURE__ */ new Map();
|
|
1429
|
+
const nameToExprAST = /* @__PURE__ */ new Map();
|
|
1289
1430
|
for (const [name, value] of Object.entries(context)) {
|
|
1290
1431
|
let id = getVariableId(value);
|
|
1291
1432
|
if (!id && (typeof value === "object" || typeof value === "function") && value !== null) {
|
|
@@ -1298,24 +1439,15 @@ function expr(context) {
|
|
|
1298
1439
|
} else {
|
|
1299
1440
|
const meta = (typeof value === "object" || typeof value === "function") && value !== null ? getProxyMetadata(value) : void 0;
|
|
1300
1441
|
if (meta?.dependencies) for (const dep of meta.dependencies) deps.add(dep);
|
|
1442
|
+
if (meta?.ast) nameToExprAST.set(name, meta.ast);
|
|
1301
1443
|
}
|
|
1302
1444
|
}
|
|
1303
|
-
const
|
|
1304
|
-
|
|
1305
|
-
|
|
1306
|
-
|
|
1307
|
-
|
|
1308
|
-
|
|
1309
|
-
return createProxyExpressionWithAST(transformIdentifiers(parse(source), (name) => {
|
|
1310
|
-
const id = nameToId.get(name);
|
|
1311
|
-
if (id) return {
|
|
1312
|
-
type: "Placeholder",
|
|
1313
|
-
id
|
|
1314
|
-
};
|
|
1315
|
-
const exprAST = nameToExprAST.get(name);
|
|
1316
|
-
if (exprAST) return exprAST;
|
|
1317
|
-
return name;
|
|
1318
|
-
}), deps);
|
|
1445
|
+
const ast = parse(source);
|
|
1446
|
+
const { ast: transformedAst, deferredAsts } = nameToExprAST.size === 0 ? {
|
|
1447
|
+
ast: transformExprVariables(ast, nameToId),
|
|
1448
|
+
deferredAsts: void 0
|
|
1449
|
+
} : transformExprIdentifiers(ast, nameToId, nameToExprAST);
|
|
1450
|
+
return createProxyExpressionWithAST(transformedAst, deps, deferredAsts);
|
|
1319
1451
|
};
|
|
1320
1452
|
}
|
|
1321
1453
|
|
|
@@ -1577,10 +1709,12 @@ const BRANCH_CONDITIONS = {
|
|
|
1577
1709
|
* ```
|
|
1578
1710
|
*/
|
|
1579
1711
|
function compile(expression, variables, _options = {}) {
|
|
1712
|
+
let deferredAsts;
|
|
1713
|
+
if ((typeof expression === "object" || typeof expression === "function") && expression !== null) deferredAsts = getProxyMetadata(expression)?.deferredAsts;
|
|
1580
1714
|
const ast = serializeArgumentToAST(expression);
|
|
1581
1715
|
const variableOrder = [];
|
|
1582
1716
|
const variableToIndex = /* @__PURE__ */ new Map();
|
|
1583
|
-
const
|
|
1717
|
+
const placeholderNames = /* @__PURE__ */ new Map();
|
|
1584
1718
|
for (const [name, value] of Object.entries(variables)) {
|
|
1585
1719
|
if (!variableToIndex.has(name)) {
|
|
1586
1720
|
const index = variableOrder.length;
|
|
@@ -1588,31 +1722,27 @@ function compile(expression, variables, _options = {}) {
|
|
|
1588
1722
|
variableOrder.push(name);
|
|
1589
1723
|
}
|
|
1590
1724
|
const id = getVariableId(value);
|
|
1591
|
-
if (id)
|
|
1725
|
+
if (id) placeholderNames.set(id, `$[${variableToIndex.get(name)}]`);
|
|
1592
1726
|
}
|
|
1593
|
-
const placeholderTransformed = transformPlaceholders(ast, (id) => {
|
|
1594
|
-
const name = symbolToName.get(id);
|
|
1595
|
-
if (!name) return null;
|
|
1596
|
-
const index = variableToIndex.get(name);
|
|
1597
|
-
return index !== void 0 ? `$[${index}]` : null;
|
|
1598
|
-
});
|
|
1599
|
-
const undefinedVars = [];
|
|
1600
|
-
const transformed = transformIdentifiers(placeholderTransformed, (name) => {
|
|
1601
|
-
if (/^\$\[\d+\]$/.test(name)) return name;
|
|
1602
|
-
if (/^_\d+$/.test(name)) return name;
|
|
1603
|
-
const index = variableToIndex.get(name);
|
|
1604
|
-
if (index !== void 0) return `$[${index}]`;
|
|
1605
|
-
if (!ALLOWED_GLOBALS.has(name)) undefinedVars.push(name);
|
|
1606
|
-
return name;
|
|
1607
|
-
});
|
|
1608
|
-
if (undefinedVars.length > 0) throw new Error(`Undefined variable(s): ${[...new Set(undefinedVars)].join(", ")}`);
|
|
1609
1727
|
const topLevelExprs = [];
|
|
1610
|
-
|
|
1728
|
+
const baseScope = { placeholderNames };
|
|
1729
|
+
const ctx = {
|
|
1611
1730
|
nextParamIndex: 0,
|
|
1612
1731
|
expressionStack: [topLevelExprs],
|
|
1613
1732
|
nextIndex: variableOrder.length,
|
|
1614
|
-
variableCount: variableOrder.length
|
|
1733
|
+
variableCount: variableOrder.length,
|
|
1734
|
+
baseScope
|
|
1735
|
+
};
|
|
1736
|
+
const deferredIndexMap = /* @__PURE__ */ new Map();
|
|
1737
|
+
if (deferredAsts && deferredAsts.size > 0) compileDeferredExprs(deferredAsts, ctx, baseScope, deferredIndexMap);
|
|
1738
|
+
const undefinedVars = [];
|
|
1739
|
+
const transformed = rewriteAstForCompile(ast, {
|
|
1740
|
+
...baseScope,
|
|
1741
|
+
deferredIndexMap,
|
|
1742
|
+
undefinedVars
|
|
1615
1743
|
});
|
|
1744
|
+
if (undefinedVars.length > 0) throw new Error(`Undefined variable(s): ${[...new Set(undefinedVars)].join(", ")}`);
|
|
1745
|
+
compileAst(transformed, ctx, baseScope);
|
|
1616
1746
|
return [variableOrder, ...topLevelExprs];
|
|
1617
1747
|
}
|
|
1618
1748
|
/**
|
|
@@ -1622,66 +1752,187 @@ function currentExprs(ctx) {
|
|
|
1622
1752
|
return ctx.expressionStack[ctx.expressionStack.length - 1];
|
|
1623
1753
|
}
|
|
1624
1754
|
/**
|
|
1755
|
+
* 编译推迟的子表达式(因引用计数 >1 未内联)
|
|
1756
|
+
* 使用递归处理,自动按依赖拓扑顺序编译
|
|
1757
|
+
*/
|
|
1758
|
+
function compileDeferredExprs(deferredAsts, ctx, baseScope, deferredIndexMap) {
|
|
1759
|
+
const processing = /* @__PURE__ */ new Set();
|
|
1760
|
+
function compileOne(name) {
|
|
1761
|
+
if (processing.has(name)) throw new Error(`Circular reference in deferred expressions: ${name}`);
|
|
1762
|
+
const existing = deferredIndexMap.get(name);
|
|
1763
|
+
if (existing !== void 0) return existing;
|
|
1764
|
+
const ast = deferredAsts.get(name);
|
|
1765
|
+
if (!ast) throw new Error(`Unknown deferred expression: ${name}`);
|
|
1766
|
+
processing.add(name);
|
|
1767
|
+
const undefinedVars = [];
|
|
1768
|
+
const transformed = rewriteAstForCompile(ast, {
|
|
1769
|
+
...baseScope,
|
|
1770
|
+
deferredAsts,
|
|
1771
|
+
deferredIndexMap,
|
|
1772
|
+
onDeferredReference: compileOne,
|
|
1773
|
+
undefinedVars
|
|
1774
|
+
});
|
|
1775
|
+
if (undefinedVars.length > 0) throw new Error(`Undefined variable(s) in deferred expression "${name}": ${[...new Set(undefinedVars)].join(", ")}`);
|
|
1776
|
+
const idx = compileAst(transformed, ctx, baseScope);
|
|
1777
|
+
deferredIndexMap.set(name, idx);
|
|
1778
|
+
processing.delete(name);
|
|
1779
|
+
return idx;
|
|
1780
|
+
}
|
|
1781
|
+
for (const name of deferredAsts.keys()) compileOne(name);
|
|
1782
|
+
}
|
|
1783
|
+
function rewriteAstForCompile(node, scope) {
|
|
1784
|
+
switch (node.type) {
|
|
1785
|
+
case "Placeholder": {
|
|
1786
|
+
const name = scope.placeholderNames.get(node.id);
|
|
1787
|
+
return name ? {
|
|
1788
|
+
type: "Identifier",
|
|
1789
|
+
name
|
|
1790
|
+
} : node;
|
|
1791
|
+
}
|
|
1792
|
+
case "Identifier": {
|
|
1793
|
+
if (scope.shadowedNames?.has(node.name)) return node;
|
|
1794
|
+
const resolved = resolveIdentifierName(node.name, scope);
|
|
1795
|
+
return resolved === node.name ? node : {
|
|
1796
|
+
...node,
|
|
1797
|
+
name: resolved
|
|
1798
|
+
};
|
|
1799
|
+
}
|
|
1800
|
+
case "BinaryExpr": {
|
|
1801
|
+
const left = rewriteAstForCompile(node.left, scope);
|
|
1802
|
+
const right = rewriteAstForCompile(node.right, scope);
|
|
1803
|
+
return left === node.left && right === node.right ? node : {
|
|
1804
|
+
...node,
|
|
1805
|
+
left,
|
|
1806
|
+
right
|
|
1807
|
+
};
|
|
1808
|
+
}
|
|
1809
|
+
case "UnaryExpr": {
|
|
1810
|
+
const argument = rewriteAstForCompile(node.argument, scope);
|
|
1811
|
+
return argument === node.argument ? node : {
|
|
1812
|
+
...node,
|
|
1813
|
+
argument
|
|
1814
|
+
};
|
|
1815
|
+
}
|
|
1816
|
+
case "ConditionalExpr": {
|
|
1817
|
+
const test = rewriteAstForCompile(node.test, scope);
|
|
1818
|
+
const consequent = rewriteAstForCompile(node.consequent, scope);
|
|
1819
|
+
const alternate = rewriteAstForCompile(node.alternate, scope);
|
|
1820
|
+
return test === node.test && consequent === node.consequent && alternate === node.alternate ? node : {
|
|
1821
|
+
...node,
|
|
1822
|
+
test,
|
|
1823
|
+
consequent,
|
|
1824
|
+
alternate
|
|
1825
|
+
};
|
|
1826
|
+
}
|
|
1827
|
+
case "MemberExpr": {
|
|
1828
|
+
const object = rewriteAstForCompile(node.object, scope);
|
|
1829
|
+
const property = node.computed ? rewriteAstForCompile(node.property, scope) : node.property;
|
|
1830
|
+
return object === node.object && property === node.property ? node : {
|
|
1831
|
+
...node,
|
|
1832
|
+
object,
|
|
1833
|
+
property
|
|
1834
|
+
};
|
|
1835
|
+
}
|
|
1836
|
+
case "CallExpr": {
|
|
1837
|
+
const callee = rewriteAstForCompile(node.callee, scope);
|
|
1838
|
+
const arguments_ = mapAstNodes(node.arguments, (arg) => rewriteAstForCompile(arg, scope));
|
|
1839
|
+
return callee === node.callee && arguments_ === node.arguments ? node : {
|
|
1840
|
+
...node,
|
|
1841
|
+
callee,
|
|
1842
|
+
arguments: arguments_
|
|
1843
|
+
};
|
|
1844
|
+
}
|
|
1845
|
+
case "ArrayExpr": {
|
|
1846
|
+
const elements = mapAstNodes(node.elements, (el) => rewriteAstForCompile(el, scope));
|
|
1847
|
+
return elements === node.elements ? node : {
|
|
1848
|
+
...node,
|
|
1849
|
+
elements
|
|
1850
|
+
};
|
|
1851
|
+
}
|
|
1852
|
+
case "ObjectExpr": {
|
|
1853
|
+
const properties = mapObjectProperties(node.properties, (prop) => {
|
|
1854
|
+
const key = prop.computed ? rewriteAstForCompile(prop.key, scope) : prop.key;
|
|
1855
|
+
const value = rewriteAstForCompile(prop.value, scope);
|
|
1856
|
+
return key === prop.key && value === prop.value ? prop : {
|
|
1857
|
+
...prop,
|
|
1858
|
+
key,
|
|
1859
|
+
value
|
|
1860
|
+
};
|
|
1861
|
+
});
|
|
1862
|
+
return properties === node.properties ? node : {
|
|
1863
|
+
...node,
|
|
1864
|
+
properties
|
|
1865
|
+
};
|
|
1866
|
+
}
|
|
1867
|
+
case "ArrowFunctionExpr": return node;
|
|
1868
|
+
default: return node;
|
|
1869
|
+
}
|
|
1870
|
+
}
|
|
1871
|
+
function resolveIdentifierName(name, scope) {
|
|
1872
|
+
if (/^\$\[\d+\]$/.test(name) || /^_\d+$/.test(name)) return name;
|
|
1873
|
+
const deferredIdx = scope.deferredIndexMap?.get(name);
|
|
1874
|
+
if (deferredIdx !== void 0) return `$[${deferredIdx}]`;
|
|
1875
|
+
if (scope.deferredAsts?.has(name) && scope.onDeferredReference) return `$[${scope.onDeferredReference(name)}]`;
|
|
1876
|
+
if (!ALLOWED_GLOBALS.has(name)) scope.undefinedVars?.push(name);
|
|
1877
|
+
return name;
|
|
1878
|
+
}
|
|
1879
|
+
function extendShadowedNames(shadowedNames, names) {
|
|
1880
|
+
if (names.length === 0) return shadowedNames;
|
|
1881
|
+
return new Set([...shadowedNames ?? [], ...names]);
|
|
1882
|
+
}
|
|
1883
|
+
function mapAstNodes(nodes, transform) {
|
|
1884
|
+
let result;
|
|
1885
|
+
for (let i = 0; i < nodes.length; i++) {
|
|
1886
|
+
const node = nodes[i];
|
|
1887
|
+
const transformed = transform(node);
|
|
1888
|
+
if (result) {
|
|
1889
|
+
result.push(transformed);
|
|
1890
|
+
continue;
|
|
1891
|
+
}
|
|
1892
|
+
if (transformed !== node) {
|
|
1893
|
+
result = nodes.slice(0, i);
|
|
1894
|
+
result.push(transformed);
|
|
1895
|
+
}
|
|
1896
|
+
}
|
|
1897
|
+
return result ?? nodes;
|
|
1898
|
+
}
|
|
1899
|
+
function mapObjectProperties(properties, transform) {
|
|
1900
|
+
let result;
|
|
1901
|
+
for (let i = 0; i < properties.length; i++) {
|
|
1902
|
+
const property = properties[i];
|
|
1903
|
+
const transformed = transform(property);
|
|
1904
|
+
if (result) {
|
|
1905
|
+
result.push(transformed);
|
|
1906
|
+
continue;
|
|
1907
|
+
}
|
|
1908
|
+
if (transformed !== property) {
|
|
1909
|
+
result = properties.slice(0, i);
|
|
1910
|
+
result.push(transformed);
|
|
1911
|
+
}
|
|
1912
|
+
}
|
|
1913
|
+
return result ?? properties;
|
|
1914
|
+
}
|
|
1915
|
+
/**
|
|
1625
1916
|
* 提取 AST 中所有 ArrowFunctionExpr 节点,编译为 FnNode,
|
|
1626
1917
|
* 并将原始位置替换为 $[N] 标识符引用。
|
|
1627
1918
|
*/
|
|
1628
|
-
function
|
|
1629
|
-
|
|
1630
|
-
|
|
1919
|
+
function compileAst(node, ctx, scope) {
|
|
1920
|
+
if (node.type === "BinaryExpr" && (node.operator === "||" || node.operator === "&&" || node.operator === "??")) return compileShortCircuit(node, ctx, scope);
|
|
1921
|
+
if (node.type === "ConditionalExpr") return compileConditional(node, ctx, scope);
|
|
1922
|
+
if (node.type === "ArrowFunctionExpr") return compileArrowFunction(node, ctx, scope);
|
|
1923
|
+
const exprStr = generate(node, { rewriteNode: (current) => {
|
|
1924
|
+
if (current.type !== "ArrowFunctionExpr") return current;
|
|
1925
|
+
return {
|
|
1631
1926
|
type: "Identifier",
|
|
1632
|
-
name: `$[${compileArrowFunction(
|
|
1633
|
-
};
|
|
1634
|
-
case "BinaryExpr": return {
|
|
1635
|
-
...node,
|
|
1636
|
-
left: extractAndCompileArrowFunctions(node.left, ctx),
|
|
1637
|
-
right: extractAndCompileArrowFunctions(node.right, ctx)
|
|
1638
|
-
};
|
|
1639
|
-
case "UnaryExpr": return {
|
|
1640
|
-
...node,
|
|
1641
|
-
argument: extractAndCompileArrowFunctions(node.argument, ctx)
|
|
1642
|
-
};
|
|
1643
|
-
case "ConditionalExpr": return {
|
|
1644
|
-
...node,
|
|
1645
|
-
test: extractAndCompileArrowFunctions(node.test, ctx),
|
|
1646
|
-
consequent: extractAndCompileArrowFunctions(node.consequent, ctx),
|
|
1647
|
-
alternate: extractAndCompileArrowFunctions(node.alternate, ctx)
|
|
1648
|
-
};
|
|
1649
|
-
case "MemberExpr": return {
|
|
1650
|
-
...node,
|
|
1651
|
-
object: extractAndCompileArrowFunctions(node.object, ctx),
|
|
1652
|
-
property: node.computed ? extractAndCompileArrowFunctions(node.property, ctx) : node.property
|
|
1927
|
+
name: `$[${compileArrowFunction(current, ctx, scope)}]`
|
|
1653
1928
|
};
|
|
1654
|
-
|
|
1655
|
-
...node,
|
|
1656
|
-
callee: extractAndCompileArrowFunctions(node.callee, ctx),
|
|
1657
|
-
arguments: node.arguments.map((arg) => extractAndCompileArrowFunctions(arg, ctx))
|
|
1658
|
-
};
|
|
1659
|
-
case "ArrayExpr": return {
|
|
1660
|
-
...node,
|
|
1661
|
-
elements: node.elements.map((el) => extractAndCompileArrowFunctions(el, ctx))
|
|
1662
|
-
};
|
|
1663
|
-
case "ObjectExpr": return {
|
|
1664
|
-
...node,
|
|
1665
|
-
properties: node.properties.map((prop) => ({
|
|
1666
|
-
...prop,
|
|
1667
|
-
key: prop.computed ? extractAndCompileArrowFunctions(prop.key, ctx) : prop.key,
|
|
1668
|
-
value: extractAndCompileArrowFunctions(prop.value, ctx)
|
|
1669
|
-
}))
|
|
1670
|
-
};
|
|
1671
|
-
default: return node;
|
|
1672
|
-
}
|
|
1673
|
-
}
|
|
1674
|
-
function compileAst(node, ctx) {
|
|
1675
|
-
if (node.type === "BinaryExpr" && (node.operator === "||" || node.operator === "&&" || node.operator === "??")) return compileShortCircuit(node, ctx);
|
|
1676
|
-
if (node.type === "ConditionalExpr") return compileConditional(node, ctx);
|
|
1677
|
-
if (node.type === "ArrowFunctionExpr") return compileArrowFunction(node, ctx);
|
|
1678
|
-
const exprStr = generate(extractAndCompileArrowFunctions(node, ctx));
|
|
1929
|
+
} });
|
|
1679
1930
|
currentExprs(ctx).push(exprStr);
|
|
1680
1931
|
return ctx.nextIndex++;
|
|
1681
1932
|
}
|
|
1682
|
-
function compileShortCircuit(node, ctx) {
|
|
1933
|
+
function compileShortCircuit(node, ctx, scope) {
|
|
1683
1934
|
const exprs = currentExprs(ctx);
|
|
1684
|
-
const leftIdx = compileAst(node.left, ctx);
|
|
1935
|
+
const leftIdx = compileAst(node.left, ctx, scope);
|
|
1685
1936
|
const condition = BRANCH_CONDITIONS[node.operator]?.(leftIdx);
|
|
1686
1937
|
if (!condition) throw new Error(`Unexpected operator: ${node.operator}`);
|
|
1687
1938
|
const branchIdx = exprs.length;
|
|
@@ -1691,16 +1942,16 @@ function compileShortCircuit(node, ctx) {
|
|
|
1691
1942
|
0
|
|
1692
1943
|
]);
|
|
1693
1944
|
ctx.nextIndex++;
|
|
1694
|
-
compileAst(node.right, ctx);
|
|
1945
|
+
compileAst(node.right, ctx, scope);
|
|
1695
1946
|
const skipCount = exprs.length - branchIdx - 1;
|
|
1696
1947
|
exprs[branchIdx][2] = skipCount;
|
|
1697
1948
|
const phiIdx = ctx.nextIndex++;
|
|
1698
1949
|
exprs.push(["phi"]);
|
|
1699
1950
|
return phiIdx;
|
|
1700
1951
|
}
|
|
1701
|
-
function compileConditional(node, ctx) {
|
|
1952
|
+
function compileConditional(node, ctx, scope) {
|
|
1702
1953
|
const exprs = currentExprs(ctx);
|
|
1703
|
-
const testIdx = compileAst(node.test, ctx);
|
|
1954
|
+
const testIdx = compileAst(node.test, ctx, scope);
|
|
1704
1955
|
const branchIdx = exprs.length;
|
|
1705
1956
|
exprs.push([
|
|
1706
1957
|
"br",
|
|
@@ -1708,11 +1959,11 @@ function compileConditional(node, ctx) {
|
|
|
1708
1959
|
0
|
|
1709
1960
|
]);
|
|
1710
1961
|
ctx.nextIndex++;
|
|
1711
|
-
compileAst(node.alternate, ctx);
|
|
1962
|
+
compileAst(node.alternate, ctx, scope);
|
|
1712
1963
|
const jmpIdx = exprs.length;
|
|
1713
1964
|
exprs.push(["jmp", 0]);
|
|
1714
1965
|
ctx.nextIndex++;
|
|
1715
|
-
compileAst(node.consequent, ctx);
|
|
1966
|
+
compileAst(node.consequent, ctx, scope);
|
|
1716
1967
|
const thenEndIdx = exprs.length;
|
|
1717
1968
|
exprs[branchIdx][2] = jmpIdx - branchIdx;
|
|
1718
1969
|
exprs[jmpIdx][1] = thenEndIdx - jmpIdx - 1;
|
|
@@ -1720,14 +1971,21 @@ function compileConditional(node, ctx) {
|
|
|
1720
1971
|
exprs.push(["phi"]);
|
|
1721
1972
|
return phiIdx;
|
|
1722
1973
|
}
|
|
1723
|
-
function compileArrowFunction(node, ctx) {
|
|
1974
|
+
function compileArrowFunction(node, ctx, scope) {
|
|
1724
1975
|
const fnIndex = ctx.nextIndex++;
|
|
1725
|
-
const
|
|
1726
|
-
|
|
1727
|
-
const
|
|
1976
|
+
const placeholderNames = new Map(scope.placeholderNames);
|
|
1977
|
+
const shadowedNames = [];
|
|
1978
|
+
for (const param of node.params) if (param.type === "Placeholder") placeholderNames.set(param.id, `_${ctx.nextParamIndex++}`);
|
|
1979
|
+
else shadowedNames.push(param.name);
|
|
1980
|
+
const lambdaScope = {
|
|
1981
|
+
...scope,
|
|
1982
|
+
placeholderNames,
|
|
1983
|
+
shadowedNames: extendShadowedNames(scope.shadowedNames, shadowedNames)
|
|
1984
|
+
};
|
|
1985
|
+
const transformedBody = rewriteAstForCompile(node.body, lambdaScope);
|
|
1728
1986
|
const lambdaStmts = [];
|
|
1729
1987
|
ctx.expressionStack.push(lambdaStmts);
|
|
1730
|
-
compileAst(transformedBody, ctx);
|
|
1988
|
+
compileAst(transformedBody, ctx, lambdaScope);
|
|
1731
1989
|
ctx.expressionStack.pop();
|
|
1732
1990
|
const fnNode = [
|
|
1733
1991
|
"fn",
|
|
@@ -1741,9 +1999,40 @@ function compileArrowFunction(node, ctx) {
|
|
|
1741
1999
|
//#endregion
|
|
1742
2000
|
//#region src/core/evaluate.ts
|
|
1743
2001
|
/**
|
|
1744
|
-
*
|
|
2002
|
+
* 一级缓存:WeakMap - 使用 CompiledData 对象引用作为 key
|
|
2003
|
+
* 优势:O(1) 查找,无序列化开销,自动 GC
|
|
2004
|
+
* 适用:相同引用被重复使用的场景
|
|
2005
|
+
*/
|
|
2006
|
+
const weakEvaluatorCache = /* @__PURE__ */ new WeakMap();
|
|
2007
|
+
/**
|
|
2008
|
+
* 二级缓存:LRU Map - 使用编译数据指纹作为 key
|
|
2009
|
+
* 优势:支持内容相同但引用不同的对象,有大小限制避免内存泄漏
|
|
2010
|
+
* 适用:CompiledData 被频繁重建但内容重复的场景
|
|
1745
2011
|
*/
|
|
1746
|
-
const
|
|
2012
|
+
const MAX_LRU_CACHE_SIZE = 128;
|
|
2013
|
+
const lruEvaluatorCache = /* @__PURE__ */ new Map();
|
|
2014
|
+
/**
|
|
2015
|
+
* 从 LRU 缓存获取求值函数,并将命中项移至末尾(最近使用)
|
|
2016
|
+
*/
|
|
2017
|
+
function getFromLruCache(key) {
|
|
2018
|
+
const evaluator = lruEvaluatorCache.get(key);
|
|
2019
|
+
if (evaluator) {
|
|
2020
|
+
lruEvaluatorCache.delete(key);
|
|
2021
|
+
lruEvaluatorCache.set(key, evaluator);
|
|
2022
|
+
}
|
|
2023
|
+
return evaluator;
|
|
2024
|
+
}
|
|
2025
|
+
/**
|
|
2026
|
+
* 向 LRU 缓存写入求值函数,超出限制时淘汰最久未使用的项
|
|
2027
|
+
*/
|
|
2028
|
+
function setToLruCache(key, evaluator) {
|
|
2029
|
+
if (lruEvaluatorCache.has(key)) lruEvaluatorCache.delete(key);
|
|
2030
|
+
else if (lruEvaluatorCache.size >= MAX_LRU_CACHE_SIZE) {
|
|
2031
|
+
const firstKey = lruEvaluatorCache.keys().next().value;
|
|
2032
|
+
if (firstKey !== void 0) lruEvaluatorCache.delete(firstKey);
|
|
2033
|
+
}
|
|
2034
|
+
lruEvaluatorCache.set(key, evaluator);
|
|
2035
|
+
}
|
|
1747
2036
|
/**
|
|
1748
2037
|
* 判断是否是 FnNode
|
|
1749
2038
|
*/
|
|
@@ -1904,21 +2193,29 @@ function translateControlFlow(expressions, variableCount) {
|
|
|
1904
2193
|
* ```
|
|
1905
2194
|
*/
|
|
1906
2195
|
function evaluate(data, values) {
|
|
1907
|
-
|
|
1908
|
-
|
|
1909
|
-
if (
|
|
1910
|
-
|
|
1911
|
-
if (
|
|
1912
|
-
|
|
2196
|
+
let evaluator = weakEvaluatorCache.get(data);
|
|
2197
|
+
let variableNames;
|
|
2198
|
+
if (evaluator) variableNames = data[0];
|
|
2199
|
+
else {
|
|
2200
|
+
if (data.length < 1) throw new Error("Invalid compiled data: must have at least variable names");
|
|
2201
|
+
variableNames = data[0];
|
|
2202
|
+
if (!Array.isArray(variableNames)) throw new Error("Invalid compiled data: first element must be variable names array");
|
|
2203
|
+
for (let i = 0; i < variableNames.length; i++) if (typeof variableNames[i] !== "string") throw new Error("Invalid compiled data: variable names must be strings");
|
|
2204
|
+
const cacheKey = JSON.stringify(data);
|
|
2205
|
+
evaluator = getFromLruCache(cacheKey);
|
|
2206
|
+
if (!evaluator) {
|
|
2207
|
+
const functionBody = buildEvaluatorFunctionBody(data.slice(1), variableNames.length);
|
|
2208
|
+
evaluator = new Function("$", functionBody);
|
|
2209
|
+
setToLruCache(cacheKey, evaluator);
|
|
2210
|
+
}
|
|
2211
|
+
weakEvaluatorCache.set(data, evaluator);
|
|
1913
2212
|
}
|
|
2213
|
+
const len = variableNames.length;
|
|
1914
2214
|
const valueArray = [];
|
|
1915
|
-
for (
|
|
1916
|
-
|
|
1917
|
-
|
|
1918
|
-
|
|
1919
|
-
const functionBody = buildEvaluatorFunctionBody(expressions, variableNames.length);
|
|
1920
|
-
evaluator = new Function("$", functionBody);
|
|
1921
|
-
evaluatorCache.set(cacheKey, evaluator);
|
|
2215
|
+
for (let i = 0; i < len; i++) {
|
|
2216
|
+
const name = variableNames[i];
|
|
2217
|
+
if (!(name in values)) throw new Error(`Missing required variable: ${name}`);
|
|
2218
|
+
valueArray.push(values[name]);
|
|
1922
2219
|
}
|
|
1923
2220
|
try {
|
|
1924
2221
|
return evaluator(valueArray);
|