From f8fc203351a998377547ef42e250718507f3f384 Mon Sep 17 00:00:00 2001 From: ematipico Date: Mon, 26 Sep 2022 14:49:40 +0100 Subject: [PATCH] fix(rome_js_analyzer): fix false positive for `useOptionalChain` --- .../src/analyzers/nursery/use_optional_chain.rs | 11 ++++++++++- .../specs/nursery/useOptionalChain/validCases.ts | 3 +++ .../specs/nursery/useOptionalChain/validCases.ts.snap | 3 +++ 3 files changed, 16 insertions(+), 1 deletion(-) diff --git a/crates/rome_js_analyze/src/analyzers/nursery/use_optional_chain.rs b/crates/rome_js_analyze/src/analyzers/nursery/use_optional_chain.rs index 844a2ddb4c50..b825901ee161 100644 --- a/crates/rome_js_analyze/src/analyzers/nursery/use_optional_chain.rs +++ b/crates/rome_js_analyze/src/analyzers/nursery/use_optional_chain.rs @@ -114,6 +114,7 @@ impl Rule for UseOptionalChain { JsLogicalOperator::NullishCoalescing | JsLogicalOperator::LogicalOr => { let chain = LogicalOrLikeChain::from_expression(logical)?; + dbg!(&chain); if chain.is_inside_another_chain() { return None; } @@ -641,6 +642,9 @@ impl LogicalOrLikeChain { /// ```js /// (foo || {}).bar; /// ``` + /// + /// The chain is not allowed if: + /// - `left` contains a `JsNewExpression`, e.g. `(new foo() || {}).bar` fn from_expression(logical: &JsLogicalExpression) -> Option { let is_right_empty_object = logical .right() @@ -651,7 +655,12 @@ impl LogicalOrLikeChain { .as_js_object_expression()? .is_empty(); - if !is_right_empty_object { + let chain_not_allowed = matches!( + logical.left().ok()?.omit_parentheses(), + JsAnyExpression::JsNewExpression(_) + ); + + if !is_right_empty_object || chain_not_allowed { return None; } diff --git a/crates/rome_js_analyze/tests/specs/nursery/useOptionalChain/validCases.ts b/crates/rome_js_analyze/tests/specs/nursery/useOptionalChain/validCases.ts index 2020bcc53d0e..461711917432 100644 --- a/crates/rome_js_analyze/tests/specs/nursery/useOptionalChain/validCases.ts +++ b/crates/rome_js_analyze/tests/specs/nursery/useOptionalChain/validCases.ts @@ -36,3 +36,6 @@ foo[12n] && foo[123n].baz; foo[/\w+/] && foo[/ab+c/].baz; ((foo || {})()).bar; + +(new foo || {}).bar +((new foo) || {}).bar diff --git a/crates/rome_js_analyze/tests/specs/nursery/useOptionalChain/validCases.ts.snap b/crates/rome_js_analyze/tests/specs/nursery/useOptionalChain/validCases.ts.snap index 7d14dbb4d541..c210b8287d54 100644 --- a/crates/rome_js_analyze/tests/specs/nursery/useOptionalChain/validCases.ts.snap +++ b/crates/rome_js_analyze/tests/specs/nursery/useOptionalChain/validCases.ts.snap @@ -43,6 +43,9 @@ foo[/\w+/] && foo[/ab+c/].baz; ((foo || {})()).bar; +(new foo || {}).bar +((new foo) || {}).bar + ```