Skip to content

Commit cc62f24

Browse files
committed
fix: improve adding parens when necessary for object literal exprs
Also, better handling of these nodes in binary exprs even though they would never appear in these contexts
1 parent a4c8fe5 commit cc62f24

File tree

2 files changed

+25
-3
lines changed

2 files changed

+25
-3
lines changed

src/parsing/parser.rs

Lines changed: 15 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2214,7 +2214,13 @@ fn should_add_parens_around_expr(node: Node, context: &Context) -> bool {
22142214
Node::CondExpr(cond_expr) => {
22152215
return cond_expr.test.span().contains(original_node.span());
22162216
}
2217-
Node::OptChainExpr(_) | Node::BinExpr(_) => {
2217+
Node::BinExpr(bin_expr) => {
2218+
// we only care to add parens when it's the left most expr
2219+
if bin_expr.right.span().contains(original_node.span()) {
2220+
return false;
2221+
}
2222+
}
2223+
Node::OptChainExpr(_) => {
22182224
// continue searching
22192225
}
22202226
_ => {
@@ -2307,7 +2313,7 @@ fn parse_non_null_expr<'a>(node: &'a TsNonNullExpr, context: &mut Context<'a>) -
23072313
}
23082314

23092315
fn parse_object_lit<'a>(node: &'a ObjectLit, context: &mut Context<'a>) -> PrintItems {
2310-
parse_object_like_node(
2316+
let items = parse_object_like_node(
23112317
ParseObjectLikeNodeOptions {
23122318
node: node.into(),
23132319
members: node.props.iter().map(|x| x.into()).collect(),
@@ -2319,7 +2325,13 @@ fn parse_object_lit<'a>(node: &'a ObjectLit, context: &mut Context<'a>) -> Print
23192325
node_sorter: None,
23202326
},
23212327
context,
2322-
)
2328+
);
2329+
2330+
return if should_add_parens_around_expr(node.into(), context) {
2331+
surround_with_parens(items)
2332+
} else {
2333+
items
2334+
};
23232335
}
23242336

23252337
fn parse_paren_expr<'a>(node: &'a ParenExpr, context: &mut Context<'a>) -> PrintItems {

tests/specs/expressions/ParenExpr/ParenExpr_All.txt

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -111,6 +111,7 @@ test;
111111
(function test() {}?.prop);
112112
(function test() {}[56]);
113113
(function test() {} + 2);
114+
(2 + function test() {});
114115
1 + (function test() {} + 2);
115116
call(function test() {}());
116117
obj[(function test() {})];
@@ -130,6 +131,7 @@ test = (function() {});
130131
(function test() {})?.prop;
131132
(function test() {})[56];
132133
(function test() {}) + 2;
134+
2 + function test() {};
133135
1 + (function test() {} + 2);
134136
call(function test() {}());
135137
obj[function test() {}];
@@ -177,3 +179,11 @@ new test(() => {});
177179
new (() => {})();
178180
test = () => {};
179181
test = () => {};
182+
183+
== should handle object literal expr in paren expr in expr stmt ==
184+
({ prop: 5 }.prop);
185+
({ prop: 5 }).prop;
186+
187+
[expect]
188+
({ prop: 5 }).prop;
189+
({ prop: 5 }).prop;

0 commit comments

Comments
 (0)