@codehz/json-expr 0.5.2 → 0.5.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 CHANGED
@@ -1,4 +1,4 @@
1
- //#region src/parser.ts
1
+ //#region src/ast-types.ts
2
2
  const PRECEDENCE = {
3
3
  "||": 1,
4
4
  "??": 1,
@@ -48,697 +48,609 @@ const BUILTIN_CONSTRUCTORS = new Set([
48
48
  "ArrayBuffer",
49
49
  "DataView"
50
50
  ]);
51
- var Parser = class Parser {
52
- pos = 0;
53
- source;
54
- constructor(source) {
55
- this.source = source;
56
- }
57
- parse() {
58
- this.skipWhitespace();
59
- const node = this.parseExpression();
60
- this.skipWhitespace();
61
- if (this.pos < this.source.length) throw new Error(`Unexpected token at position ${this.pos}: ${this.source.slice(this.pos, this.pos + 10)}`);
62
- return node;
51
+
52
+ //#endregion
53
+ //#region src/generate.ts
54
+ /**
55
+ * 创建新的生成上下文
56
+ */
57
+ function createGenerateContext() {
58
+ return {
59
+ lambdaParamCounter: 0,
60
+ paramMapping: /* @__PURE__ */ new Map()
61
+ };
62
+ }
63
+ /**
64
+ * 从 AST 生成规范化的代码
65
+ */
66
+ function generate(node) {
67
+ return generateWithContext(node, createGenerateContext());
68
+ }
69
+ /**
70
+ * 带上下文的代码生成
71
+ */
72
+ function generateWithContext(node, ctx) {
73
+ switch (node.type) {
74
+ case "NumberLiteral": return node.raw;
75
+ case "StringLiteral": return JSON.stringify(node.value);
76
+ case "BooleanLiteral": return node.value ? "true" : "false";
77
+ case "NullLiteral": return "null";
78
+ case "Identifier": return node.name;
79
+ case "Placeholder": {
80
+ const mappedName = ctx.paramMapping.get(node.id);
81
+ if (mappedName) return mappedName;
82
+ return `$$${node.id.description}$$`;
83
+ }
84
+ case "BinaryExpr": {
85
+ const left = wrapIfNeededWithContext(node.left, node, "left", ctx);
86
+ const right = wrapIfNeededWithContext(node.right, node, "right", ctx);
87
+ if (node.operator === "in" || node.operator === "instanceof") return `${left} ${node.operator} ${right}`;
88
+ return `${left}${node.operator}${right}`;
89
+ }
90
+ case "UnaryExpr":
91
+ if (node.prefix) {
92
+ const arg = wrapIfNeededWithContext(node.argument, node, "argument", ctx);
93
+ if (node.operator === "typeof" || node.operator === "void") return `${node.operator} ${arg}`;
94
+ return `${node.operator}${arg}`;
95
+ }
96
+ return generateWithContext(node.argument, ctx) + node.operator;
97
+ case "ConditionalExpr": return `${wrapIfNeededWithContext(node.test, node, "test", ctx)}?${wrapIfNeededWithContext(node.consequent, node, "consequent", ctx)}:${wrapIfNeededWithContext(node.alternate, node, "alternate", ctx)}`;
98
+ case "MemberExpr": {
99
+ const object = wrapIfNeededWithContext(node.object, node, "object", ctx);
100
+ const property = generateWithContext(node.property, ctx);
101
+ return node.computed ? `${object}${node.optional ? "?." : ""}[${property}]` : `${object}${node.optional ? "?." : "."}${property}`;
102
+ }
103
+ case "CallExpr": {
104
+ const callee = wrapIfNeededWithContext(node.callee, node, "callee", ctx);
105
+ const args = node.arguments.map((arg) => generateWithContext(arg, ctx)).join(",");
106
+ return `${node.callee.type === "Identifier" && BUILTIN_CONSTRUCTORS.has(node.callee.name) ? "new " : ""}${callee}${node.optional ? "?." : ""}(${args})`;
107
+ }
108
+ case "ArrayExpr": return `[${node.elements.map((el) => generateWithContext(el, ctx)).join(",")}]`;
109
+ case "ObjectExpr": return `{${node.properties.map((prop) => {
110
+ if (prop.shorthand) return generateWithContext(prop.key, ctx);
111
+ return `${prop.computed ? `[${generateWithContext(prop.key, ctx)}]` : generateWithContext(prop.key, ctx)}:${generateWithContext(prop.value, ctx)}`;
112
+ }).join(",")}}`;
113
+ case "ArrowFunctionExpr": {
114
+ const paramNames = [];
115
+ const placeholderIds = [];
116
+ for (const param of node.params) if (param.type === "Placeholder") {
117
+ const uniqueName = `_${ctx.lambdaParamCounter++}`;
118
+ paramNames.push(uniqueName);
119
+ placeholderIds.push(param.id);
120
+ ctx.paramMapping.set(param.id, uniqueName);
121
+ } else paramNames.push(param.name);
122
+ const paramsStr = paramNames.length === 1 ? paramNames[0] : `(${paramNames.join(",")})`;
123
+ const body = node.body.type === "ObjectExpr" ? `(${generateWithContext(node.body, ctx)})` : generateWithContext(node.body, ctx);
124
+ for (const id of placeholderIds) ctx.paramMapping.delete(id);
125
+ return `${paramsStr}=>${body}`;
126
+ }
127
+ default: {
128
+ const nodeType = node.type ?? "unknown";
129
+ throw new Error(`Unknown node type: ${nodeType}`);
130
+ }
63
131
  }
64
- parseExpression() {
65
- return this.parseConditional();
132
+ }
133
+ /**
134
+ * 判断是否需要括号包裹,并生成代码(带上下文版本)
135
+ */
136
+ function wrapIfNeededWithContext(child, parent, position, ctx) {
137
+ const code = generateWithContext(child, ctx);
138
+ if (needsParens(child, parent, position)) return `(${code})`;
139
+ return code;
140
+ }
141
+ /**
142
+ * 判断子节点是否需要括号
143
+ */
144
+ function needsParens(child, parent, position) {
145
+ switch (parent.type) {
146
+ case "BinaryExpr":
147
+ if (child.type === "ConditionalExpr" || child.type === "UnaryExpr") return true;
148
+ if (child.type === "BinaryExpr") {
149
+ const childPrec = PRECEDENCE[child.operator] ?? 0;
150
+ const parentPrec = PRECEDENCE[parent.operator] ?? 0;
151
+ if (childPrec < parentPrec) return true;
152
+ if (childPrec === parentPrec && position === "right" && !RIGHT_ASSOCIATIVE.has(parent.operator)) return true;
153
+ }
154
+ return false;
155
+ case "UnaryExpr": return position === "argument" && (child.type === "BinaryExpr" || child.type === "ConditionalExpr");
156
+ case "MemberExpr":
157
+ case "CallExpr":
158
+ if (position !== "object" && position !== "callee") return false;
159
+ if ([
160
+ "BinaryExpr",
161
+ "ConditionalExpr",
162
+ "UnaryExpr",
163
+ "ArrowFunctionExpr",
164
+ "ObjectExpr"
165
+ ].includes(child.type)) return true;
166
+ if (child.type === "NumberLiteral" && parent.type === "MemberExpr" && !parent.computed) return !child.raw.includes(".") && !child.raw.includes("e") && !child.raw.includes("x");
167
+ return false;
168
+ case "ConditionalExpr": return position === "test" && child.type === "ConditionalExpr";
169
+ default: return false;
66
170
  }
67
- parseConditional() {
68
- let node = this.parseBinary(0);
69
- this.skipWhitespace();
70
- if (this.peek() === "?") {
71
- this.advance();
72
- this.skipWhitespace();
73
- const consequent = this.parseExpression();
74
- this.skipWhitespace();
75
- this.expect(":");
76
- this.skipWhitespace();
77
- const alternate = this.parseExpression();
78
- node = {
79
- type: "ConditionalExpr",
80
- test: node,
81
- consequent,
82
- alternate
83
- };
171
+ }
172
+ /**
173
+ * 转换 AST 中的标识符
174
+ * 回调函数可以返回:
175
+ * - string: 替换标识符名称
176
+ * - ASTNode: 内联该 AST 节点(用于子表达式内联)
177
+ */
178
+ function transformIdentifiers(node, transform) {
179
+ switch (node.type) {
180
+ case "Identifier": {
181
+ const result = transform(node.name);
182
+ return typeof result === "string" ? {
183
+ ...node,
184
+ name: result
185
+ } : result;
84
186
  }
85
- return node;
86
- }
87
- parseBinary(minPrec) {
88
- let left = this.parseUnary();
89
- while (true) {
90
- this.skipWhitespace();
91
- const op = this.peekOperator();
92
- if (!op || PRECEDENCE[op] === void 0 || PRECEDENCE[op] < minPrec) break;
93
- this.pos += op.length;
94
- this.skipWhitespace();
95
- const nextMinPrec = RIGHT_ASSOCIATIVE.has(op) ? PRECEDENCE[op] : PRECEDENCE[op] + 1;
96
- const right = this.parseBinary(nextMinPrec);
97
- left = {
98
- type: "BinaryExpr",
99
- operator: op,
100
- left,
101
- right
187
+ case "Placeholder": return node;
188
+ case "BinaryExpr": return {
189
+ ...node,
190
+ left: transformIdentifiers(node.left, transform),
191
+ right: transformIdentifiers(node.right, transform)
192
+ };
193
+ case "UnaryExpr": return {
194
+ ...node,
195
+ argument: transformIdentifiers(node.argument, transform)
196
+ };
197
+ case "ConditionalExpr": return {
198
+ ...node,
199
+ test: transformIdentifiers(node.test, transform),
200
+ consequent: transformIdentifiers(node.consequent, transform),
201
+ alternate: transformIdentifiers(node.alternate, transform)
202
+ };
203
+ case "MemberExpr": return {
204
+ ...node,
205
+ object: transformIdentifiers(node.object, transform),
206
+ property: node.computed ? transformIdentifiers(node.property, transform) : node.property
207
+ };
208
+ case "CallExpr": return {
209
+ ...node,
210
+ callee: transformIdentifiers(node.callee, transform),
211
+ arguments: node.arguments.map((arg) => transformIdentifiers(arg, transform))
212
+ };
213
+ case "ArrayExpr": return {
214
+ ...node,
215
+ elements: node.elements.map((el) => transformIdentifiers(el, transform))
216
+ };
217
+ case "ObjectExpr": return {
218
+ ...node,
219
+ properties: node.properties.map((prop) => ({
220
+ ...prop,
221
+ key: prop.computed ? transformIdentifiers(prop.key, transform) : prop.key,
222
+ value: transformIdentifiers(prop.value, transform)
223
+ }))
224
+ };
225
+ case "ArrowFunctionExpr": {
226
+ const paramNames = new Set(node.params.filter((p) => p.type === "Identifier").map((p) => p.name));
227
+ return {
228
+ ...node,
229
+ body: transformIdentifiers(node.body, (name) => paramNames.has(name) ? name : transform(name))
102
230
  };
103
231
  }
104
- return left;
232
+ default: return node;
105
233
  }
106
- parseUnary() {
107
- this.skipWhitespace();
108
- const ch = this.peek();
109
- if (ch === "!" || ch === "~" || ch === "+" || ch === "-") {
110
- this.advance();
111
- this.skipWhitespace();
112
- return {
113
- type: "UnaryExpr",
114
- operator: ch,
115
- argument: this.parseUnary(),
116
- prefix: true
117
- };
234
+ }
235
+ /**
236
+ * 转换 AST 中的占位符节点
237
+ * 回调函数接收 symbol,返回 Identifier 节点的名称
238
+ * 如果返回 null/undefined,则保留原始 Placeholder 节点
239
+ */
240
+ function transformPlaceholders(node, transform) {
241
+ switch (node.type) {
242
+ case "Placeholder": {
243
+ const name = transform(node.id);
244
+ return name != null ? {
245
+ type: "Identifier",
246
+ name
247
+ } : node;
118
248
  }
119
- for (const keyword of ["typeof", "void"]) if (this.matchKeyword(keyword)) {
120
- this.skipWhitespace();
249
+ case "Identifier": return node;
250
+ case "BinaryExpr": return {
251
+ ...node,
252
+ left: transformPlaceholders(node.left, transform),
253
+ right: transformPlaceholders(node.right, transform)
254
+ };
255
+ case "UnaryExpr": return {
256
+ ...node,
257
+ argument: transformPlaceholders(node.argument, transform)
258
+ };
259
+ case "ConditionalExpr": return {
260
+ ...node,
261
+ test: transformPlaceholders(node.test, transform),
262
+ consequent: transformPlaceholders(node.consequent, transform),
263
+ alternate: transformPlaceholders(node.alternate, transform)
264
+ };
265
+ case "MemberExpr": return {
266
+ ...node,
267
+ object: transformPlaceholders(node.object, transform),
268
+ property: node.computed ? transformPlaceholders(node.property, transform) : node.property
269
+ };
270
+ case "CallExpr": return {
271
+ ...node,
272
+ callee: transformPlaceholders(node.callee, transform),
273
+ arguments: node.arguments.map((arg) => transformPlaceholders(arg, transform))
274
+ };
275
+ case "ArrayExpr": return {
276
+ ...node,
277
+ elements: node.elements.map((el) => transformPlaceholders(el, transform))
278
+ };
279
+ case "ObjectExpr": return {
280
+ ...node,
281
+ properties: node.properties.map((prop) => ({
282
+ ...prop,
283
+ key: prop.computed ? transformPlaceholders(prop.key, transform) : prop.key,
284
+ value: transformPlaceholders(prop.value, transform)
285
+ }))
286
+ };
287
+ case "ArrowFunctionExpr": {
288
+ const paramSymbols = new Set(node.params.filter((p) => p.type === "Placeholder").map((p) => p.id));
121
289
  return {
122
- type: "UnaryExpr",
123
- operator: keyword,
124
- argument: this.parseUnary(),
125
- prefix: true
290
+ ...node,
291
+ body: transformPlaceholders(node.body, (id) => paramSymbols.has(id) ? null : transform(id))
126
292
  };
127
293
  }
128
- return this.parsePostfix();
294
+ default: return node;
129
295
  }
130
- parsePostfix() {
131
- let node = this.parsePrimary();
132
- while (true) {
133
- this.skipWhitespace();
134
- const ch = this.peek();
135
- if (ch === ".") {
136
- this.advance();
137
- this.skipWhitespace();
138
- const property = this.parseIdentifier();
139
- node = {
140
- type: "MemberExpr",
141
- object: node,
142
- property,
143
- computed: false,
144
- optional: false
145
- };
146
- } else if (ch === "[") {
147
- this.advance();
148
- this.skipWhitespace();
149
- const property = this.parseExpression();
150
- this.skipWhitespace();
151
- this.expect("]");
152
- node = {
153
- type: "MemberExpr",
154
- object: node,
155
- property,
156
- computed: true,
157
- optional: false
158
- };
159
- } else if (ch === "(") {
160
- this.advance();
161
- const args = this.parseArguments();
162
- this.expect(")");
163
- node = {
164
- type: "CallExpr",
165
- callee: node,
166
- arguments: args,
167
- optional: false
168
- };
169
- } else if (ch === "?" && this.peekAt(1) === ".") {
170
- this.advance();
171
- this.advance();
172
- this.skipWhitespace();
173
- if (this.peek() === "[") {
174
- this.advance();
175
- this.skipWhitespace();
176
- const property = this.parseExpression();
177
- this.skipWhitespace();
178
- this.expect("]");
179
- node = {
180
- type: "MemberExpr",
181
- object: node,
182
- property,
183
- computed: true,
184
- optional: true
185
- };
186
- } else if (this.peek() === "(") {
187
- this.advance();
188
- const args = this.parseArguments();
189
- this.expect(")");
190
- node = {
191
- type: "CallExpr",
192
- callee: node,
193
- arguments: args,
194
- optional: true
195
- };
196
- } else {
197
- const property = this.parseIdentifier();
198
- node = {
199
- type: "MemberExpr",
200
- object: node,
201
- property,
202
- computed: false,
203
- optional: true
204
- };
205
- }
206
- } else break;
207
- }
208
- return node;
209
- }
210
- parsePrimary() {
211
- this.skipWhitespace();
212
- const ch = this.peek();
213
- if (this.isDigit(ch) || ch === "." && this.isDigit(this.peekAt(1))) return this.parseNumber();
214
- if (ch === "\"" || ch === "'" || ch === "`") return this.parseString();
215
- if (ch === "[") return this.parseArray();
216
- if (ch === "{") return this.parseObject();
217
- if (ch === "(") {
218
- const arrowFunc = this.tryParseArrowFunction();
219
- if (arrowFunc) return arrowFunc;
220
- this.advance();
221
- this.skipWhitespace();
222
- const expr = this.parseExpression();
223
- this.skipWhitespace();
224
- this.expect(")");
225
- return expr;
226
- }
227
- if (this.matchKeyword("true")) return {
228
- type: "BooleanLiteral",
229
- value: true
230
- };
231
- if (this.matchKeyword("false")) return {
232
- type: "BooleanLiteral",
233
- value: false
234
- };
235
- if (this.matchKeyword("null")) return { type: "NullLiteral" };
236
- if (this.matchKeyword("undefined")) return {
237
- type: "Identifier",
238
- name: "undefined"
239
- };
240
- if (this.isIdentifierStart(ch)) {
241
- const arrowFunc = this.tryParseSingleParamArrowFunction();
242
- if (arrowFunc) return arrowFunc;
243
- return this.parseIdentifier();
244
- }
245
- throw new Error(`Unexpected character at position ${this.pos}: ${ch}`);
246
- }
247
- parseNumber() {
248
- const start = this.pos;
249
- if (this.peek() === "0") {
250
- const next = this.peekAt(1)?.toLowerCase();
251
- if (next === "x" || next === "o" || next === "b") {
252
- this.advance();
253
- this.advance();
254
- while (this.isHexDigit(this.peek())) this.advance();
255
- const raw = this.source.slice(start, this.pos);
256
- return {
257
- type: "NumberLiteral",
258
- value: Number(raw),
259
- raw
260
- };
261
- }
262
- }
263
- while (this.isDigit(this.peek())) this.advance();
264
- if (this.peek() === "." && this.isDigit(this.peekAt(1))) {
265
- this.advance();
266
- while (this.isDigit(this.peek())) this.advance();
267
- }
268
- if (this.peek()?.toLowerCase() === "e") {
269
- this.advance();
270
- if (this.peek() === "+" || this.peek() === "-") this.advance();
271
- while (this.isDigit(this.peek())) this.advance();
272
- }
273
- const raw = this.source.slice(start, this.pos);
274
- return {
275
- type: "NumberLiteral",
276
- value: Number(raw),
277
- raw
278
- };
279
- }
280
- static ESCAPE_CHARS = {
281
- n: "\n",
282
- r: "\r",
283
- t: " ",
284
- "\\": "\\",
285
- "'": "'",
286
- "\"": "\"",
287
- "`": "`"
296
+ }
297
+
298
+ //#endregion
299
+ //#region src/proxy-metadata.ts
300
+ /**
301
+ * 全局 WeakMap 存储
302
+ */
303
+ const proxyMetadata = /* @__PURE__ */ new WeakMap();
304
+ /**
305
+ * 设置 Proxy 元数据
306
+ */
307
+ function setProxyMetadata(proxy, metadata) {
308
+ proxyMetadata.set(proxy, metadata);
309
+ }
310
+ /**
311
+ * 获取 Proxy 元数据
312
+ */
313
+ function getProxyMetadata(proxy) {
314
+ return proxyMetadata.get(proxy);
315
+ }
316
+ /**
317
+ * 检查对象是否是 Proxy variable
318
+ */
319
+ function isProxyVariable(obj) {
320
+ if (typeof obj !== "object" && typeof obj !== "function" || obj === null) return false;
321
+ return proxyMetadata.get(obj)?.type === "variable";
322
+ }
323
+ /**
324
+ * 检查对象是否是 Proxy expression
325
+ */
326
+ function isProxyExpression(obj) {
327
+ if (typeof obj !== "object" && typeof obj !== "function" || obj === null) return false;
328
+ return proxyMetadata.get(obj)?.type === "expression";
329
+ }
330
+ /**
331
+ * 检查对象是否是任意 Proxy (variable 或 expression)
332
+ */
333
+ function isProxy(obj) {
334
+ if (typeof obj !== "object" && typeof obj !== "function" || obj === null) return false;
335
+ return proxyMetadata.has(obj);
336
+ }
337
+
338
+ //#endregion
339
+ //#region src/proxy-variable.ts
340
+ const typedArrayConstructors = [
341
+ "Int8Array",
342
+ "Uint8Array",
343
+ "Uint8ClampedArray",
344
+ "Int16Array",
345
+ "Uint16Array",
346
+ "Int32Array",
347
+ "Uint32Array",
348
+ "Float32Array",
349
+ "Float64Array",
350
+ "BigInt64Array",
351
+ "BigUint64Array"
352
+ ];
353
+ /**
354
+ * 创建占位符 AST 节点
355
+ */
356
+ function placeholder(id) {
357
+ return {
358
+ type: "Placeholder",
359
+ id
288
360
  };
289
- parseString() {
290
- const quote = this.peek();
291
- this.advance();
292
- let value = "";
293
- while (this.pos < this.source.length && this.peek() !== quote) if (this.peek() === "\\") {
294
- this.advance();
295
- const escaped = this.peek();
296
- value += Parser.ESCAPE_CHARS[escaped] ?? escaped;
297
- this.advance();
298
- } else {
299
- value += this.peek();
300
- this.advance();
301
- }
302
- this.expect(quote);
303
- return {
304
- type: "StringLiteral",
305
- value,
306
- quote
307
- };
308
- }
309
- parseArray() {
310
- this.expect("[");
311
- const elements = [];
312
- this.skipWhitespace();
313
- while (this.peek() !== "]") {
314
- elements.push(this.parseExpression());
315
- this.skipWhitespace();
316
- if (this.peek() === ",") {
317
- this.advance();
318
- this.skipWhitespace();
319
- } else break;
320
- }
321
- this.expect("]");
322
- return {
323
- type: "ArrayExpr",
324
- elements
325
- };
326
- }
327
- parseObject() {
328
- this.expect("{");
329
- const properties = [];
330
- this.skipWhitespace();
331
- while (this.peek() !== "}") {
332
- const prop = this.parseObjectProperty();
333
- properties.push(prop);
334
- this.skipWhitespace();
335
- if (this.peek() === ",") {
336
- this.advance();
337
- this.skipWhitespace();
338
- } else break;
339
- }
340
- this.expect("}");
341
- return {
342
- type: "ObjectExpr",
343
- properties
344
- };
345
- }
346
- parseObjectProperty() {
347
- this.skipWhitespace();
348
- let key;
349
- let computed = false;
350
- if (this.peek() === "[") {
351
- this.advance();
352
- this.skipWhitespace();
353
- key = this.parseExpression();
354
- this.skipWhitespace();
355
- this.expect("]");
356
- computed = true;
357
- } else if (this.peek() === "\"" || this.peek() === "'") key = this.parseString();
358
- else key = this.parseIdentifier();
359
- this.skipWhitespace();
360
- if (this.peek() === ":") {
361
- this.advance();
362
- this.skipWhitespace();
363
- const value = this.parseExpression();
364
- return {
365
- key,
366
- value,
367
- computed,
368
- shorthand: false
369
- };
370
- }
371
- if (key.type !== "Identifier") throw new Error("Shorthand property must be an identifier");
372
- return {
373
- key,
374
- value: key,
375
- computed: false,
376
- shorthand: true
377
- };
378
- }
379
- parseIdentifier() {
380
- const start = this.pos;
381
- while (this.isIdentifierPart(this.peek())) this.advance();
382
- const name = this.source.slice(start, this.pos);
383
- if (!name) throw new Error(`Expected identifier at position ${this.pos}`);
384
- return {
385
- type: "Identifier",
386
- name
387
- };
388
- }
389
- /**
390
- * 尝试解析带括号的箭头函数: (a, b) => expr
391
- * 使用回溯机制
392
- */
393
- tryParseArrowFunction() {
394
- const savedPos = this.pos;
395
- try {
396
- this.expect("(");
397
- this.skipWhitespace();
398
- const params = [];
399
- while (this.peek() !== ")") {
400
- if (!this.isIdentifierStart(this.peek())) throw new Error("Expected identifier");
401
- params.push(this.parseIdentifier());
402
- this.skipWhitespace();
403
- if (this.peek() === ",") {
404
- this.advance();
405
- this.skipWhitespace();
406
- } else break;
407
- }
408
- this.expect(")");
409
- this.skipWhitespace();
410
- if (this.source.slice(this.pos, this.pos + 2) !== "=>") throw new Error("Expected =>");
411
- this.pos += 2;
412
- this.skipWhitespace();
413
- return {
414
- type: "ArrowFunctionExpr",
415
- params,
416
- body: this.parseExpression()
417
- };
418
- } catch {
419
- this.pos = savedPos;
420
- return null;
421
- }
422
- }
423
- /**
424
- * 尝试解析单参数无括号的箭头函数: a => expr
425
- * 使用回溯机制
426
- */
427
- tryParseSingleParamArrowFunction() {
428
- const savedPos = this.pos;
429
- try {
430
- const param = this.parseIdentifier();
431
- this.skipWhitespace();
432
- if (this.source.slice(this.pos, this.pos + 2) !== "=>") throw new Error("Expected =>");
433
- this.pos += 2;
434
- this.skipWhitespace();
435
- const body = this.parseExpression();
436
- return {
437
- type: "ArrowFunctionExpr",
438
- params: [param],
439
- body
440
- };
441
- } catch {
442
- this.pos = savedPos;
443
- return null;
444
- }
445
- }
446
- parseArguments() {
447
- const args = [];
448
- this.skipWhitespace();
449
- while (this.peek() !== ")") {
450
- args.push(this.parseExpression());
451
- this.skipWhitespace();
452
- if (this.peek() === ",") {
453
- this.advance();
454
- this.skipWhitespace();
455
- } else break;
456
- }
457
- return args;
458
- }
459
- static OPERATORS = [
460
- "instanceof",
461
- ">>>",
462
- "===",
463
- "!==",
464
- "&&",
465
- "||",
466
- "??",
467
- "==",
468
- "!=",
469
- "<=",
470
- ">=",
471
- "<<",
472
- ">>",
473
- "**",
474
- "in",
475
- "+",
476
- "-",
477
- "*",
478
- "/",
479
- "%",
480
- "<",
481
- ">",
482
- "&",
483
- "|",
484
- "^"
485
- ];
486
- static KEYWORD_OPERATORS = new Set(["in", "instanceof"]);
487
- peekOperator() {
488
- for (const op of Parser.OPERATORS) {
489
- if (!this.source.startsWith(op, this.pos)) continue;
490
- if (Parser.KEYWORD_OPERATORS.has(op)) {
491
- const nextChar = this.source[this.pos + op.length];
492
- if (nextChar && this.isIdentifierPart(nextChar)) continue;
493
- }
494
- return op;
495
- }
496
- return null;
497
- }
498
- matchKeyword(keyword) {
499
- if (this.source.startsWith(keyword, this.pos)) {
500
- const nextChar = this.source[this.pos + keyword.length];
501
- if (!nextChar || !this.isIdentifierPart(nextChar)) {
502
- this.pos += keyword.length;
503
- return true;
504
- }
505
- }
506
- return false;
507
- }
508
- peek() {
509
- return this.source[this.pos] || "";
510
- }
511
- peekAt(offset) {
512
- return this.source[this.pos + offset] || "";
513
- }
514
- advance() {
515
- return this.source[this.pos++] || "";
516
- }
517
- expect(ch) {
518
- if (this.peek() !== ch) throw new Error(`Expected '${ch}' at position ${this.pos}, got '${this.peek()}'`);
519
- this.advance();
520
- }
521
- skipWhitespace() {
522
- while (/\s/.test(this.peek())) this.advance();
523
- }
524
- isDigit(ch) {
525
- const code = ch.charCodeAt(0);
526
- return code >= 48 && code <= 57;
527
- }
528
- isHexDigit(ch) {
529
- const code = ch.charCodeAt(0);
530
- return code >= 48 && code <= 57 || code >= 65 && code <= 70 || code >= 97 && code <= 102;
531
- }
532
- isIdentifierStart(ch) {
533
- const code = ch.charCodeAt(0);
534
- return code >= 65 && code <= 90 || code >= 97 && code <= 122 || code === 95 || code === 36;
535
- }
536
- isIdentifierPart(ch) {
537
- const code = ch.charCodeAt(0);
538
- return code >= 65 && code <= 90 || code >= 97 && code <= 122 || code >= 48 && code <= 57 || code === 95 || code === 36;
539
- }
540
- };
361
+ }
362
+ /**
363
+ * 创建标识符 AST 节点
364
+ */
365
+ function identifier(name) {
366
+ return {
367
+ type: "Identifier",
368
+ name
369
+ };
370
+ }
371
+ /**
372
+ * 创建数字字面量 AST 节点
373
+ */
374
+ function numberLiteral(value) {
375
+ return {
376
+ type: "NumberLiteral",
377
+ value,
378
+ raw: String(value)
379
+ };
380
+ }
381
+ /**
382
+ * 创建字符串字面量 AST 节点
383
+ */
384
+ function stringLiteral(value, quote = "\"") {
385
+ return {
386
+ type: "StringLiteral",
387
+ value,
388
+ quote
389
+ };
390
+ }
391
+ /**
392
+ * 创建成员表达式 AST 节点
393
+ */
394
+ function memberExpr(object, property) {
395
+ return {
396
+ type: "MemberExpr",
397
+ object,
398
+ property,
399
+ computed: false,
400
+ optional: false
401
+ };
402
+ }
541
403
  /**
542
- * 解析 JavaScript 表达式为 AST
404
+ * 创建调用表达式 AST 节点
543
405
  */
544
- function parse(source) {
545
- return new Parser(source).parse();
406
+ function callExpr(callee, arguments_) {
407
+ return {
408
+ type: "CallExpr",
409
+ callee,
410
+ arguments: arguments_,
411
+ optional: false
412
+ };
546
413
  }
547
414
  /**
548
- * AST 生成规范化的代码
415
+ * 创建数组表达式 AST 节点
549
416
  */
550
- function generate(node) {
551
- switch (node.type) {
552
- case "NumberLiteral": return node.raw;
553
- case "StringLiteral": return JSON.stringify(node.value);
554
- case "BooleanLiteral": return node.value ? "true" : "false";
555
- case "NullLiteral": return "null";
556
- case "Identifier": return node.name;
557
- case "BinaryExpr": {
558
- const left = wrapIfNeeded(node.left, node, "left");
559
- const right = wrapIfNeeded(node.right, node, "right");
560
- if (node.operator === "in" || node.operator === "instanceof") return `${left} ${node.operator} ${right}`;
561
- return `${left}${node.operator}${right}`;
417
+ function arrayExpr(elements) {
418
+ return {
419
+ type: "ArrayExpr",
420
+ elements
421
+ };
422
+ }
423
+ /**
424
+ * 检查对象是否为 TypedArray 实例
425
+ */
426
+ function getTypedArrayConstructor(value) {
427
+ for (const constructorName of typedArrayConstructors) {
428
+ const Constructor = globalThis[constructorName];
429
+ if (Constructor && value instanceof Constructor) return Constructor;
430
+ }
431
+ return null;
432
+ }
433
+ /**
434
+ * 序列化参数为 AST 节点
435
+ * - Proxy Variable/Expression:使用 ast 或占位符标识符
436
+ * - 数组:返回 ArrayExpr 节点
437
+ * - 对象:返回 ObjectExpr 节点
438
+ * - 原始值:返回对应的字面量节点
439
+ * - Date, RegExp, BigInt, URL, URLSearchParams, Map, Set, TypedArray, DataView: 构造函数调用
440
+ */
441
+ function serializeArgumentToAST(arg) {
442
+ if ((typeof arg === "object" || typeof arg === "function") && arg !== null) {
443
+ const meta = getProxyMetadata(arg);
444
+ if (meta) {
445
+ if (meta.ast) return meta.ast;
446
+ if (meta.rootVariable) return placeholder(meta.rootVariable);
562
447
  }
563
- case "UnaryExpr":
564
- if (node.prefix) {
565
- const arg = wrapIfNeeded(node.argument, node, "argument");
566
- if (node.operator === "typeof" || node.operator === "void") return `${node.operator} ${arg}`;
567
- return `${node.operator}${arg}`;
568
- }
569
- return generate(node.argument) + node.operator;
570
- case "ConditionalExpr": return `${wrapIfNeeded(node.test, node, "test")}?${wrapIfNeeded(node.consequent, node, "consequent")}:${wrapIfNeeded(node.alternate, node, "alternate")}`;
571
- case "MemberExpr": {
572
- const object = wrapIfNeeded(node.object, node, "object");
573
- const property = generate(node.property);
574
- return node.computed ? `${object}${node.optional ? "?." : ""}[${property}]` : `${object}${node.optional ? "?." : "."}${property}`;
448
+ }
449
+ if (Array.isArray(arg)) return arrayExpr(arg.map(serializeArgumentToAST));
450
+ if (typeof arg === "object" && arg !== null) {
451
+ if (arg instanceof Date) return callExpr(identifier("Date"), [numberLiteral(arg.getTime())]);
452
+ if (arg instanceof RegExp) {
453
+ const args = [stringLiteral(arg.source)];
454
+ if (arg.flags) args.push(stringLiteral(arg.flags));
455
+ return callExpr(identifier("RegExp"), args);
575
456
  }
576
- case "CallExpr": {
577
- const callee = wrapIfNeeded(node.callee, node, "callee");
578
- const args = node.arguments.map(generate).join(",");
579
- return `${node.callee.type === "Identifier" && BUILTIN_CONSTRUCTORS.has(node.callee.name) ? "new " : ""}${callee}${node.optional ? "?." : ""}(${args})`;
457
+ if (typeof URL !== "undefined" && arg instanceof URL) return callExpr(identifier("URL"), [stringLiteral(arg.href)]);
458
+ if (typeof URLSearchParams !== "undefined" && arg instanceof URLSearchParams) {
459
+ const entries = [];
460
+ arg.forEach((value, key) => {
461
+ entries.push(arrayExpr([stringLiteral(key), stringLiteral(value)]));
462
+ });
463
+ return callExpr(identifier("URLSearchParams"), [arrayExpr(entries)]);
580
464
  }
581
- case "ArrayExpr": return `[${node.elements.map(generate).join(",")}]`;
582
- case "ObjectExpr": return `{${node.properties.map((prop) => {
583
- if (prop.shorthand) return generate(prop.key);
584
- return `${prop.computed ? `[${generate(prop.key)}]` : generate(prop.key)}:${generate(prop.value)}`;
585
- }).join(",")}}`;
586
- case "ArrowFunctionExpr": {
587
- const params = node.params.map((p) => p.name).join(",");
588
- const body = node.body.type === "ObjectExpr" ? `(${generate(node.body)})` : generate(node.body);
589
- return `${node.params.length === 1 ? params : `(${params})`}=>${body}`;
465
+ if (arg instanceof Map) {
466
+ const entries = [];
467
+ arg.forEach((value, key) => {
468
+ entries.push(arrayExpr([serializeArgumentToAST(key), serializeArgumentToAST(value)]));
469
+ });
470
+ return callExpr(identifier("Map"), [arrayExpr(entries)]);
590
471
  }
591
- default: {
592
- const nodeType = node.type ?? "unknown";
593
- throw new Error(`Unknown node type: ${nodeType}`);
472
+ if (arg instanceof Set) {
473
+ const values = [];
474
+ arg.forEach((value) => values.push(serializeArgumentToAST(value)));
475
+ return callExpr(identifier("Set"), [arrayExpr(values)]);
476
+ }
477
+ const typedArrayConstructor = getTypedArrayConstructor(arg);
478
+ if (typedArrayConstructor) {
479
+ const values = [...arg].map(serializeArgumentToAST);
480
+ const constructorName = typedArrayConstructor.name;
481
+ return callExpr(identifier(constructorName), [arrayExpr(values)]);
482
+ }
483
+ if (arg instanceof ArrayBuffer) {
484
+ const uint8Array = new Uint8Array(arg);
485
+ const values = Array.from(uint8Array).map(numberLiteral);
486
+ return memberExpr(callExpr(identifier("Uint8Array"), [arrayExpr(values)]), identifier("buffer"));
594
487
  }
488
+ if (arg instanceof DataView) return callExpr(identifier("DataView"), [serializeArgumentToAST(arg.buffer)]);
489
+ return {
490
+ type: "ObjectExpr",
491
+ properties: Object.entries(arg).map(([k, v]) => {
492
+ return {
493
+ key: /^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(k) ? identifier(k) : stringLiteral(k),
494
+ value: serializeArgumentToAST(v),
495
+ computed: false,
496
+ shorthand: false
497
+ };
498
+ })
499
+ };
595
500
  }
501
+ if (arg === null) return { type: "NullLiteral" };
502
+ if (arg === void 0) return identifier("undefined");
503
+ if (typeof arg === "boolean") return {
504
+ type: "BooleanLiteral",
505
+ value: arg
506
+ };
507
+ if (typeof arg === "number") return numberLiteral(arg);
508
+ if (typeof arg === "string") return stringLiteral(arg);
509
+ if (typeof arg === "bigint") return callExpr(identifier("BigInt"), [stringLiteral(arg.toString())]);
510
+ throw new Error(`Unsupported argument type: ${typeof arg}`);
596
511
  }
597
512
  /**
598
- * 判断是否需要括号包裹,并生成代码
513
+ * 从参数中收集依赖的 Symbol
514
+ * 递归遍历数组和对象,收集所有 Proxy 的依赖
599
515
  */
600
- function wrapIfNeeded(child, parent, position) {
601
- const code = generate(child);
602
- if (needsParens(child, parent, position)) return `(${code})`;
603
- return code;
516
+ function collectDepsFromArgs(args, deps) {
517
+ for (const arg of args) if ((typeof arg === "object" || typeof arg === "function") && arg !== null) {
518
+ const meta = getProxyMetadata(arg);
519
+ if (meta?.dependencies) for (const dep of meta.dependencies) deps.add(dep);
520
+ else if (Array.isArray(arg)) collectDepsFromArgs(arg, deps);
521
+ else if (typeof arg === "object") collectDepsFromArgs(Object.values(arg), deps);
522
+ }
604
523
  }
605
524
  /**
606
- * 判断子节点是否需要括号
525
+ * 根据路径构建成员表达式 AST
607
526
  */
608
- function needsParens(child, parent, position) {
609
- switch (parent.type) {
610
- case "BinaryExpr":
611
- if (child.type === "ConditionalExpr" || child.type === "UnaryExpr") return true;
612
- if (child.type === "BinaryExpr") {
613
- const childPrec = PRECEDENCE[child.operator] ?? 0;
614
- const parentPrec = PRECEDENCE[parent.operator] ?? 0;
615
- if (childPrec < parentPrec) return true;
616
- if (childPrec === parentPrec && position === "right" && !RIGHT_ASSOCIATIVE.has(parent.operator)) return true;
617
- }
618
- return false;
619
- case "UnaryExpr": return position === "argument" && (child.type === "BinaryExpr" || child.type === "ConditionalExpr");
620
- case "MemberExpr":
621
- case "CallExpr":
622
- if (position !== "object" && position !== "callee") return false;
623
- if ([
624
- "BinaryExpr",
625
- "ConditionalExpr",
626
- "UnaryExpr",
627
- "ArrowFunctionExpr",
628
- "ObjectExpr"
629
- ].includes(child.type)) return true;
630
- if (child.type === "NumberLiteral" && parent.type === "MemberExpr" && !parent.computed) return !child.raw.includes(".") && !child.raw.includes("e") && !child.raw.includes("x");
631
- return false;
632
- case "ConditionalExpr": return position === "test" && child.type === "ConditionalExpr";
633
- default: return false;
634
- }
527
+ function buildMemberExprAst(rootId, path) {
528
+ let ast = placeholder(rootId);
529
+ for (const prop of path) ast = memberExpr(ast, identifier(prop));
530
+ return ast;
635
531
  }
636
532
  /**
637
- * 转换 AST 中的标识符
638
- * 回调函数可以返回:
639
- * - string: 替换标识符名称
640
- * - ASTNode: 内联该 AST 节点(用于子表达式内联)
533
+ * 创建 Proxy 的公共 handler
641
534
  */
642
- function transformIdentifiers(node, transform) {
643
- switch (node.type) {
644
- case "Identifier": {
645
- const result = transform(node.name);
646
- return typeof result === "string" ? {
647
- ...node,
648
- name: result
649
- } : result;
650
- }
651
- case "BinaryExpr": return {
652
- ...node,
653
- left: transformIdentifiers(node.left, transform),
654
- right: transformIdentifiers(node.right, transform)
655
- };
656
- case "UnaryExpr": return {
657
- ...node,
658
- argument: transformIdentifiers(node.argument, transform)
659
- };
660
- case "ConditionalExpr": return {
661
- ...node,
662
- test: transformIdentifiers(node.test, transform),
663
- consequent: transformIdentifiers(node.consequent, transform),
664
- alternate: transformIdentifiers(node.alternate, transform)
665
- };
666
- case "MemberExpr": return {
667
- ...node,
668
- object: transformIdentifiers(node.object, transform),
669
- property: node.computed ? transformIdentifiers(node.property, transform) : node.property
670
- };
671
- case "CallExpr": return {
672
- ...node,
673
- callee: transformIdentifiers(node.callee, transform),
674
- arguments: node.arguments.map((arg) => transformIdentifiers(arg, transform))
675
- };
676
- case "ArrayExpr": return {
677
- ...node,
678
- elements: node.elements.map((el) => transformIdentifiers(el, transform))
679
- };
680
- case "ObjectExpr": return {
681
- ...node,
682
- properties: node.properties.map((prop) => ({
683
- ...prop,
684
- key: prop.computed ? transformIdentifiers(prop.key, transform) : prop.key,
685
- value: transformIdentifiers(prop.value, transform)
686
- }))
687
- };
688
- case "ArrowFunctionExpr": {
689
- const paramNames = new Set(node.params.map((p) => p.name));
690
- return {
691
- ...node,
692
- body: transformIdentifiers(node.body, (name) => paramNames.has(name) ? name : transform(name))
693
- };
535
+ function createProxyHandler(ast, deps) {
536
+ return {
537
+ get(_target, prop) {
538
+ if (typeof prop === "symbol") return void 0;
539
+ return createProxyExpressionWithAST(memberExpr(ast, identifier(String(prop))), deps);
540
+ },
541
+ apply(_target, _thisArg, args) {
542
+ const callAst = callExpr(ast, args.map(serializeArgumentToAST));
543
+ const newDeps = new Set(deps);
544
+ collectDepsFromArgs(args, newDeps);
545
+ return createProxyExpressionWithAST(callAst, newDeps);
694
546
  }
695
- default: return node;
696
- }
547
+ };
548
+ }
549
+ /**
550
+ * 创建根 Variable Proxy
551
+ * 拦截属性访问,返回新的 expression proxy
552
+ * 不可直接调用(apply 应该只在链式调用后可用)
553
+ *
554
+ * @param id - 变量的唯一标识 Symbol
555
+ * @returns Proxy 包装的 Variable
556
+ */
557
+ function createProxyVariable(id) {
558
+ const deps = new Set([id]);
559
+ const proxy = new Proxy(function() {}, {
560
+ get(_target, prop) {
561
+ if (typeof prop === "symbol") return void 0;
562
+ return createProxyExpressionWithAST(buildMemberExprAst(id, [String(prop)]), deps);
563
+ },
564
+ apply() {
565
+ throw new Error("Variable cannot be called directly");
566
+ }
567
+ });
568
+ setProxyMetadata(proxy, {
569
+ type: "variable",
570
+ path: [],
571
+ rootVariable: id,
572
+ dependencies: deps
573
+ });
574
+ return proxy;
697
575
  }
698
-
699
- //#endregion
700
- //#region src/proxy-metadata.ts
701
- /**
702
- * 全局 WeakMap 存储
703
- */
704
- const proxyMetadata = /* @__PURE__ */ new WeakMap();
705
576
  /**
706
- * 设置 Proxy 元数据
577
+ * 创建带完整 AST 的 Proxy(方法调用后)
578
+ * 可以继续链式访问和调用
579
+ *
580
+ * @param ast - 完整的表达式 AST
581
+ * @param deps - 依赖集合
582
+ * @returns Proxy 包装的 Expression
707
583
  */
708
- function setProxyMetadata(proxy, metadata) {
709
- proxyMetadata.set(proxy, metadata);
584
+ function createProxyExpressionWithAST(ast, deps) {
585
+ const proxy = new Proxy(function() {}, createProxyHandler(ast, deps));
586
+ setProxyMetadata(proxy, {
587
+ type: "expression",
588
+ path: [],
589
+ ast,
590
+ dependencies: deps
591
+ });
592
+ return proxy;
710
593
  }
594
+
595
+ //#endregion
596
+ //#region src/variable.ts
711
597
  /**
712
- * 获取 Proxy 元数据
598
+ * 跟踪每个 variable 的唯一 Symbol ID
713
599
  */
714
- function getProxyMetadata(proxy) {
715
- return proxyMetadata.get(proxy);
716
- }
600
+ const variableIds = /* @__PURE__ */ new WeakMap();
717
601
  /**
718
- * 检查对象是否是 Proxy variable
602
+ * 计数器用于生成唯一变量 ID
719
603
  */
720
- function isProxyVariable(obj) {
721
- if (typeof obj !== "object" && typeof obj !== "function" || obj === null) return false;
722
- return proxyMetadata.get(obj)?.type === "variable";
723
- }
604
+ let variableCounter = 0;
724
605
  /**
725
- * 检查对象是否是 Proxy expression
606
+ * 创建一个类型化变量
607
+ * 返回 Proxy 对象,支持链式属性访问和方法调用
608
+ *
609
+ * @example
610
+ * ```ts
611
+ * const x = variable<number>();
612
+ * const config = variable<{ timeout: number }>();
613
+ * const timeout = config.timeout; // Proxy expression
614
+ * ```
726
615
  */
727
- function isProxyExpression(obj) {
728
- if (typeof obj !== "object" && typeof obj !== "function" || obj === null) return false;
729
- return proxyMetadata.get(obj)?.type === "expression";
616
+ function variable() {
617
+ const id = Symbol(`var_${variableCounter++}`);
618
+ const proxy = createProxyVariable(id);
619
+ variableIds.set(proxy, id);
620
+ return proxy;
730
621
  }
731
622
  /**
732
- * 检查对象是否是任意 Proxy (variable expression)
623
+ * 获取 variable 的唯一 Symbol ID
733
624
  */
734
- function isProxy(obj) {
735
- if (typeof obj !== "object" && typeof obj !== "function" || obj === null) return false;
736
- return proxyMetadata.has(obj);
625
+ function getVariableId(variable) {
626
+ if (typeof variable !== "object" && typeof variable !== "function" || variable === null) return void 0;
627
+ return variableIds.get(variable);
737
628
  }
738
629
 
739
630
  //#endregion
740
- //#region src/proxy-variable.ts
741
- const typedArrayConstructors = [
631
+ //#region src/compile.ts
632
+ const ALLOWED_GLOBALS = new Set([
633
+ "Math",
634
+ "JSON",
635
+ "Date",
636
+ "RegExp",
637
+ "Number",
638
+ "String",
639
+ "Boolean",
640
+ "Array",
641
+ "Object",
642
+ "undefined",
643
+ "NaN",
644
+ "Infinity",
645
+ "isNaN",
646
+ "isFinite",
647
+ "parseInt",
648
+ "parseFloat",
649
+ "BigInt",
650
+ "URL",
651
+ "URLSearchParams",
652
+ "Map",
653
+ "Set",
742
654
  "Int8Array",
743
655
  "Uint8Array",
744
656
  "Uint8ClampedArray",
@@ -749,552 +661,738 @@ const typedArrayConstructors = [
749
661
  "Float32Array",
750
662
  "Float64Array",
751
663
  "BigInt64Array",
752
- "BigUint64Array"
753
- ];
754
- /**
755
- * 使用 Symbol.description 生成占位符
756
- * 用于在表达式源码中标识变量
757
- */
758
- function getVariablePlaceholder$1(id) {
759
- return `$$VAR_${id.description}$$`;
760
- }
761
- /**
762
- * 创建标识符 AST 节点
763
- */
764
- function identifier(name) {
765
- return {
766
- type: "Identifier",
767
- name
768
- };
769
- }
770
- /**
771
- * 创建数字字面量 AST 节点
772
- */
773
- function numberLiteral(value) {
774
- return {
775
- type: "NumberLiteral",
776
- value,
777
- raw: String(value)
778
- };
779
- }
780
- /**
781
- * 创建字符串字面量 AST 节点
782
- */
783
- function stringLiteral(value, quote = "\"") {
784
- return {
785
- type: "StringLiteral",
786
- value,
787
- quote
788
- };
789
- }
664
+ "BigUint64Array",
665
+ "ArrayBuffer",
666
+ "DataView"
667
+ ]);
790
668
  /**
791
- * 创建成员表达式 AST 节点
669
+ * Proxy Expression 编译为可序列化的 JSON 结构
670
+ *
671
+ * @template TResult - 表达式结果类型
672
+ * @param expression - Proxy Expression,或包含 Proxy 的对象/数组/原始值
673
+ * @param variables - 所有使用的变量定义
674
+ * @param options - 编译选项
675
+ * @returns 编译后的数据结构 [变量名列表, 表达式1, 表达式2, ...]
676
+ *
677
+ * @throws 如果传入无效的表达式或未定义的变量引用
678
+ *
679
+ * @example
680
+ * ```ts
681
+ * const x = variable<number>()
682
+ * const y = variable<number>()
683
+ * const sum = expr({ x, y })("x + y")
684
+ * const result = expr({ sum, x })("sum * x")
685
+ * const compiled = compile(result, { x, y })
686
+ * // => [["x", "y"], "($0+$1)*$0"]
687
+ * ```
792
688
  */
793
- function memberExpr(object, property) {
794
- return {
795
- type: "MemberExpr",
796
- object,
797
- property,
798
- computed: false,
799
- optional: false
800
- };
689
+ function compile(expression, variables, options = {}) {
690
+ const { shortCircuit = true } = options;
691
+ const ast = serializeArgumentToAST(expression);
692
+ const variableOrder = [];
693
+ const variableToIndex = /* @__PURE__ */ new Map();
694
+ const symbolToName = /* @__PURE__ */ new Map();
695
+ for (const [name, value] of Object.entries(variables)) {
696
+ if (!variableToIndex.has(name)) {
697
+ variableToIndex.set(name, variableOrder.length);
698
+ variableOrder.push(name);
699
+ }
700
+ const id = getVariableId(value);
701
+ if (id) symbolToName.set(id, name);
702
+ }
703
+ const placeholderTransformed = transformPlaceholders(ast, (id) => {
704
+ const name = symbolToName.get(id);
705
+ if (!name) return null;
706
+ const index = variableToIndex.get(name);
707
+ if (index === void 0) return null;
708
+ return `$${index}`;
709
+ });
710
+ const undefinedVars = [];
711
+ const transformed = transformIdentifiers(placeholderTransformed, (name) => {
712
+ if (name.startsWith("$") && /^\$\d+$/.test(name)) return name;
713
+ const index = variableToIndex.get(name);
714
+ if (index !== void 0) return `$${index}`;
715
+ if (!ALLOWED_GLOBALS.has(name)) undefinedVars.push(name);
716
+ return name;
717
+ });
718
+ if (undefinedVars.length > 0) {
719
+ const uniqueVars = [...new Set(undefinedVars)];
720
+ throw new Error(`Undefined variable(s): ${uniqueVars.join(", ")}`);
721
+ }
722
+ const expressions = [];
723
+ if (shortCircuit) {
724
+ let nextIndex = variableOrder.length;
725
+ function compileAst(node) {
726
+ if (node.type === "BinaryExpr" && (node.operator === "||" || node.operator === "&&" || node.operator === "??")) return compileShortCircuit(node);
727
+ if (node.type === "ConditionalExpr") return compileConditional(node);
728
+ const exprStr = generate(node);
729
+ expressions.push(exprStr);
730
+ return nextIndex++;
731
+ }
732
+ function compileShortCircuit(node) {
733
+ const leftIdx = compileAst(node.left);
734
+ const branchConditions = {
735
+ "||": `$${leftIdx}`,
736
+ "&&": `!$${leftIdx}`,
737
+ "??": `$${leftIdx}!=null`
738
+ };
739
+ const branchIdx = expressions.length;
740
+ expressions.push([
741
+ "br",
742
+ branchConditions[node.operator],
743
+ 0
744
+ ]);
745
+ nextIndex++;
746
+ compileAst(node.right);
747
+ const skipCount = expressions.length - branchIdx - 1;
748
+ expressions[branchIdx][2] = skipCount;
749
+ const phiIdx = nextIndex++;
750
+ expressions.push(["phi"]);
751
+ return phiIdx;
752
+ }
753
+ function compileConditional(node) {
754
+ const testIdx = compileAst(node.test);
755
+ const branchIdx = expressions.length;
756
+ expressions.push([
757
+ "br",
758
+ `$${testIdx}`,
759
+ 0
760
+ ]);
761
+ nextIndex++;
762
+ compileAst(node.alternate);
763
+ const jmpIdx = expressions.length;
764
+ expressions.push(["jmp", 0]);
765
+ nextIndex++;
766
+ compileAst(node.consequent);
767
+ const thenEndIdx = expressions.length;
768
+ expressions[branchIdx][2] = jmpIdx - branchIdx;
769
+ expressions[jmpIdx][1] = thenEndIdx - jmpIdx - 1;
770
+ const phiIdx = nextIndex++;
771
+ expressions.push(["phi"]);
772
+ return phiIdx;
773
+ }
774
+ compileAst(transformed);
775
+ } else expressions.push(generate(transformed));
776
+ return [variableOrder, ...expressions];
801
777
  }
778
+
779
+ //#endregion
780
+ //#region src/evaluate.ts
802
781
  /**
803
- * 创建调用表达式 AST 节点
804
- */
805
- function callExpr(callee, arguments_) {
806
- return {
807
- type: "CallExpr",
808
- callee,
809
- arguments: arguments_,
810
- optional: false
811
- };
812
- }
782
+ * 缓存已构造的求值函数,以提升重复执行性能
783
+ */
784
+ const evaluatorCache = /* @__PURE__ */ new Map();
813
785
  /**
814
- * 创建数组表达式 AST 节点
786
+ * 检测编译数据是否包含控制流节点(V2 格式)
815
787
  */
816
- function arrayExpr(elements) {
817
- return {
818
- type: "ArrayExpr",
819
- elements
820
- };
788
+ function isV2Format(expressions) {
789
+ return expressions.some((expr) => Array.isArray(expr));
821
790
  }
822
791
  /**
823
- * 检查对象是否为 TypedArray 实例
792
+ * 执行编译后的表达式
793
+ *
794
+ * @template TResult - 表达式结果类型
795
+ * @param data - 编译后的数据结构 [变量名列表, 表达式1, 表达式2, ...]
796
+ * @param values - 变量值映射,按变量名提供值
797
+ * @returns 最后一个表达式的求值结果
798
+ *
799
+ * @throws 如果运行时类型验证失败或表达式执行出错
800
+ *
801
+ * @example
802
+ * ```ts
803
+ * const compiled = [["x", "y"], "$0+$1", "$1*2"]
804
+ * const result = evaluate<number>(compiled, { x: 2, y: 3 })
805
+ * // => 6 (3 * 2)
806
+ * ```
824
807
  */
825
- function getTypedArrayConstructor(value) {
826
- for (const constructorName of typedArrayConstructors) {
827
- const Constructor = globalThis[constructorName];
828
- if (Constructor && value instanceof Constructor) return Constructor;
808
+ function evaluate(data, values) {
809
+ if (data.length < 1) throw new Error("Invalid compiled data: must have at least variable names");
810
+ const [variableNames, ...expressions] = data;
811
+ if (!Array.isArray(variableNames)) throw new Error("Invalid compiled data: first element must be variable names array");
812
+ for (const varName of variableNames) {
813
+ if (typeof varName !== "string") throw new Error("Invalid compiled data: variable names must be strings");
814
+ if (!(varName in values)) throw new Error(`Missing required variable: ${varName}`);
815
+ }
816
+ const valueArray = [];
817
+ for (const varName of variableNames) valueArray.push(values[varName]);
818
+ const cacheKey = JSON.stringify(data);
819
+ let evaluator = evaluatorCache.get(cacheKey);
820
+ if (!evaluator) {
821
+ const functionBody = isV2Format(expressions) ? buildEvaluatorFunctionBodyV2(expressions, variableNames.length) : buildEvaluatorFunctionBody(expressions, variableNames.length);
822
+ evaluator = new Function("$values", functionBody);
823
+ evaluatorCache.set(cacheKey, evaluator);
824
+ }
825
+ try {
826
+ return evaluator(valueArray);
827
+ } catch (error) {
828
+ throw new Error(`Failed to evaluate expression: ${error instanceof Error ? error.message : String(error)}`);
829
829
  }
830
- return null;
831
830
  }
832
831
  /**
833
- * 序列化参数为 AST 节点
834
- * - Proxy Variable/Expression:使用 ast 或占位符标识符
835
- * - 数组:返回 ArrayExpr 节点
836
- * - 对象:返回 ObjectExpr 节点
837
- * - 原始值:返回对应的字面量节点
838
- * - Date, RegExp, BigInt, URL, URLSearchParams, Map, Set, TypedArray, DataView: 构造函数调用
832
+ * 构造求值函数体
833
+ *
834
+ * @param expressions - 表达式列表
835
+ * @param variableCount - 变量数量
836
+ * @returns 函数体字符串
837
+ *
838
+ * @example
839
+ * ```ts
840
+ * buildEvaluatorFunctionBody(["$0+$1", "$2*2"], 2)
841
+ * // 返回执行 $0+$1 并存储到 $values[2],然后执行 $2*2 的函数体
842
+ * ```
839
843
  */
840
- function serializeArgumentToAST(arg) {
841
- if ((typeof arg === "object" || typeof arg === "function") && arg !== null) {
842
- const meta = getProxyMetadata(arg);
843
- if (meta) {
844
- if (meta.ast) return meta.ast;
845
- if (meta.rootVariable) return identifier(getVariablePlaceholder$1(meta.rootVariable));
844
+ function buildEvaluatorFunctionBody(expressions, variableCount) {
845
+ if (expressions.length === 0) throw new Error("No expressions to evaluate");
846
+ return [
847
+ ...Array.from({ length: variableCount }, (_, i) => `const $${i} = $values[${i}];`),
848
+ ...expressions.map((expr, i) => {
849
+ const idx = variableCount + i;
850
+ return `const $${idx} = ${expr}; $values[${idx}] = $${idx};`;
851
+ }),
852
+ `return $values[$values.length - 1];`
853
+ ].join("\n");
854
+ }
855
+ /**
856
+ * 构造带控制流支持的求值函数体(V2 格式)
857
+ *
858
+ * @param expressions - 表达式列表(可包含控制流节点)
859
+ * @param variableCount - 变量数量
860
+ * @returns 函数体字符串
861
+ */
862
+ function buildEvaluatorFunctionBodyV2(expressions, variableCount) {
863
+ if (expressions.length === 0) throw new Error("No expressions to evaluate");
864
+ const lines = [
865
+ ...Array.from({ length: variableCount }, (_, i) => `const $${i} = $values[${i}];`),
866
+ "let $pc = 0;",
867
+ "let $lastValue;",
868
+ ...expressions.map((_, i) => `let $${variableCount + i};`),
869
+ `while ($pc < ${expressions.length}) {`,
870
+ " switch ($pc) {"
871
+ ];
872
+ expressions.forEach((expr, i) => {
873
+ const idx = variableCount + i;
874
+ lines.push(` case ${i}: {`);
875
+ if (typeof expr === "string") {
876
+ lines.push(` $${idx} = $lastValue = ${expr};`);
877
+ lines.push(` $values[${idx}] = $${idx};`);
878
+ lines.push(" $pc++; break;");
879
+ } else {
880
+ const [type] = expr;
881
+ switch (type) {
882
+ case "br":
883
+ lines.push(` if (${expr[1]}) { $pc += ${expr[2] + 1}; } else { $pc++; } break;`);
884
+ break;
885
+ case "jmp":
886
+ lines.push(` $pc += ${expr[1] + 1}; break;`);
887
+ break;
888
+ case "phi":
889
+ lines.push(` $${idx} = $values[${idx}] = $lastValue; $pc++; break;`);
890
+ break;
891
+ }
892
+ }
893
+ lines.push(" }");
894
+ });
895
+ lines.push(" }", "}", "return $values[$values.length - 1];");
896
+ return lines.join("\n");
897
+ }
898
+
899
+ //#endregion
900
+ //#region src/parser.ts
901
+ var Parser = class Parser {
902
+ pos = 0;
903
+ source;
904
+ constructor(source) {
905
+ this.source = source;
906
+ }
907
+ parse() {
908
+ this.skipWhitespace();
909
+ const node = this.parseExpression();
910
+ this.skipWhitespace();
911
+ if (this.pos < this.source.length) throw new Error(`Unexpected token at position ${this.pos}: ${this.source.slice(this.pos, this.pos + 10)}`);
912
+ return node;
913
+ }
914
+ parseExpression() {
915
+ return this.parseConditional();
916
+ }
917
+ parseConditional() {
918
+ let node = this.parseBinary(0);
919
+ this.skipWhitespace();
920
+ if (this.peek() === "?") {
921
+ this.advance();
922
+ this.skipWhitespace();
923
+ const consequent = this.parseExpression();
924
+ this.skipWhitespace();
925
+ this.expect(":");
926
+ this.skipWhitespace();
927
+ const alternate = this.parseExpression();
928
+ node = {
929
+ type: "ConditionalExpr",
930
+ test: node,
931
+ consequent,
932
+ alternate
933
+ };
934
+ }
935
+ return node;
936
+ }
937
+ parseBinary(minPrec) {
938
+ let left = this.parseUnary();
939
+ while (true) {
940
+ this.skipWhitespace();
941
+ const op = this.peekOperator();
942
+ if (!op || PRECEDENCE[op] === void 0 || PRECEDENCE[op] < minPrec) break;
943
+ this.pos += op.length;
944
+ this.skipWhitespace();
945
+ const nextMinPrec = RIGHT_ASSOCIATIVE.has(op) ? PRECEDENCE[op] : PRECEDENCE[op] + 1;
946
+ const right = this.parseBinary(nextMinPrec);
947
+ left = {
948
+ type: "BinaryExpr",
949
+ operator: op,
950
+ left,
951
+ right
952
+ };
953
+ }
954
+ return left;
955
+ }
956
+ parseUnary() {
957
+ this.skipWhitespace();
958
+ const ch = this.peek();
959
+ if (ch === "!" || ch === "~" || ch === "+" || ch === "-") {
960
+ this.advance();
961
+ this.skipWhitespace();
962
+ return {
963
+ type: "UnaryExpr",
964
+ operator: ch,
965
+ argument: this.parseUnary(),
966
+ prefix: true
967
+ };
968
+ }
969
+ for (const keyword of ["typeof", "void"]) if (this.matchKeyword(keyword)) {
970
+ this.skipWhitespace();
971
+ return {
972
+ type: "UnaryExpr",
973
+ operator: keyword,
974
+ argument: this.parseUnary(),
975
+ prefix: true
976
+ };
977
+ }
978
+ return this.parsePostfix();
979
+ }
980
+ parsePostfix() {
981
+ let node = this.parsePrimary();
982
+ while (true) {
983
+ this.skipWhitespace();
984
+ const ch = this.peek();
985
+ if (ch === ".") {
986
+ this.advance();
987
+ this.skipWhitespace();
988
+ const property = this.parseIdentifier();
989
+ node = {
990
+ type: "MemberExpr",
991
+ object: node,
992
+ property,
993
+ computed: false,
994
+ optional: false
995
+ };
996
+ } else if (ch === "[") {
997
+ this.advance();
998
+ this.skipWhitespace();
999
+ const property = this.parseExpression();
1000
+ this.skipWhitespace();
1001
+ this.expect("]");
1002
+ node = {
1003
+ type: "MemberExpr",
1004
+ object: node,
1005
+ property,
1006
+ computed: true,
1007
+ optional: false
1008
+ };
1009
+ } else if (ch === "(") {
1010
+ this.advance();
1011
+ const args = this.parseArguments();
1012
+ this.expect(")");
1013
+ node = {
1014
+ type: "CallExpr",
1015
+ callee: node,
1016
+ arguments: args,
1017
+ optional: false
1018
+ };
1019
+ } else if (ch === "?" && this.peekAt(1) === ".") {
1020
+ this.advance();
1021
+ this.advance();
1022
+ this.skipWhitespace();
1023
+ if (this.peek() === "[") {
1024
+ this.advance();
1025
+ this.skipWhitespace();
1026
+ const property = this.parseExpression();
1027
+ this.skipWhitespace();
1028
+ this.expect("]");
1029
+ node = {
1030
+ type: "MemberExpr",
1031
+ object: node,
1032
+ property,
1033
+ computed: true,
1034
+ optional: true
1035
+ };
1036
+ } else if (this.peek() === "(") {
1037
+ this.advance();
1038
+ const args = this.parseArguments();
1039
+ this.expect(")");
1040
+ node = {
1041
+ type: "CallExpr",
1042
+ callee: node,
1043
+ arguments: args,
1044
+ optional: true
1045
+ };
1046
+ } else {
1047
+ const property = this.parseIdentifier();
1048
+ node = {
1049
+ type: "MemberExpr",
1050
+ object: node,
1051
+ property,
1052
+ computed: false,
1053
+ optional: true
1054
+ };
1055
+ }
1056
+ } else break;
846
1057
  }
1058
+ return node;
847
1059
  }
848
- if (Array.isArray(arg)) return arrayExpr(arg.map(serializeArgumentToAST));
849
- if (typeof arg === "object" && arg !== null) {
850
- if (arg instanceof Date) return callExpr(identifier("Date"), [numberLiteral(arg.getTime())]);
851
- if (arg instanceof RegExp) {
852
- const args = [stringLiteral(arg.source)];
853
- if (arg.flags) args.push(stringLiteral(arg.flags));
854
- return callExpr(identifier("RegExp"), args);
855
- }
856
- if (typeof URL !== "undefined" && arg instanceof URL) return callExpr(identifier("URL"), [stringLiteral(arg.href)]);
857
- if (typeof URLSearchParams !== "undefined" && arg instanceof URLSearchParams) {
858
- const entries = [];
859
- arg.forEach((value, key) => {
860
- entries.push(arrayExpr([stringLiteral(key), stringLiteral(value)]));
861
- });
862
- return callExpr(identifier("URLSearchParams"), [arrayExpr(entries)]);
1060
+ parsePrimary() {
1061
+ this.skipWhitespace();
1062
+ const ch = this.peek();
1063
+ if (this.isDigit(ch) || ch === "." && this.isDigit(this.peekAt(1))) return this.parseNumber();
1064
+ if (ch === "\"" || ch === "'" || ch === "`") return this.parseString();
1065
+ if (ch === "[") return this.parseArray();
1066
+ if (ch === "{") return this.parseObject();
1067
+ if (ch === "(") {
1068
+ const arrowFunc = this.tryParseArrowFunction();
1069
+ if (arrowFunc) return arrowFunc;
1070
+ this.advance();
1071
+ this.skipWhitespace();
1072
+ const expr = this.parseExpression();
1073
+ this.skipWhitespace();
1074
+ this.expect(")");
1075
+ return expr;
863
1076
  }
864
- if (arg instanceof Map) {
865
- const entries = [];
866
- arg.forEach((value, key) => {
867
- entries.push(arrayExpr([serializeArgumentToAST(key), serializeArgumentToAST(value)]));
868
- });
869
- return callExpr(identifier("Map"), [arrayExpr(entries)]);
1077
+ if (this.matchKeyword("true")) return {
1078
+ type: "BooleanLiteral",
1079
+ value: true
1080
+ };
1081
+ if (this.matchKeyword("false")) return {
1082
+ type: "BooleanLiteral",
1083
+ value: false
1084
+ };
1085
+ if (this.matchKeyword("null")) return { type: "NullLiteral" };
1086
+ if (this.matchKeyword("undefined")) return {
1087
+ type: "Identifier",
1088
+ name: "undefined"
1089
+ };
1090
+ if (this.isIdentifierStart(ch)) {
1091
+ const arrowFunc = this.tryParseSingleParamArrowFunction();
1092
+ if (arrowFunc) return arrowFunc;
1093
+ return this.parseIdentifier();
870
1094
  }
871
- if (arg instanceof Set) {
872
- const values = [];
873
- arg.forEach((value) => values.push(serializeArgumentToAST(value)));
874
- return callExpr(identifier("Set"), [arrayExpr(values)]);
1095
+ throw new Error(`Unexpected character at position ${this.pos}: ${ch}`);
1096
+ }
1097
+ parseNumber() {
1098
+ const start = this.pos;
1099
+ if (this.peek() === "0") {
1100
+ const next = this.peekAt(1)?.toLowerCase();
1101
+ if (next === "x" || next === "o" || next === "b") {
1102
+ this.advance();
1103
+ this.advance();
1104
+ while (this.isHexDigit(this.peek())) this.advance();
1105
+ const raw = this.source.slice(start, this.pos);
1106
+ return {
1107
+ type: "NumberLiteral",
1108
+ value: Number(raw),
1109
+ raw
1110
+ };
1111
+ }
875
1112
  }
876
- const typedArrayConstructor = getTypedArrayConstructor(arg);
877
- if (typedArrayConstructor) {
878
- const values = [...arg].map(serializeArgumentToAST);
879
- const constructorName = typedArrayConstructor.name;
880
- return callExpr(identifier(constructorName), [arrayExpr(values)]);
1113
+ while (this.isDigit(this.peek())) this.advance();
1114
+ if (this.peek() === "." && this.isDigit(this.peekAt(1))) {
1115
+ this.advance();
1116
+ while (this.isDigit(this.peek())) this.advance();
881
1117
  }
882
- if (arg instanceof ArrayBuffer) {
883
- const uint8Array = new Uint8Array(arg);
884
- const values = Array.from(uint8Array).map(numberLiteral);
885
- return memberExpr(callExpr(identifier("Uint8Array"), [arrayExpr(values)]), identifier("buffer"));
1118
+ if (this.peek()?.toLowerCase() === "e") {
1119
+ this.advance();
1120
+ if (this.peek() === "+" || this.peek() === "-") this.advance();
1121
+ while (this.isDigit(this.peek())) this.advance();
886
1122
  }
887
- if (arg instanceof DataView) return callExpr(identifier("DataView"), [serializeArgumentToAST(arg.buffer)]);
1123
+ const raw = this.source.slice(start, this.pos);
888
1124
  return {
889
- type: "ObjectExpr",
890
- properties: Object.entries(arg).map(([k, v]) => {
891
- return {
892
- key: /^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(k) ? identifier(k) : stringLiteral(k),
893
- value: serializeArgumentToAST(v),
894
- computed: false,
895
- shorthand: false
896
- };
897
- })
1125
+ type: "NumberLiteral",
1126
+ value: Number(raw),
1127
+ raw
898
1128
  };
899
1129
  }
900
- if (arg === null) return { type: "NullLiteral" };
901
- if (arg === void 0) return identifier("undefined");
902
- if (typeof arg === "boolean") return {
903
- type: "BooleanLiteral",
904
- value: arg
1130
+ static ESCAPE_CHARS = {
1131
+ n: "\n",
1132
+ r: "\r",
1133
+ t: " ",
1134
+ "\\": "\\",
1135
+ "'": "'",
1136
+ "\"": "\"",
1137
+ "`": "`"
905
1138
  };
906
- if (typeof arg === "number") return numberLiteral(arg);
907
- if (typeof arg === "string") return stringLiteral(arg);
908
- if (typeof arg === "bigint") return callExpr(identifier("BigInt"), [stringLiteral(arg.toString())]);
909
- throw new Error(`Unsupported argument type: ${typeof arg}`);
910
- }
911
- /**
912
- * 从参数中收集依赖的 Symbol
913
- * 递归遍历数组和对象,收集所有 Proxy 的依赖
914
- */
915
- function collectDepsFromArgs(args, deps) {
916
- for (const arg of args) if ((typeof arg === "object" || typeof arg === "function") && arg !== null) {
917
- const meta = getProxyMetadata(arg);
918
- if (meta?.dependencies) for (const dep of meta.dependencies) deps.add(dep);
919
- else if (Array.isArray(arg)) collectDepsFromArgs(arg, deps);
920
- else if (typeof arg === "object") collectDepsFromArgs(Object.values(arg), deps);
1139
+ parseString() {
1140
+ const quote = this.peek();
1141
+ this.advance();
1142
+ let value = "";
1143
+ while (this.pos < this.source.length && this.peek() !== quote) if (this.peek() === "\\") {
1144
+ this.advance();
1145
+ const escaped = this.peek();
1146
+ value += Parser.ESCAPE_CHARS[escaped] ?? escaped;
1147
+ this.advance();
1148
+ } else {
1149
+ value += this.peek();
1150
+ this.advance();
1151
+ }
1152
+ this.expect(quote);
1153
+ return {
1154
+ type: "StringLiteral",
1155
+ value,
1156
+ quote
1157
+ };
921
1158
  }
922
- }
923
- /**
924
- * 根据路径构建成员表达式 AST
925
- */
926
- function buildMemberExprAst(rootId, path) {
927
- let ast = identifier(getVariablePlaceholder$1(rootId));
928
- for (const prop of path) ast = memberExpr(ast, identifier(prop));
929
- return ast;
930
- }
931
- /**
932
- * 创建 Proxy 的公共 handler
933
- */
934
- function createProxyHandler(ast, deps) {
935
- return {
936
- get(_target, prop) {
937
- if (typeof prop === "symbol") return void 0;
938
- return createProxyExpressionWithAST(memberExpr(ast, identifier(String(prop))), deps);
939
- },
940
- apply(_target, _thisArg, args) {
941
- const callAst = callExpr(ast, args.map(serializeArgumentToAST));
942
- const newDeps = new Set(deps);
943
- collectDepsFromArgs(args, newDeps);
944
- return createProxyExpressionWithAST(callAst, newDeps);
1159
+ parseArray() {
1160
+ this.expect("[");
1161
+ const elements = [];
1162
+ this.skipWhitespace();
1163
+ while (this.peek() !== "]") {
1164
+ elements.push(this.parseExpression());
1165
+ this.skipWhitespace();
1166
+ if (this.peek() === ",") {
1167
+ this.advance();
1168
+ this.skipWhitespace();
1169
+ } else break;
945
1170
  }
946
- };
947
- }
948
- /**
949
- * 创建根 Variable Proxy
950
- * 拦截属性访问,返回新的 expression proxy
951
- * 不可直接调用(apply 应该只在链式调用后可用)
952
- *
953
- * @param id - 变量的唯一标识 Symbol
954
- * @returns Proxy 包装的 Variable
955
- */
956
- function createProxyVariable(id) {
957
- const deps = new Set([id]);
958
- const proxy = new Proxy(function() {}, {
959
- get(_target, prop) {
960
- if (typeof prop === "symbol") return void 0;
961
- return createProxyExpressionWithAST(buildMemberExprAst(id, [String(prop)]), deps);
962
- },
963
- apply() {
964
- throw new Error("Variable cannot be called directly");
1171
+ this.expect("]");
1172
+ return {
1173
+ type: "ArrayExpr",
1174
+ elements
1175
+ };
1176
+ }
1177
+ parseObject() {
1178
+ this.expect("{");
1179
+ const properties = [];
1180
+ this.skipWhitespace();
1181
+ while (this.peek() !== "}") {
1182
+ const prop = this.parseObjectProperty();
1183
+ properties.push(prop);
1184
+ this.skipWhitespace();
1185
+ if (this.peek() === ",") {
1186
+ this.advance();
1187
+ this.skipWhitespace();
1188
+ } else break;
965
1189
  }
966
- });
967
- setProxyMetadata(proxy, {
968
- type: "variable",
969
- path: [],
970
- rootVariable: id,
971
- dependencies: deps
972
- });
973
- return proxy;
974
- }
975
- /**
976
- * 创建带完整 AST Proxy(方法调用后)
977
- * 可以继续链式访问和调用
978
- *
979
- * @param ast - 完整的表达式 AST
980
- * @param deps - 依赖集合
981
- * @returns Proxy 包装的 Expression
982
- */
983
- function createProxyExpressionWithAST(ast, deps) {
984
- const proxy = new Proxy(function() {}, createProxyHandler(ast, deps));
985
- setProxyMetadata(proxy, {
986
- type: "expression",
987
- path: [],
988
- ast,
989
- dependencies: deps
990
- });
991
- return proxy;
992
- }
993
-
994
- //#endregion
995
- //#region src/variable.ts
996
- /**
997
- * 跟踪每个 variable 的唯一 Symbol ID
998
- */
999
- const variableIds = /* @__PURE__ */ new WeakMap();
1000
- /**
1001
- * 计数器用于生成唯一变量 ID
1002
- */
1003
- let variableCounter = 0;
1004
- /**
1005
- * 创建一个类型化变量
1006
- * 返回 Proxy 对象,支持链式属性访问和方法调用
1007
- *
1008
- * @example
1009
- * ```ts
1010
- * const x = variable<number>();
1011
- * const config = variable<{ timeout: number }>();
1012
- * const timeout = config.timeout; // Proxy expression
1013
- * ```
1014
- */
1015
- function variable() {
1016
- const id = Symbol(`var_${variableCounter++}`);
1017
- const proxy = createProxyVariable(id);
1018
- variableIds.set(proxy, id);
1019
- return proxy;
1020
- }
1021
- /**
1022
- * 获取 variable 的唯一 Symbol ID
1023
- */
1024
- function getVariableId(variable) {
1025
- if (typeof variable !== "object" && typeof variable !== "function" || variable === null) return void 0;
1026
- return variableIds.get(variable);
1027
- }
1028
- /**
1029
- * 生成变量占位符字符串
1030
- * 格式:$$VAR_var_N$$
1031
- */
1032
- function getVariablePlaceholder(id) {
1033
- return `$$VAR_${id.description}$$`;
1034
- }
1035
-
1036
- //#endregion
1037
- //#region src/compile.ts
1038
- const ALLOWED_GLOBALS = new Set([
1039
- "Math",
1040
- "JSON",
1041
- "Date",
1042
- "RegExp",
1043
- "Number",
1044
- "String",
1045
- "Boolean",
1046
- "Array",
1047
- "Object",
1048
- "undefined",
1049
- "NaN",
1050
- "Infinity",
1051
- "isNaN",
1052
- "isFinite",
1053
- "parseInt",
1054
- "parseFloat",
1055
- "BigInt",
1056
- "URL",
1057
- "URLSearchParams",
1058
- "Map",
1059
- "Set",
1060
- "Int8Array",
1061
- "Uint8Array",
1062
- "Uint8ClampedArray",
1063
- "Int16Array",
1064
- "Uint16Array",
1065
- "Int32Array",
1066
- "Uint32Array",
1067
- "Float32Array",
1068
- "Float64Array",
1069
- "BigInt64Array",
1070
- "BigUint64Array",
1071
- "ArrayBuffer",
1072
- "DataView"
1073
- ]);
1074
- /**
1075
- * 将 Proxy Expression 编译为可序列化的 JSON 结构
1076
- *
1077
- * @template TResult - 表达式结果类型
1078
- * @param expression - Proxy Expression,或包含 Proxy 的对象/数组/原始值
1079
- * @param variables - 所有使用的变量定义
1080
- * @param options - 编译选项
1081
- * @returns 编译后的数据结构 [变量名列表, 表达式1, 表达式2, ...]
1082
- *
1083
- * @throws 如果传入无效的表达式或未定义的变量引用
1084
- *
1085
- * @example
1086
- * ```ts
1087
- * const x = variable<number>()
1088
- * const y = variable<number>()
1089
- * const sum = expr({ x, y })("x + y")
1090
- * const result = expr({ sum, x })("sum * x")
1091
- * const compiled = compile(result, { x, y })
1092
- * // => [["x", "y"], "($0+$1)*$0"]
1093
- * ```
1094
- */
1095
- function compile(expression, variables, options = {}) {
1096
- const { shortCircuit = true } = options;
1097
- const ast = serializeArgumentToAST(expression);
1098
- const variableOrder = [];
1099
- const variableToIndex = /* @__PURE__ */ new Map();
1100
- const descToName = /* @__PURE__ */ new Map();
1101
- for (const [name, value] of Object.entries(variables)) {
1102
- if (!variableToIndex.has(name)) {
1103
- variableToIndex.set(name, variableOrder.length);
1104
- variableOrder.push(name);
1190
+ this.expect("}");
1191
+ return {
1192
+ type: "ObjectExpr",
1193
+ properties
1194
+ };
1195
+ }
1196
+ parseObjectProperty() {
1197
+ this.skipWhitespace();
1198
+ let key;
1199
+ let computed = false;
1200
+ if (this.peek() === "[") {
1201
+ this.advance();
1202
+ this.skipWhitespace();
1203
+ key = this.parseExpression();
1204
+ this.skipWhitespace();
1205
+ this.expect("]");
1206
+ computed = true;
1207
+ } else if (this.peek() === "\"" || this.peek() === "'") key = this.parseString();
1208
+ else key = this.parseIdentifier();
1209
+ this.skipWhitespace();
1210
+ if (this.peek() === ":") {
1211
+ this.advance();
1212
+ this.skipWhitespace();
1213
+ const value = this.parseExpression();
1214
+ return {
1215
+ key,
1216
+ value,
1217
+ computed,
1218
+ shorthand: false
1219
+ };
1105
1220
  }
1106
- const id = getVariableId(value);
1107
- if (id?.description) descToName.set(id.description, name);
1221
+ if (key.type !== "Identifier") throw new Error("Shorthand property must be an identifier");
1222
+ return {
1223
+ key,
1224
+ value: key,
1225
+ computed: false,
1226
+ shorthand: true
1227
+ };
1108
1228
  }
1109
- const undefinedVars = [];
1110
- const transformed = transformIdentifiers(ast, (name) => {
1111
- const placeholderMatch = name.match(/^\$\$VAR_(.+)\$\$$/);
1112
- const resolvedName = placeholderMatch ? descToName.get(placeholderMatch[1]) : name;
1113
- if (placeholderMatch && !resolvedName) throw new Error(`Unknown variable placeholder: ${name}`);
1114
- const index = variableToIndex.get(resolvedName);
1115
- if (index !== void 0) return `$${index}`;
1116
- if (!ALLOWED_GLOBALS.has(resolvedName)) undefinedVars.push(resolvedName);
1117
- return resolvedName;
1118
- });
1119
- if (undefinedVars.length > 0) {
1120
- const uniqueVars = [...new Set(undefinedVars)];
1121
- throw new Error(`Undefined variable(s): ${uniqueVars.join(", ")}`);
1229
+ parseIdentifier() {
1230
+ const start = this.pos;
1231
+ while (this.isIdentifierPart(this.peek())) this.advance();
1232
+ const name = this.source.slice(start, this.pos);
1233
+ if (!name) throw new Error(`Expected identifier at position ${this.pos}`);
1234
+ return {
1235
+ type: "Identifier",
1236
+ name
1237
+ };
1122
1238
  }
1123
- const expressions = [];
1124
- if (shortCircuit) {
1125
- let nextIndex = variableOrder.length;
1126
- function compileAst(node) {
1127
- if (node.type === "BinaryExpr" && (node.operator === "||" || node.operator === "&&" || node.operator === "??")) return compileShortCircuit(node);
1128
- if (node.type === "ConditionalExpr") return compileConditional(node);
1129
- const exprStr = generate(node);
1130
- expressions.push(exprStr);
1131
- return nextIndex++;
1239
+ /**
1240
+ * 尝试解析带括号的箭头函数: (a, b) => expr
1241
+ * 使用回溯机制
1242
+ */
1243
+ tryParseArrowFunction() {
1244
+ const savedPos = this.pos;
1245
+ try {
1246
+ this.expect("(");
1247
+ this.skipWhitespace();
1248
+ const params = [];
1249
+ while (this.peek() !== ")") {
1250
+ if (!this.isIdentifierStart(this.peek())) throw new Error("Expected identifier");
1251
+ params.push(this.parseIdentifier());
1252
+ this.skipWhitespace();
1253
+ if (this.peek() === ",") {
1254
+ this.advance();
1255
+ this.skipWhitespace();
1256
+ } else break;
1257
+ }
1258
+ this.expect(")");
1259
+ this.skipWhitespace();
1260
+ if (this.source.slice(this.pos, this.pos + 2) !== "=>") throw new Error("Expected =>");
1261
+ this.pos += 2;
1262
+ this.skipWhitespace();
1263
+ return {
1264
+ type: "ArrowFunctionExpr",
1265
+ params,
1266
+ body: this.parseExpression()
1267
+ };
1268
+ } catch {
1269
+ this.pos = savedPos;
1270
+ return null;
1271
+ }
1272
+ }
1273
+ /**
1274
+ * 尝试解析单参数无括号的箭头函数: a => expr
1275
+ * 使用回溯机制
1276
+ */
1277
+ tryParseSingleParamArrowFunction() {
1278
+ const savedPos = this.pos;
1279
+ try {
1280
+ const param = this.parseIdentifier();
1281
+ this.skipWhitespace();
1282
+ if (this.source.slice(this.pos, this.pos + 2) !== "=>") throw new Error("Expected =>");
1283
+ this.pos += 2;
1284
+ this.skipWhitespace();
1285
+ const body = this.parseExpression();
1286
+ return {
1287
+ type: "ArrowFunctionExpr",
1288
+ params: [param],
1289
+ body
1290
+ };
1291
+ } catch {
1292
+ this.pos = savedPos;
1293
+ return null;
1294
+ }
1295
+ }
1296
+ parseArguments() {
1297
+ const args = [];
1298
+ this.skipWhitespace();
1299
+ while (this.peek() !== ")") {
1300
+ args.push(this.parseExpression());
1301
+ this.skipWhitespace();
1302
+ if (this.peek() === ",") {
1303
+ this.advance();
1304
+ this.skipWhitespace();
1305
+ } else break;
1132
1306
  }
1133
- function compileShortCircuit(node) {
1134
- const leftIdx = compileAst(node.left);
1135
- const branchConditions = {
1136
- "||": `$${leftIdx}`,
1137
- "&&": `!$${leftIdx}`,
1138
- "??": `$${leftIdx}!=null`
1139
- };
1140
- const branchIdx = expressions.length;
1141
- expressions.push([
1142
- "br",
1143
- branchConditions[node.operator],
1144
- 0
1145
- ]);
1146
- nextIndex++;
1147
- compileAst(node.right);
1148
- const skipCount = expressions.length - branchIdx - 1;
1149
- expressions[branchIdx][2] = skipCount;
1150
- const phiIdx = nextIndex++;
1151
- expressions.push(["phi"]);
1152
- return phiIdx;
1307
+ return args;
1308
+ }
1309
+ static OPERATORS = [
1310
+ "instanceof",
1311
+ ">>>",
1312
+ "===",
1313
+ "!==",
1314
+ "&&",
1315
+ "||",
1316
+ "??",
1317
+ "==",
1318
+ "!=",
1319
+ "<=",
1320
+ ">=",
1321
+ "<<",
1322
+ ">>",
1323
+ "**",
1324
+ "in",
1325
+ "+",
1326
+ "-",
1327
+ "*",
1328
+ "/",
1329
+ "%",
1330
+ "<",
1331
+ ">",
1332
+ "&",
1333
+ "|",
1334
+ "^"
1335
+ ];
1336
+ static KEYWORD_OPERATORS = new Set(["in", "instanceof"]);
1337
+ peekOperator() {
1338
+ for (const op of Parser.OPERATORS) {
1339
+ if (!this.source.startsWith(op, this.pos)) continue;
1340
+ if (Parser.KEYWORD_OPERATORS.has(op)) {
1341
+ const nextChar = this.source[this.pos + op.length];
1342
+ if (nextChar && this.isIdentifierPart(nextChar)) continue;
1343
+ }
1344
+ return op;
1153
1345
  }
1154
- function compileConditional(node) {
1155
- const testIdx = compileAst(node.test);
1156
- const branchIdx = expressions.length;
1157
- expressions.push([
1158
- "br",
1159
- `$${testIdx}`,
1160
- 0
1161
- ]);
1162
- nextIndex++;
1163
- compileAst(node.alternate);
1164
- const jmpIdx = expressions.length;
1165
- expressions.push(["jmp", 0]);
1166
- nextIndex++;
1167
- compileAst(node.consequent);
1168
- const thenEndIdx = expressions.length;
1169
- expressions[branchIdx][2] = jmpIdx - branchIdx;
1170
- expressions[jmpIdx][1] = thenEndIdx - jmpIdx - 1;
1171
- const phiIdx = nextIndex++;
1172
- expressions.push(["phi"]);
1173
- return phiIdx;
1346
+ return null;
1347
+ }
1348
+ matchKeyword(keyword) {
1349
+ if (this.source.startsWith(keyword, this.pos)) {
1350
+ const nextChar = this.source[this.pos + keyword.length];
1351
+ if (!nextChar || !this.isIdentifierPart(nextChar)) {
1352
+ this.pos += keyword.length;
1353
+ return true;
1354
+ }
1174
1355
  }
1175
- compileAst(transformed);
1176
- } else expressions.push(generate(transformed));
1177
- return [variableOrder, ...expressions];
1178
- }
1179
-
1180
- //#endregion
1181
- //#region src/evaluate.ts
1182
- /**
1183
- * 缓存已构造的求值函数,以提升重复执行性能
1184
- */
1185
- const evaluatorCache = /* @__PURE__ */ new Map();
1186
- /**
1187
- * 检测编译数据是否包含控制流节点(V2 格式)
1188
- */
1189
- function isV2Format(expressions) {
1190
- return expressions.some((expr) => Array.isArray(expr));
1191
- }
1192
- /**
1193
- * 执行编译后的表达式
1194
- *
1195
- * @template TResult - 表达式结果类型
1196
- * @param data - 编译后的数据结构 [变量名列表, 表达式1, 表达式2, ...]
1197
- * @param values - 变量值映射,按变量名提供值
1198
- * @returns 最后一个表达式的求值结果
1199
- *
1200
- * @throws 如果运行时类型验证失败或表达式执行出错
1201
- *
1202
- * @example
1203
- * ```ts
1204
- * const compiled = [["x", "y"], "$0+$1", "$1*2"]
1205
- * const result = evaluate<number>(compiled, { x: 2, y: 3 })
1206
- * // => 6 (3 * 2)
1207
- * ```
1208
- */
1209
- function evaluate(data, values) {
1210
- if (data.length < 1) throw new Error("Invalid compiled data: must have at least variable names");
1211
- const [variableNames, ...expressions] = data;
1212
- if (!Array.isArray(variableNames)) throw new Error("Invalid compiled data: first element must be variable names array");
1213
- for (const varName of variableNames) {
1214
- if (typeof varName !== "string") throw new Error("Invalid compiled data: variable names must be strings");
1215
- if (!(varName in values)) throw new Error(`Missing required variable: ${varName}`);
1356
+ return false;
1216
1357
  }
1217
- const valueArray = [];
1218
- for (const varName of variableNames) valueArray.push(values[varName]);
1219
- const cacheKey = JSON.stringify(data);
1220
- let evaluator = evaluatorCache.get(cacheKey);
1221
- if (!evaluator) {
1222
- const functionBody = isV2Format(expressions) ? buildEvaluatorFunctionBodyV2(expressions, variableNames.length) : buildEvaluatorFunctionBody(expressions, variableNames.length);
1223
- evaluator = new Function("$values", functionBody);
1224
- evaluatorCache.set(cacheKey, evaluator);
1358
+ peek() {
1359
+ return this.source[this.pos] || "";
1225
1360
  }
1226
- try {
1227
- return evaluator(valueArray);
1228
- } catch (error) {
1229
- throw new Error(`Failed to evaluate expression: ${error instanceof Error ? error.message : String(error)}`);
1361
+ peekAt(offset) {
1362
+ return this.source[this.pos + offset] || "";
1230
1363
  }
1231
- }
1232
- /**
1233
- * 构造求值函数体
1234
- *
1235
- * @param expressions - 表达式列表
1236
- * @param variableCount - 变量数量
1237
- * @returns 函数体字符串
1238
- *
1239
- * @example
1240
- * ```ts
1241
- * buildEvaluatorFunctionBody(["$0+$1", "$2*2"], 2)
1242
- * // 返回执行 $0+$1 并存储到 $values[2],然后执行 $2*2 的函数体
1243
- * ```
1244
- */
1245
- function buildEvaluatorFunctionBody(expressions, variableCount) {
1246
- if (expressions.length === 0) throw new Error("No expressions to evaluate");
1247
- return [
1248
- ...Array.from({ length: variableCount }, (_, i) => `const $${i} = $values[${i}];`),
1249
- ...expressions.map((expr, i) => {
1250
- const idx = variableCount + i;
1251
- return `const $${idx} = ${expr}; $values[${idx}] = $${idx};`;
1252
- }),
1253
- `return $values[$values.length - 1];`
1254
- ].join("\n");
1255
- }
1364
+ advance() {
1365
+ return this.source[this.pos++] || "";
1366
+ }
1367
+ expect(ch) {
1368
+ if (this.peek() !== ch) throw new Error(`Expected '${ch}' at position ${this.pos}, got '${this.peek()}'`);
1369
+ this.advance();
1370
+ }
1371
+ skipWhitespace() {
1372
+ while (/\s/.test(this.peek())) this.advance();
1373
+ }
1374
+ isDigit(ch) {
1375
+ const code = ch.charCodeAt(0);
1376
+ return code >= 48 && code <= 57;
1377
+ }
1378
+ isHexDigit(ch) {
1379
+ const code = ch.charCodeAt(0);
1380
+ return code >= 48 && code <= 57 || code >= 65 && code <= 70 || code >= 97 && code <= 102;
1381
+ }
1382
+ isIdentifierStart(ch) {
1383
+ const code = ch.charCodeAt(0);
1384
+ return code >= 65 && code <= 90 || code >= 97 && code <= 122 || code === 95 || code === 36;
1385
+ }
1386
+ isIdentifierPart(ch) {
1387
+ const code = ch.charCodeAt(0);
1388
+ return code >= 65 && code <= 90 || code >= 97 && code <= 122 || code >= 48 && code <= 57 || code === 95 || code === 36;
1389
+ }
1390
+ };
1256
1391
  /**
1257
- * 构造带控制流支持的求值函数体(V2 格式)
1258
- *
1259
- * @param expressions - 表达式列表(可包含控制流节点)
1260
- * @param variableCount - 变量数量
1261
- * @returns 函数体字符串
1392
+ * 解析 JavaScript 表达式为 AST
1262
1393
  */
1263
- function buildEvaluatorFunctionBodyV2(expressions, variableCount) {
1264
- if (expressions.length === 0) throw new Error("No expressions to evaluate");
1265
- const lines = [
1266
- ...Array.from({ length: variableCount }, (_, i) => `const $${i} = $values[${i}];`),
1267
- "let $pc = 0;",
1268
- "let $lastValue;",
1269
- ...expressions.map((_, i) => `let $${variableCount + i};`),
1270
- `while ($pc < ${expressions.length}) {`,
1271
- " switch ($pc) {"
1272
- ];
1273
- expressions.forEach((expr, i) => {
1274
- const idx = variableCount + i;
1275
- lines.push(` case ${i}: {`);
1276
- if (typeof expr === "string") {
1277
- lines.push(` $${idx} = $lastValue = ${expr};`);
1278
- lines.push(` $values[${idx}] = $${idx};`);
1279
- lines.push(" $pc++; break;");
1280
- } else {
1281
- const [type] = expr;
1282
- switch (type) {
1283
- case "br":
1284
- lines.push(` if (${expr[1]}) { $pc += ${expr[2] + 1}; } else { $pc++; } break;`);
1285
- break;
1286
- case "jmp":
1287
- lines.push(` $pc += ${expr[1] + 1}; break;`);
1288
- break;
1289
- case "phi":
1290
- lines.push(` $${idx} = $values[${idx}] = $lastValue; $pc++; break;`);
1291
- break;
1292
- }
1293
- }
1294
- lines.push(" }");
1295
- });
1296
- lines.push(" }", "}", "return $values[$values.length - 1];");
1297
- return lines.join("\n");
1394
+ function parse(source) {
1395
+ return new Parser(source).parse();
1298
1396
  }
1299
1397
 
1300
1398
  //#endregion
@@ -1352,7 +1450,10 @@ function expr(context) {
1352
1450
  }
1353
1451
  return createProxyExpressionWithAST(transformIdentifiers(parse(source), (name) => {
1354
1452
  const id = nameToId.get(name);
1355
- if (id) return getVariablePlaceholder(id);
1453
+ if (id) return {
1454
+ type: "Placeholder",
1455
+ id
1456
+ };
1356
1457
  const exprAST = nameToExprAST.get(name);
1357
1458
  if (exprAST) return exprAST;
1358
1459
  return name;
@@ -1405,7 +1506,7 @@ function lambda(builder) {
1405
1506
  const paramCount = builder.length;
1406
1507
  const { params, paramSymbols } = createLambdaParams(paramCount);
1407
1508
  const { bodyAst, bodyDeps } = extractBodyAstAndDeps(builder(...params));
1408
- const lambdaProxy = createProxyExpressionWithAST(createArrowFunctionAst(transformParamPlaceholders(bodyAst, paramSymbols), paramCount), filterClosureDeps(bodyDeps, paramSymbols));
1509
+ const lambdaProxy = createProxyExpressionWithAST(createArrowFunctionAst(bodyAst, paramCount, paramSymbols), filterClosureDeps(bodyDeps, paramSymbols));
1409
1510
  const existingMeta = getProxyMetadata(lambdaProxy);
1410
1511
  if (existingMeta) setProxyMetadata(lambdaProxy, {
1411
1512
  ...existingMeta,
@@ -1449,27 +1550,15 @@ function extractBodyAstAndDeps(bodyExpr) {
1449
1550
  }
1450
1551
  }
1451
1552
  /**
1452
- * 将参数占位符标识符转换为实际参数名
1453
- */
1454
- function transformParamPlaceholders(bodyAst, paramSymbols) {
1455
- return transformIdentifiers(bodyAst, (name) => {
1456
- for (let i = 0; i < paramSymbols.length; i++) {
1457
- const sym = paramSymbols[i];
1458
- if (!sym) continue;
1459
- if (name === `$$VAR_${sym.description}$$`) return `_${i}`;
1460
- }
1461
- return name;
1462
- });
1463
- }
1464
- /**
1465
1553
  * 创建箭头函数 AST
1554
+ * 使用 Placeholder 节点作为参数,在代码生成时再分配实际参数名
1466
1555
  */
1467
- function createArrowFunctionAst(bodyAst, paramCount) {
1556
+ function createArrowFunctionAst(bodyAst, paramCount, paramSymbols) {
1468
1557
  return {
1469
1558
  type: "ArrowFunctionExpr",
1470
1559
  params: Array.from({ length: paramCount }, (_, i) => ({
1471
- type: "Identifier",
1472
- name: `_${i}`
1560
+ type: "Placeholder",
1561
+ id: paramSymbols[i]
1473
1562
  })),
1474
1563
  body: bodyAst
1475
1564
  };