Skip to content

Commit ea80c6a

Browse files
committed
fix(parser): add spaces around 'in' and 'instanceof' operators
- Fix generate function to properly handle keyword operators by adding spaces - Add unit tests for 'in' and 'instanceof' operators in parser tests - Ensure 'in' operator works correctly in boolean expressions
1 parent 93fc8fe commit ea80c6a

File tree

3 files changed

+23
-0
lines changed

3 files changed

+23
-0
lines changed

src/integration.boolean.test.ts

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -254,4 +254,17 @@ describe("集成测试:布尔表达式", () => {
254254
}
255255
});
256256
});
257+
258+
describe("in 运算符", () => {
259+
test("检查对象属性", () => {
260+
const obj = variable(z.record(z.string(), z.number()));
261+
const key = variable(z.string());
262+
263+
const hasKey = expr({ key, obj })("key in obj");
264+
const compiled = compile(hasKey, { key, obj });
265+
266+
expect(evaluate<boolean>(compiled, { key: "a", obj: { a: 1, b: 2 } })).toBe(true);
267+
expect(evaluate<boolean>(compiled, { key: "c", obj: { a: 1, b: 2 } })).toBe(false);
268+
});
269+
});
257270
});

src/parser.test.ts

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,12 @@ test("parse: logical operators", () => {
5151
expect(generate(parse("a ?? b"))).toBe("a??b");
5252
});
5353

54+
test("parse: keyword operators (in, instanceof)", () => {
55+
expect(generate(parse("key in obj"))).toBe("key in obj");
56+
expect(generate(parse("value instanceof Array"))).toBe("value instanceof Array");
57+
expect(generate(parse("'prop' in object"))).toBe('"prop" in object');
58+
});
59+
5460
test("parse: unary expressions", () => {
5561
expect(generate(parse("!a"))).toBe("!a");
5662
expect(generate(parse("-a"))).toBe("-a");

src/parser.ts

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -706,6 +706,10 @@ export function generate(node: ASTNode): string {
706706
case "BinaryExpr": {
707707
const left = wrapIfNeeded(node.left, node, "left");
708708
const right = wrapIfNeeded(node.right, node, "right");
709+
// 关键字运算符需要空格
710+
if (node.operator === "in" || node.operator === "instanceof") {
711+
return `${left} ${node.operator} ${right}`;
712+
}
709713
return `${left}${node.operator}${right}`;
710714
}
711715

0 commit comments

Comments
 (0)