Skip to content

Commit

Permalink
RedundantParens: rewrite bodies of if/while/case
Browse files Browse the repository at this point in the history
  • Loading branch information
kitbellew committed May 19, 2022
1 parent 4653e9a commit 09ae200
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 14 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -90,20 +90,23 @@ class RedundantParens(ftoks: FormatTokens) extends FormatTokensRewrite.Rule {
.exists(TreeOps.isSeqSingle) =>
false
case TreeOps.SplitAssignIntoParts((body, _)) =>
body.eq(t) && (t match {
case InfixApp(ia) => !breaksBeforeOp(ia)
case _ => true
})
body.eq(t) && canRewriteBody(t)
case _: Enumerator.Guard => RewriteCtx.isPostfixExpr(t)
case p: Case =>
p.cond.contains(t) && RewriteCtx.isPostfixExpr(t)
case _: Term.Do => false
if (p.body eq t) canRewriteBody(t)
else p.cond.contains(t) && RewriteCtx.isPostfixExpr(t)
case p: Term.Do =>
p.body.eq(t) && canRewriteBody(t)
case p: Term.While =>
style.dialect.allowSignificantIndentation && p.expr == t &&
ftoks.tokenBefore(p.body).left.is[Token.KwDo]
if (p.expr eq t)
style.dialect.allowSignificantIndentation &&
ftoks.tokenBefore(p.body).left.is[Token.KwDo]
else canRewriteBody(t)
case p: Term.If =>
style.dialect.allowSignificantIndentation && p.cond == t &&
ftoks.tokenBefore(p.thenp).left.is[Token.KwThen]
if (p.cond eq t)
style.dialect.allowSignificantIndentation &&
ftoks.tokenBefore(p.thenp).left.is[Token.KwThen]
else canRewriteBody(t)
case InfixApp(pia) if !infixNeedsParens(pia, t) =>
t match {
case InfixApp(tia) =>
Expand Down Expand Up @@ -153,6 +156,12 @@ class RedundantParens(ftoks: FormatTokens) extends FormatTokensRewrite.Rule {
})
}

private def canRewriteBody(tree: Tree): Boolean =
tree match {
case InfixApp(ia) => !breaksBeforeOp(ia)
case _ => true
}

private def findEnclosed(implicit ft: FormatToken): Option[Enclosed] = {
// counts consecutive parent pairs starting with the given one as the innermost
// the parens could belong to tree they are enclosing, or its parent
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1060,7 +1060,7 @@ object a {
}
>>>
object a {
if (true) (foo)
if (true) foo
if (true)
(
a
Expand All @@ -1078,7 +1078,7 @@ object a {
}
>>>
object a {
while (true) (foo)
while (true) foo
while (true)
(
a
Expand All @@ -1097,7 +1097,7 @@ object a {
}
>>>
object a {
do (foo) while (true)
do foo while (true)
do (
a
+ b
Expand All @@ -1116,7 +1116,7 @@ object a {
>>>
object a {
foo match {
case bar => (baz)
case bar => baz
case bar => (
a
+ b
Expand Down

0 comments on commit 09ae200

Please sign in to comment.