feat(prettier): handle parens for (x % y) % z (#1603)

This commit is contained in:
Boshen 2023-12-01 21:29:56 +08:00 committed by GitHub
parent b4e90a723a
commit bb61f10399
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
3 changed files with 27 additions and 12 deletions

View file

@ -84,26 +84,36 @@ impl BinaryishOperator {
return false;
}
if matches!(parent_op, Self::BinaryOperator(op) if op == BinaryOperator::Exponential) {
let Self::BinaryOperator(op) = self else { return true };
let Self::BinaryOperator(parent_op) = parent_op else { return true };
// ** is right-associative
// x ** y ** z --> x ** (y ** z)
if parent_op == BinaryOperator::Exponential {
return false;
}
if matches!(parent_op, Self::BinaryOperator(op) if op.is_equality())
&& matches!(self, Self::BinaryOperator(op) if op.is_equality())
// x == y == z --> (x == y) == z
if parent_op.is_equality() && op.is_equality() {
return false;
}
// x * y % z --> (x * y) % z
if (op == BinaryOperator::Remainder && parent_op.is_multiplicative())
|| (parent_op == BinaryOperator::Remainder && op.is_multiplicative())
{
return false;
}
if self != parent_op
&& matches!(parent_op, Self::BinaryOperator(op) if op.is_multiplicative())
&& matches!(self, Self::BinaryOperator(op) if op.is_multiplicative())
{
// x * y / z --> (x * y) / z
// x / y * z --> (x / y) * z
if op != parent_op && parent_op.is_multiplicative() && op.is_multiplicative() {
return false;
}
if matches!(parent_op, Self::BinaryOperator(op) if op.is_bitshift())
&& matches!(self, Self::BinaryOperator(op) if op.is_bitshift())
{
// x << y << z --> (x << y) << z
if parent_op.is_bitshift() && op.is_bitshift() {
return false;
}

View file

@ -452,6 +452,12 @@ impl<'a> Prettier<'a> {
return true;
}
if parent_precedence < precedence
&& matches!(operator, BinaryishOperator::BinaryOperator(op) if op == BinaryOperator::Remainder)
{
return matches!(parent_operator, BinaryishOperator::BinaryOperator(op) if matches!(op, BinaryOperator::Addition | BinaryOperator::Subtraction));
}
// Add parenthesis when working with bitwise operators
// It's not strictly needed but helps with code understanding
if matches!(parent_kind, AstKind::BinaryExpression(binary_expr) if binary_expr.operator.is_bitwise())

View file

@ -1,4 +1,4 @@
Compatibility: 212/561 (37.79%)
Compatibility: 215/561 (38.32%)
# Failed
@ -75,7 +75,6 @@ Compatibility: 212/561 (37.79%)
* binary-expressions/inline-jsx.js
* binary-expressions/inline-object-array.js
* binary-expressions/jsx_parent.js
* binary-expressions/math.js
* binary-expressions/return.js
* binary-expressions/short-right.js
* binary-expressions/test.js