Skip to content

Commit

Permalink
RewriteTrailingCommas: take over check, refactor
Browse files Browse the repository at this point in the history
  • Loading branch information
kitbellew committed Mar 27, 2024
1 parent 08f0a19 commit 7f967a1
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 12 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -88,15 +88,10 @@ class RedundantParens(implicit val ftoks: FormatTokens)
session: Session,
style: ScalafmtConfig
): Option[(Replacement, Replacement)] =
ft.right match {
case _: Token.RightParen if left.isRemove && {
val maybeCommaFt = ftoks.prevNonComment(ft)
!maybeCommaFt.left.is[Token.Comma] ||
session.isRemovedOnLeft(maybeCommaFt, true)
} /* check for trailing comma */ =>
Some((left, removeToken))
case _ => None
}
if (left.isRemove && RewriteTrailingCommas.checkIfPrevious)
Some((left, removeToken))
else
None

private def okToReplaceWithCount(numParens: Int, tree: Tree)(implicit
style: ScalafmtConfig
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,13 +10,28 @@ import org.scalafmt.internal.FormatTokens

object RewriteTrailingCommas extends FormatTokensRewrite.RuleFactory {

import FormatTokensRewrite._

override def enabled(implicit style: ScalafmtConfig): Boolean =
style.dialect.allowTrailingCommas &&
style.getTrailingCommas.ne(TrailingCommas.keep)

override def create(implicit ftoks: FormatTokens): FormatTokensRewrite.Rule =
new RewriteTrailingCommas

private[rewrite] def checkIfPrevious(implicit
ft: FormatToken,
session: Session,
ftoks: FormatTokens
): Boolean =
ft.right match {
case _: Token.RightParen =>
val maybeCommaFt = ftoks.prevNonComment(ft)
!maybeCommaFt.left.is[Token.Comma] ||
session.isRemovedOnLeft(maybeCommaFt, true)
case _ => true
}

}

private class RewriteTrailingCommas(implicit val ftoks: FormatTokens)
Expand All @@ -37,9 +52,15 @@ private class RewriteTrailingCommas(implicit val ftoks: FormatTokens)
session: Session,
style: ScalafmtConfig
): Option[Replacement] = {
val ok = ft.right.is[Token.Comma] && {
if (shouldRemove(ft)) Some(removeToken) else None
}

private[rewrite] def shouldRemove(
ft: FormatToken
)(implicit session: Session): Boolean = {
ft.right.is[Token.Comma] && {
val rightOwner = ft.meta.rightOwner
val nft = ftoks.nextNonComment(ftoks.next(ft))
val nft = ftoks.nextNonCommentAfter(ft)

// comma and paren/bracket/brace need to have the same owner
(rightOwner eq nft.meta.rightOwner) && (nft.right match {
Expand All @@ -59,7 +80,6 @@ private class RewriteTrailingCommas(implicit val ftoks: FormatTokens)
case _ => false
})
}
if (ok) Some(removeToken) else None
}

override def onRight(lt: Replacement, hasFormatOff: Boolean)(implicit
Expand Down

0 comments on commit 7f967a1

Please sign in to comment.