Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

challenge(formatter): disambiguate unary expr in instanceof and in expr #806

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
15 changes: 14 additions & 1 deletion crates/biome_js_formatter/src/js/expressions/unary_expression.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,9 @@ use crate::parentheses::{unary_like_expression_needs_parentheses, NeedsParenthes

use biome_js_syntax::JsSyntaxNode;
use biome_js_syntax::JsUnaryExpression;
use biome_js_syntax::{JsUnaryExpressionFields, JsUnaryOperator};
use biome_js_syntax::{
JsInExpression, JsInstanceofExpression, JsUnaryExpressionFields, JsUnaryOperator,
};
use biome_rowan::match_ast;

#[derive(Debug, Clone, Default)]
Expand Down Expand Up @@ -65,6 +67,12 @@ impl NeedsParentheses for JsUnaryExpression {
matches!(operator, Ok(JsUnaryOperator::Plus | JsUnaryOperator::Minus))
&& parent_operator == operator
},
// A user typing `!foo instanceof Bar` probably intended `!(foo instanceof Bar)`,
// so format to `(!foo) instance Bar` to what is really happening
JsInstanceofExpression(_) => true,
// A user typing `!foo in bar` probably intended `!(foo instanceof Bar)`,
// so format to `(!foo) in bar` to what is really happening
JsInExpression(_) => true,
_ => {
unary_like_expression_needs_parentheses(self.syntax(), parent)
}
Expand All @@ -83,6 +91,11 @@ mod tests {
fn needs_parentheses() {
assert_needs_parentheses!("class A extends (!B) {}", JsUnaryExpression);

assert_needs_parentheses!("(!foo) instanceof Bar", JsUnaryExpression);
assert_needs_parentheses!("(!foo) instanceof Bar", JsUnaryExpression);
assert_needs_parentheses!("(~foo) in bar", JsUnaryExpression);
assert_needs_parentheses!("(~foo) in bar", JsUnaryExpression);

assert_needs_parentheses!("(+a).b", JsUnaryExpression);
assert_needs_parentheses!("(+a)[b]", JsUnaryExpression);
assert_not_needs_parentheses!("a[+b]", JsUnaryExpression);
Expand Down

This file was deleted.