Skip to content

Commit

Permalink
Prevent adjacent unary operators from merging
Browse files Browse the repository at this point in the history
  • Loading branch information
nreid260 committed Jun 8, 2022
1 parent e563773 commit 03b8ddc
Show file tree
Hide file tree
Showing 2 changed files with 53 additions and 6 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -1075,19 +1075,33 @@ class KotlinInputAstVisitor(
builder.close()
}

override fun visitUnaryExpression(expression: KtUnaryExpression) {
override fun visitPostfixExpression(expression: KtPostfixExpression) {
builder.sync(expression)
builder.block(ZERO) {
visit(expression.baseExpression)
builder.token(expression.operationReference.text)
val baseExpression = expression.baseExpression
val operator = expression.operationReference.text

visit(baseExpression)
if (baseExpression is KtPostfixExpression &&
baseExpression.operationReference.text.last() == operator.first()) {
builder.space()
}
builder.token(operator)
}
}

override fun visitPrefixExpression(expression: KtPrefixExpression) {
builder.sync(expression)
builder.block(ZERO) {
builder.token(expression.operationReference.text)
visit(expression.baseExpression)
val baseExpression = expression.baseExpression
val operator = expression.operationReference.text

builder.token(operator)
if (baseExpression is KtPrefixExpression &&
operator.last() == baseExpression.operationReference.text.first()) {
builder.space()
}
visit(baseExpression)
}
}

Expand Down
35 changes: 34 additions & 1 deletion core/src/test/java/com/facebook/ktfmt/format/FormatterTest.kt
Original file line number Diff line number Diff line change
Expand Up @@ -2834,7 +2834,7 @@ class FormatterTest {
|""".trimMargin())

@Test
fun `Unary expressions`() =
fun `Unary prefix expressions`() =
assertFormatted(
"""
|fun f() {
Expand All @@ -2844,6 +2844,39 @@ class FormatterTest {
| +4
| ++a
| --a
|
| + +a
| +-a
| +!a
| -+a
| - -a
| -!a
| !+a
| !a
| ! !a
|
| + ++a
| +--a
| -++a
| - --a
| !++a
| !--a
|}
|""".trimMargin())

@Test
fun `Unary postfix expressions`() =
assertFormatted(
"""
|fun f() {
| a!!
| a++
| a--
|
| a--!!
| a++!!
|
| a!! !!
|}
|""".trimMargin())

Expand Down

0 comments on commit 03b8ddc

Please sign in to comment.