diff --git a/src/main/java/org/openrewrite/staticanalysis/OperatorWrap.java b/src/main/java/org/openrewrite/staticanalysis/OperatorWrap.java index bd662a18e..4e6a2e159 100644 --- a/src/main/java/org/openrewrite/staticanalysis/OperatorWrap.java +++ b/src/main/java/org/openrewrite/staticanalysis/OperatorWrap.java @@ -53,6 +53,11 @@ public TreeVisitor, ExecutionContext> getVisitor() { @Override public J visit(@Nullable Tree tree, ExecutionContext ctx) { if (tree instanceof JavaSourceFile) { + // Kotlin treats a newline as an expression terminator, so a leading binary operator + // becomes a unary operator on a new statement. Only reformat Java compilation units. + if (!(tree instanceof J.CompilationUnit)) { + return (J) tree; + } SourceFile cu = (SourceFile) tree; operatorWrapStyle = Style.from(OperatorWrapStyle.class, cu, Checkstyle::operatorWrapStyle); diff --git a/src/test/java/org/openrewrite/staticanalysis/OperatorWrapKotlinTest.java b/src/test/java/org/openrewrite/staticanalysis/OperatorWrapKotlinTest.java new file mode 100644 index 000000000..10f5559f8 --- /dev/null +++ b/src/test/java/org/openrewrite/staticanalysis/OperatorWrapKotlinTest.java @@ -0,0 +1,46 @@ +/* + * Copyright 2024 the original author or authors. + *
+ * Licensed under the Moderne Source Available License (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + *
+ * https://docs.moderne.io/licensing/moderne-source-available-license + *
+ * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.openrewrite.staticanalysis; + +import org.junit.jupiter.api.Test; +import org.openrewrite.test.RecipeSpec; +import org.openrewrite.test.RewriteTest; + +import static org.openrewrite.kotlin.Assertions.kotlin; + +class OperatorWrapKotlinTest implements RewriteTest { + @Override + public void defaults(RecipeSpec spec) { + spec.recipe(new OperatorWrap(null)); + } + + @Test + void doesNotMoveBinaryOperatorToNewLineInKotlin() { + // In Kotlin a newline ends an expression, so a leading binary operator is parsed as a unary + // operator on a new statement. Moving `+` to the start of the next line breaks the code. + rewriteRun( + kotlin( + """ + fun method(): String { + val s = "aaa" + "b" + + "c" + return s + } + """ + ) + ); + } +}