Skip to content

Commit 6c45201

Browse files
feat: add parens around unary expressions in in/instanceof (#564)
1 parent 1dcd758 commit 6c45201

File tree

2 files changed

+51
-0
lines changed

2 files changed

+51
-0
lines changed

src/generation/generate.rs

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3052,6 +3052,11 @@ fn gen_unary_expr<'a>(node: &UnaryExpr<'a>, context: &mut Context<'a>) -> PrintI
30523052
let mut items = PrintItems::new();
30533053
items.push_str(get_operator_text(node.op()));
30543054
items.extend(gen_node(node.arg.into(), context));
3055+
3056+
if get_should_use_parens(node) {
3057+
items = surround_with_parens(items);
3058+
}
3059+
30553060
return items;
30563061

30573062
fn get_operator_text<'a>(op: UnaryOp) -> &'a str {
@@ -3065,6 +3070,13 @@ fn gen_unary_expr<'a>(node: &UnaryExpr<'a>, context: &mut Context<'a>) -> PrintI
30653070
UnaryOp::Tilde => "~",
30663071
}
30673072
}
3073+
3074+
fn get_should_use_parens(node: &UnaryExpr) -> bool {
3075+
if let Node::BinExpr(parent) = node.parent() {
3076+
return matches!(parent.op(), BinaryOp::In | BinaryOp::InstanceOf);
3077+
}
3078+
false
3079+
}
30683080
}
30693081

30703082
fn gen_update_expr<'a>(node: &UpdateExpr<'a>, context: &mut Context<'a>) -> PrintItems {
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
== should properly parenthesize ! operator in in ==
2+
!foo in bar;
3+
(!foo in bar);
4+
!(foo in bar);
5+
(!foo) in bar;
6+
!!foo in bar;
7+
8+
[expect]
9+
(!foo) in bar;
10+
(!foo) in bar;
11+
!(foo in bar);
12+
(!foo) in bar;
13+
(!!foo) in bar;
14+
15+
== should properly parenthesize ! operator in instanceof ==
16+
!foo instanceof Bar;
17+
(!foo instanceof Bar);
18+
!(foo instanceof Bar);
19+
(!foo) instanceof Bar;
20+
!!foo instanceof bar;
21+
22+
[expect]
23+
(!foo) instanceof Bar;
24+
(!foo) instanceof Bar;
25+
!(foo instanceof Bar);
26+
(!foo) instanceof Bar;
27+
(!!foo) instanceof bar;
28+
29+
== should properly parenthesize void operator in instanceof ==
30+
void 0 in bar;
31+
(void 0 in bar);
32+
void (0 in bar);
33+
(void 0) in bar;
34+
35+
[expect]
36+
(void 0) in bar;
37+
(void 0) in bar;
38+
void (0 in bar);
39+
(void 0) in bar;

0 commit comments

Comments
 (0)