[ { "repo": "Kotlin/kotlinx.coroutines", "pull_number": 3639, "instance_id": "Kotlin__kotlinx.coroutines-3639", "issue_numbers": [ "3300" ], "base_commit": "1ed19c872e3c283354349ced921d5f039048d4e1", "patch": "diff --git a/kotlinx-coroutines-core/common/src/Job.kt b/kotlinx-coroutines-core/common/src/Job.kt\nindex 65646dc59f..5f40dfc194 100644\n--- a/kotlinx-coroutines-core/common/src/Job.kt\n+++ b/kotlinx-coroutines-core/common/src/Job.kt\n@@ -539,7 +539,7 @@ public fun Job.cancelChildren(cause: Throwable? = null) {\n \n /**\n * Returns `true` when the [Job] of the coroutine in this context is still active\n- * (has not completed and was not cancelled yet).\n+ * (has not completed and was not cancelled yet) or the context does not have a [Job] in it.\n *\n * Check this property in long-running computation loops to support cancellation\n * when [CoroutineScope.isActive] is not available:\n@@ -550,11 +550,11 @@ public fun Job.cancelChildren(cause: Throwable? = null) {\n * }\n * ```\n *\n- * The `coroutineContext.isActive` expression is a shortcut for `coroutineContext[Job]?.isActive == true`.\n+ * The `coroutineContext.isActive` expression is a shortcut for `get(Job)?.isActive ?: true`.\n * See [Job.isActive].\n */\n public val CoroutineContext.isActive: Boolean\n- get() = this[Job]?.isActive == true\n+ get() = get(Job)?.isActive ?: true\n \n /**\n * Cancels [Job] of this context with an optional cancellation cause.\n", "test_patch": "diff --git a/kotlinx-coroutines-core/common/test/CoroutineScopeTest.kt b/kotlinx-coroutines-core/common/test/CoroutineScopeTest.kt\nindex c46f41a073..b678b03c7a 100644\n--- a/kotlinx-coroutines-core/common/test/CoroutineScopeTest.kt\n+++ b/kotlinx-coroutines-core/common/test/CoroutineScopeTest.kt\n@@ -277,4 +277,15 @@ class CoroutineScopeTest : TestBase() {\n \n private fun scopePlusContext(c1: CoroutineContext, c2: CoroutineContext) =\n (ContextScope(c1) + c2).coroutineContext\n+\n+ @Test\n+ fun testIsActiveWithoutJob() {\n+ var invoked = false\n+ suspend fun testIsActive() {\n+ assertTrue(coroutineContext.isActive)\n+ invoked = true\n+ }\n+ ::testIsActive.startCoroutine(Continuation(EmptyCoroutineContext){})\n+ assertTrue(invoked)\n+ }\n }\n", "problem_statement": "Consider deprecating or changing the behaviour of CoroutineContext.isActive\nAccording to the [doc](https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/is-active.html), `isActive` has the following property:\r\n\r\n>The coroutineContext.isActive expression is a shortcut for coroutineContext[Job]?.isActive == true. See [Job.isActive](https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-job/is-active.html).\r\n\r\nIt means that, if the `Job` is not present, `isActive` always returns `false`.\r\n\r\nWe have multiple reports that such behaviour can be error-prone when used with non-`kotlinx.coroutines` entry points, such as Ktor and `suspend fun main`, because it is inconsistent with the overall contract:\r\n\r\n>(Job) has not been completed and was not cancelled yet\r\n\r\n\r\n`CoroutineContext.isActive` predates both `CoroutineScope` (which should always have a `Job` in it, if it's not `GlobalScope`) and `job` extension, so it may be the case that it can be safely deprecated.\r\n\r\nBasically, we have three options:\r\n\r\n* Do nothing, left things as is. It doesn't solve the original issue, but also doesn't introduce any potentially breaking changes\r\n* Deprecate `CoroutineContext.isActive`. Such change has multiple potential downsides\r\n * Its only possible replacement is `this.job.isActive`, but this replacement is not equivalent to the original method -- `.job` throws an exception for contexts without a `Job`. An absence of replacement can be too disturbing as [a lot of code](https://grep.app/search?q=context.isActive&filter[lang][0]=Kotlin) rely on a perfectly fine `ctxWithJob.isActive`\r\n * Code that relies on `.job.isActive` no longer can be called from such entry points safely\r\n* Change the default behaviour -- return `true`. It also \"fixes\" such patterns as `GlobalScope.isActive` but basically is a breaking change\n", "hints_text": "> It also \"fixes\" such patterns as `GlobalScope.isActive`\r\n\r\n`GlobalScope.isActive` is not the same property, and already defaults to `true` when there is no job, so this one is not broken:\r\nhttps://github.com/Kotlin/kotlinx.coroutines/blob/master/kotlinx-coroutines-core/common/src/CoroutineScope.kt#L137\r\n\r\nThis is why I believe it's often more correct to use `CoroutineScope.isActive` rather than `CoroutineContext.isActive`.\r\n\r\n> Its only possible replacement is `this.job.isActive`\r\n\r\nWhy, though? Isn't `this[Job]?.isActive == true` another perfectly valid replacement that doesn't change behaviour? Or is this what you mean by \"absence of replacement\" - just inlining the property?\r\n\r\nI would also be reluctant in suggesting the `.job.isActive` replacement. Very often the authors of those pieces of code just didn't think of the jobless case, and here we would push them towards making their code fail even harder in this case (possibly unknowingly).\r\n\r\n> An absence of replacement can be too disturbing as [a lot of code](https://grep.app/search?q=context.isActive&filter%5Blang%5D%5B0%5D=Kotlin) rely on a perfectly fine `ctxWithJob.isActive`\r\n\r\nWithout better-looking replacement than the body of the current property getter, users could \"fix\" their code by wrapping the body of their function with `coroutineScope { ... }` and accessing the `CoroutineScope.isActive` property from that scope (which would now have a job). Or just use `yield()` if they want to cancel a non-suspending loop. Or just remove that condition altogether because they didn't need it in the first place (calling other suspend functions with prompt cancellation guarantees already).\r\n\r\nWhether we should deprecate `CoroutineContext.isActive` is rather a conceptual matter of whether we want to give meaning to this property when there is no job.\r\n\r\n---\r\nTL;DR: I like both the deprecation option and the default change option, but if we deprecate I find the replacement `.job.isActive` harmful. What I like about the change of default is that even though it's technically breaking, it will probably fix more things than break them, and without any change in the ecosystem but version bumps.", "created_at": "2023-02-23T09:54:20Z", "version": "1.6", "FAIL_TO_PASS": [ "gradle_test_execution" ], "PASS_TO_PASS": [], "ERROR_TO_PASS": [], "environment_setup_commit": "4116d4a178f32b1241db8247a38cd2823fb8b03e" }, { "repo": "Kotlin/kotlinx.coroutines", "pull_number": 3921, "instance_id": "Kotlin__kotlinx.coroutines-3921", "issue_numbers": [ "3920" ], "base_commit": "2b5d93f2dbc0de0f82e4ec9ab7753e5f24da6e30", "patch": "diff --git a/kotlinx-coroutines-core/common/src/Delay.kt b/kotlinx-coroutines-core/common/src/Delay.kt\nindex ba06d9778d..313e87314d 100644\n--- a/kotlinx-coroutines-core/common/src/Delay.kt\n+++ b/kotlinx-coroutines-core/common/src/Delay.kt\n@@ -7,6 +7,7 @@ package kotlinx.coroutines\n import kotlinx.coroutines.selects.*\n import kotlin.coroutines.*\n import kotlin.time.*\n+import kotlin.time.Duration.Companion.nanoseconds\n \n /**\n * This dispatcher _feature_ is implemented by [CoroutineDispatcher] implementations that natively support\n@@ -106,7 +107,7 @@ internal interface DelayWithTimeoutDiagnostics : Delay {\n public suspend fun awaitCancellation(): Nothing = suspendCancellableCoroutine {}\n \n /**\n- * Delays coroutine for a given time without blocking a thread and resumes it after a specified time.\n+ * Delays coroutine for at least the given time without blocking a thread and resumes it after a specified time.\n * If the given [timeMillis] is non-positive, this function returns immediately.\n *\n * This suspending function is cancellable.\n@@ -133,7 +134,7 @@ public suspend fun delay(timeMillis: Long) {\n }\n \n /**\n- * Delays coroutine for a given [duration] without blocking a thread and resumes it after the specified time.\n+ * Delays coroutine for at least the given [duration] without blocking a thread and resumes it after the specified time.\n * If the given [duration] is non-positive, this function returns immediately.\n *\n * This suspending function is cancellable.\n@@ -154,8 +155,10 @@ public suspend fun delay(duration: Duration): Unit = delay(duration.toDelayMilli\n internal val CoroutineContext.delay: Delay get() = get(ContinuationInterceptor) as? Delay ?: DefaultDelay\n \n /**\n- * Convert this duration to its millisecond value.\n- * Positive durations are coerced at least `1`.\n+ * Convert this duration to its millisecond value. Durations which have a nanosecond component less than\n+ * a single millisecond will be rounded up to the next largest millisecond.\n */\n-internal fun Duration.toDelayMillis(): Long =\n- if (this > Duration.ZERO) inWholeMilliseconds.coerceAtLeast(1) else 0\n+internal fun Duration.toDelayMillis(): Long = when (isPositive()) {\n+ true -> plus(999_999L.nanoseconds).inWholeMilliseconds\n+ false -> 0L\n+}\n", "test_patch": "diff --git a/kotlinx-coroutines-core/common/test/DurationToMillisTest.kt b/kotlinx-coroutines-core/common/test/DurationToMillisTest.kt\nnew file mode 100644\nindex 0000000000..e2ea43dd3c\n--- /dev/null\n+++ b/kotlinx-coroutines-core/common/test/DurationToMillisTest.kt\n@@ -0,0 +1,69 @@\n+/*\n+ * Copyright 2016-2023 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.\n+ */\n+package kotlinx.coroutines\n+\n+import kotlin.test.*\n+import kotlin.time.*\n+import kotlin.time.Duration.Companion.milliseconds\n+import kotlin.time.Duration.Companion.nanoseconds\n+import kotlin.time.Duration.Companion.seconds\n+\n+class DurationToMillisTest {\n+\n+ @Test\n+ fun testNegativeDurationCoercedToZeroMillis() {\n+ assertEquals(0L, (-1).seconds.toDelayMillis())\n+ }\n+\n+ @Test\n+ fun testZeroDurationCoercedToZeroMillis() {\n+ assertEquals(0L, 0.seconds.toDelayMillis())\n+ }\n+\n+ @Test\n+ fun testOneNanosecondCoercedToOneMillisecond() {\n+ assertEquals(1L, 1.nanoseconds.toDelayMillis())\n+ }\n+\n+ @Test\n+ fun testOneSecondCoercedTo1000Milliseconds() {\n+ assertEquals(1_000L, 1.seconds.toDelayMillis())\n+ }\n+\n+ @Test\n+ fun testMixedComponentDurationRoundedUpToNextMillisecond() {\n+ assertEquals(999L, (998.milliseconds + 75909.nanoseconds).toDelayMillis())\n+ }\n+\n+ @Test\n+ fun testOneExtraNanosecondRoundedUpToNextMillisecond() {\n+ assertEquals(999L, (998.milliseconds + 1.nanoseconds).toDelayMillis())\n+ }\n+\n+ @Test\n+ fun testInfiniteDurationCoercedToLongMaxValue() {\n+ assertEquals(Long.MAX_VALUE, Duration.INFINITE.toDelayMillis())\n+ }\n+\n+ @Test\n+ fun testNegativeInfiniteDurationCoercedToZero() {\n+ assertEquals(0L, (-Duration.INFINITE).toDelayMillis())\n+ }\n+\n+ @Test\n+ fun testNanosecondOffByOneInfinityDoesNotOverflow() {\n+ assertEquals(Long.MAX_VALUE / 1_000_000, (Long.MAX_VALUE - 1L).nanoseconds.toDelayMillis())\n+ }\n+\n+ @Test\n+ fun testMillisecondOffByOneInfinityDoesNotIncrement() {\n+ assertEquals((Long.MAX_VALUE / 2) - 1, ((Long.MAX_VALUE / 2) - 1).milliseconds.toDelayMillis())\n+ }\n+\n+ @Test\n+ fun testOutOfBoundsNanosecondsButFiniteDoesNotIncrement() {\n+ val milliseconds = Long.MAX_VALUE / 10\n+ assertEquals(milliseconds, milliseconds.milliseconds.toDelayMillis())\n+ }\n+}\n", "problem_statement": "`delay(Duration)` improperly coerces nanoseconds and microseconds\n**Describe the bug**\r\n\r\nI am currently unsure if this is desired behavior, so if it is, please let me know.\r\n\r\nWhen invoking a delay with a `Duration`, the value of that duration is coerced to milliseconds and then delegated to `delay(Long)`. It is not documented behavior that delaying with a duration loses granularity for nanoseconds or microseconds. For example, delaying with `998.75909ms` gets coerced to a call of `998ms` when delegating to `delay(Long)`. \r\n\r\nThe offending code is the following: \r\n\r\n```kt\r\ninternal fun Duration.toDelayMillis(): Long =\r\n if (this > Duration.ZERO) inWholeMilliseconds.coerceAtLeast(1) else 0\r\n```\r\n\r\n**What happened? What should have happened instead?**\r\n\r\nThe symptom of this issue is that when working on implementing a cron-like API for delay based job scheduling, I was having jobs invoked up to 600us before they should have been invoked. The end result was that jobs scheduled to occur at the beginning of a second in a certain time zone would invoke early once and then as expected afterwards in quick succession. \r\n\r\nThe above function `Duration.toDelaymillis` should likely coerce durations which have a nanosecond component up `duration.inWholeMilliseconds + 1`. \r\n\r\nLocally this implementation is working well for me. \r\n\r\n```kt\r\ninternal fun Duration.myToMillis(): Long = if (this > Duration.ZERO) {\r\n val millis = inWholeMilliseconds\r\n if (millis * 1_000_000 < inWholeNanoseconds) millis + 1 else millis\r\n} else 0\r\n```\r\n\r\n**Provide a Reproducer**\r\n\r\n```kt\r\n @Test fun foo() = runTest(timeout = 1.days) {\r\n withContext(Dispatchers.Default) {\r\n while (true) {\r\n val expectedDuration = 998.milliseconds + 902752.nanoseconds\r\n val actualDuration = measureTime { delay(expectedDuration) }\r\n val difference = actualDuration - expectedDuration\r\n assertTrue(difference.isPositive()) // fails\r\n }\r\n }\r\n }\r\n\r\n```\r\n\n", "hints_text": "I am happy to raise a PR if this is indeed a bug! \nThe proposal to round sub-millisecond components up sounds completely reasonable.\nWhen merged, #3921 should solve this bug, but it's worth considering that the delegation of `delay(Duration)` to `delay(Long)` is backwards. The [Worker](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.native.concurrent/-worker/execute-after.html) API supports scheduling execution to the microsecond granularity, for example. \r\n\r\nI don't know if having nanosecond or microsecond granularity has a real use case, so maybe not worth the effort. ", "created_at": "2023-10-23T11:51:19Z", "version": "1.7", "FAIL_TO_PASS": [ "gradle_test_execution" ], "PASS_TO_PASS": [], "ERROR_TO_PASS": [], "environment_setup_commit": "26fab9459955d246c16a8609195526cea7dc6f1e" }, { "repo": "Kotlin/kotlinx.coroutines", "pull_number": 3711, "instance_id": "Kotlin__kotlinx.coroutines-3711", "issue_numbers": [ "3706" ], "base_commit": "d47e9f32f630945b20e88eb559a18c78072f6f40", "patch": "diff --git a/kotlinx-coroutines-core/common/src/flow/operators/Lint.kt b/kotlinx-coroutines-core/common/src/flow/operators/Lint.kt\nindex f7c7528d43..d7fec3fec0 100644\n--- a/kotlinx-coroutines-core/common/src/flow/operators/Lint.kt\n+++ b/kotlinx-coroutines-core/common/src/flow/operators/Lint.kt\n@@ -144,9 +144,19 @@ public inline fun SharedFlow.retryWhen(noinline predicate: suspend FlowCo\n level = DeprecationLevel.WARNING\n )\n @InlineOnly\n-public suspend inline fun SharedFlow.toList(destination: MutableList = ArrayList()): List =\n+public suspend inline fun SharedFlow.toList(): List =\n (this as Flow).toList()\n \n+/**\n+ * A specialized version of [Flow.toList] that returns [Nothing]\n+ * to indicate that [SharedFlow] collection never completes.\n+ */\n+@InlineOnly\n+public suspend inline fun SharedFlow.toList(destination: MutableList): Nothing {\n+ (this as Flow).toList(destination)\n+ throw IllegalStateException(\"this code is supposed to be unreachable\")\n+}\n+\n /**\n * @suppress\n */\n@@ -156,9 +166,19 @@ public suspend inline fun SharedFlow.toList(destination: MutableList =\n level = DeprecationLevel.WARNING\n )\n @InlineOnly\n-public suspend inline fun SharedFlow.toSet(destination: MutableSet = LinkedHashSet()): Set =\n+public suspend inline fun SharedFlow.toSet(): Set =\n (this as Flow).toSet()\n \n+/**\n+ * A specialized version of [Flow.toSet] that returns [Nothing]\n+ * to indicate that [SharedFlow] collection never completes.\n+ */\n+@InlineOnly\n+public suspend inline fun SharedFlow.toSet(destination: MutableSet): Nothing {\n+ (this as Flow).toSet(destination)\n+ throw IllegalStateException(\"this code is supposed to be unreachable\")\n+}\n+\n /**\n * @suppress\n */\n", "test_patch": "diff --git a/kotlinx-coroutines-core/common/test/flow/operators/LintTest.kt b/kotlinx-coroutines-core/common/test/flow/operators/LintTest.kt\nnew file mode 100644\nindex 0000000000..9cf6cbb958\n--- /dev/null\n+++ b/kotlinx-coroutines-core/common/test/flow/operators/LintTest.kt\n@@ -0,0 +1,31 @@\n+/*\n+ * Copyright 2016-2023 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.\n+ */\n+\n+package kotlinx.coroutines.flow.operators\n+\n+import kotlinx.coroutines.*\n+import kotlinx.coroutines.flow.*\n+import kotlin.test.*\n+\n+class LintTest: TestBase() {\n+ /**\n+ * Tests that using [SharedFlow.toList] and similar functions by passing a mutable collection does add values\n+ * to the provided collection.\n+ */\n+ @Test\n+ fun testSharedFlowToCollection() = runTest {\n+ val sharedFlow = MutableSharedFlow()\n+ val list = mutableListOf()\n+ val set = mutableSetOf()\n+ val jobs = listOf(suspend { sharedFlow.toList(list) }, { sharedFlow.toSet(set) }).map {\n+ launch(Dispatchers.Unconfined) { it() }\n+ }\n+ repeat(10) {\n+ sharedFlow.emit(it)\n+ }\n+ jobs.forEach { it.cancelAndJoin() }\n+ assertEquals((0..9).toList(), list)\n+ assertEquals((0..9).toSet(), set)\n+ }\n+}\n", "problem_statement": "`SharedFlow.toList(mutableList)`: difference behavior between 1.6.4 vs 1.7.0-Beta\nSometimes, I use this method to write simple test on SharedFlow.\nVersion 1.6.4 works well.\nSince 1.7.0-Beta, this method is deprecated and the implementation seem be wrong\n\n```kotlin\nval acc = MutableList()\nval job = scope.launch(start = Undispatched) {\n sharedFlow.toList(acc)\n}\n\n// later...\n\njob.cancel()\nassertContentEquals(\n expected = ...,\n actual = acc\n)\n```\n\nIMO, the correct impl. is `SharedFlow.toList(acc) = (this as Flow).toList(acc)`\n", "hints_text": "+1 to this issue and proposed solution. Seems this commit changed the behavior: https://github.com/Kotlin/kotlinx.coroutines/commit/f981a1d00a9d75169321f5ef63fed16622c3e44f", "created_at": "2023-04-12T10:46:21Z", "version": "1.7", "FAIL_TO_PASS": [ "gradle_test_execution" ], "PASS_TO_PASS": [], "ERROR_TO_PASS": [], "environment_setup_commit": "26fab9459955d246c16a8609195526cea7dc6f1e" }, { "repo": "Kotlin/kotlinx.coroutines", "pull_number": 4136, "instance_id": "Kotlin__kotlinx.coroutines-4136", "issue_numbers": [ "4134", "4134" ], "base_commit": "259000fa564d2891650a3decc931a45666e18e5d", "patch": "diff --git a/kotlinx-coroutines-core/common/src/EventLoop.common.kt b/kotlinx-coroutines-core/common/src/EventLoop.common.kt\nindex 6bfcbf0cbf..84291a1b69 100644\n--- a/kotlinx-coroutines-core/common/src/EventLoop.common.kt\n+++ b/kotlinx-coroutines-core/common/src/EventLoop.common.kt\n@@ -256,21 +256,7 @@ internal abstract class EventLoopImplBase: EventLoopImplPlatform(), Delay {\n // unconfined events take priority\n if (processUnconfinedEvent()) return 0\n // queue all delayed tasks that are due to be executed\n- val delayed = _delayed.value\n- if (delayed != null && !delayed.isEmpty) {\n- val now = nanoTime()\n- while (true) {\n- // make sure that moving from delayed to queue removes from delayed only after it is added to queue\n- // to make sure that 'isEmpty' and `nextTime` that check both of them\n- // do not transiently report that both delayed and queue are empty during move\n- delayed.removeFirstIf {\n- if (it.timeToExecute(now)) {\n- enqueueImpl(it)\n- } else\n- false\n- } ?: break // quit loop when nothing more to remove or enqueueImpl returns false on \"isComplete\"\n- }\n- }\n+ enqueueDelayedTasks()\n // then process one event from queue\n val task = dequeue()\n if (task != null) {\n@@ -283,6 +269,8 @@ internal abstract class EventLoopImplBase: EventLoopImplPlatform(), Delay {\n final override fun dispatch(context: CoroutineContext, block: Runnable) = enqueue(block)\n \n open fun enqueue(task: Runnable) {\n+ // are there some delayed tasks that should execute before this one? If so, move them to the queue first.\n+ enqueueDelayedTasks()\n if (enqueueImpl(task)) {\n // todo: we should unpark only when this delayed task became first in the queue\n unpark()\n@@ -336,6 +324,25 @@ internal abstract class EventLoopImplBase: EventLoopImplPlatform(), Delay {\n }\n }\n \n+ /** Move all delayed tasks that are due to the main queue. */\n+ private fun enqueueDelayedTasks() {\n+ val delayed = _delayed.value\n+ if (delayed != null && !delayed.isEmpty) {\n+ val now = nanoTime()\n+ while (true) {\n+ // make sure that moving from delayed to queue removes from delayed only after it is added to queue\n+ // to make sure that 'isEmpty' and `nextTime` that check both of them\n+ // do not transiently report that both delayed and queue are empty during move\n+ delayed.removeFirstIf {\n+ if (it.timeToExecute(now)) {\n+ enqueueImpl(it)\n+ } else\n+ false\n+ } ?: break // quit loop when nothing more to remove or enqueueImpl returns false on \"isComplete\"\n+ }\n+ }\n+ }\n+\n private fun closeQueue() {\n assert { isCompleted }\n _queue.loop { queue ->\n", "test_patch": "diff --git a/kotlinx-coroutines-core/jvm/test/EventLoopsTest.kt b/kotlinx-coroutines-core/jvm/test/EventLoopsTest.kt\nindex 9ab52fd220..551d1977c0 100644\n--- a/kotlinx-coroutines-core/jvm/test/EventLoopsTest.kt\n+++ b/kotlinx-coroutines-core/jvm/test/EventLoopsTest.kt\n@@ -126,6 +126,21 @@ class EventLoopsTest : TestBase() {\n finish(4)\n }\n \n+ /**\n+ * Tests that, when delayed tasks are due on an event loop, they will execute earlier than the newly-scheduled\n+ * non-delayed tasks.\n+ */\n+ @Test\n+ fun testPendingDelayedBeingDueEarlier() = runTest {\n+ launch(start = CoroutineStart.UNDISPATCHED) {\n+ delay(1)\n+ expect(1)\n+ }\n+ Thread.sleep(100)\n+ yield()\n+ finish(2)\n+ }\n+\n class EventSync {\n private val waitingThread = atomic(null)\n private val fired = atomic(false)\n", "problem_statement": "Coroutine on EventLoop dispatcher fails to yield to a task which is resuming after a delay\n```kotlin\r\nfun main() = runBlocking {\r\n launch {\r\n delay(1)\r\n println(\"This should be first\")\r\n }\r\n Thread.sleep(1000)\r\n yield()\r\n println(\"This should be second\")\r\n}\r\n```\r\n\r\n### Actual behaviour\r\nThe code outputs:\r\n```\r\nThis should be second\r\nThis should be first\r\n```\r\nThe call to `yield()` resumes immediately, instead of yielding control to the other coroutine.\r\n\r\nThis seems to be an issue with the `EventLoop` dispatcher used by `runBlocking`. It maintains a separate queue for delayed continuations. On each iteration of the event loop, tasks whose delay has expired are moved from the delay queue to the main event queue. During a call to `yield()`, this takes place _after_ the `yield()` function has added its own continuation to the event queue. That means a `yield()` call will always fail to yield if the only other continuations waiting to resume are ones whose delay has expired since the last dispatch.\r\n\r\n### Expected behaviour\r\nOutput should be:\r\n```\r\nThis should be first\r\nThis should be second\r\n```\r\nOn reaching the call to `yield()`, the `launch` job is already eligible to resume. 1 second has elapsed, which is much longer than the 1ms required delay. The dispatcher should prefer to dispatch the `launch` job, instead of resuming the same coroutine that called `yield()`.\r\n\r\n### Environment\r\n\r\nReproduced using Kotlin 1.9 with coroutines 1.8.1, on JVM 1.8.\r\n\r\nThis issue was first reported by a user on Slack: https://kotlinlang.slack.com/archives/C0B8MA7FA/p1716495410746749\nCoroutine on EventLoop dispatcher fails to yield to a task which is resuming after a delay\n```kotlin\r\nfun main() = runBlocking {\r\n launch {\r\n delay(1)\r\n println(\"This should be first\")\r\n }\r\n Thread.sleep(1000)\r\n yield()\r\n println(\"This should be second\")\r\n}\r\n```\r\n\r\n### Actual behaviour\r\nThe code outputs:\r\n```\r\nThis should be second\r\nThis should be first\r\n```\r\nThe call to `yield()` resumes immediately, instead of yielding control to the other coroutine.\r\n\r\nThis seems to be an issue with the `EventLoop` dispatcher used by `runBlocking`. It maintains a separate queue for delayed continuations. On each iteration of the event loop, tasks whose delay has expired are moved from the delay queue to the main event queue. During a call to `yield()`, this takes place _after_ the `yield()` function has added its own continuation to the event queue. That means a `yield()` call will always fail to yield if the only other continuations waiting to resume are ones whose delay has expired since the last dispatch.\r\n\r\n### Expected behaviour\r\nOutput should be:\r\n```\r\nThis should be first\r\nThis should be second\r\n```\r\nOn reaching the call to `yield()`, the `launch` job is already eligible to resume. 1 second has elapsed, which is much longer than the 1ms required delay. The dispatcher should prefer to dispatch the `launch` job, instead of resuming the same coroutine that called `yield()`.\r\n\r\n### Environment\r\n\r\nReproduced using Kotlin 1.9 with coroutines 1.8.1, on JVM 1.8.\r\n\r\nThis issue was first reported by a user on Slack: https://kotlinlang.slack.com/archives/C0B8MA7FA/p1716495410746749\n", "hints_text": "Here's the sequence of events:\r\n* A new coroutine is launched.\r\n* `Thread.sleep`.\r\n* `yield`.\r\n* Now, the thread can start the coroutine that was `launch`-ed.\r\n* `delay` is called, suspending the new coroutine.\r\n* While the new coroutine is suspended, the old one prints the text.\r\n* The new coroutine wakes up and also prints its text.\r\n\r\n**That said**, this example *should* work the way you describe:\r\n\r\n```kotlin\r\nimport kotlinx.coroutines.*\r\n\r\nfun main() = runBlocking {\r\n launch(start = CoroutineStart.UNDISPATCHED) {\r\n delay(1)\r\n println(\"This should be first\")\r\n }\r\n Thread.sleep(1000)\r\n yield()\r\n println(\"This should be second\")\r\n}\r\n```\r\n\r\nYet it, too, doesn't.\r\n\r\nSo, it looks like there is a real bug here, but at the same time, the example you've submitted *is* working as intended.\nOops! I guess when I was simplifying my reproducer code, I accidentally simplified it too much. Thank you for fixing my mistake. Your explanation makes complete sense and I can now see why the code I shared is actually not demonstrating the bug \ud83e\udd26.\nThe reason behind that behaviour is that internally, there are two event loops -- one is the regular tasks queue, and the other one is the timed tasks queue.\r\n\r\nWhen a timed event fires (meaning it becomes eligible for execution), it is moved to the tasks queue first (which is FIFO), and then the task queue is processed. \r\n\r\nIn theory, we can workaround that by nano-timestamping each event and providing some semi-strict ordering, or by checking timed queue on each regular enqueue, but we should be really careful about the consequences \nActually, @roomscape deserves credit for having already identified this: the same analysis is present in the initial message as well. Thanks for the well-researched issue report!\nI took a shortcut and looked at the minified example and expected/actual results first, and then immediately started to think about the reasons \ud83d\ude05 \r\nThanks, @roomscape, indeed!\nHere's the sequence of events:\r\n* A new coroutine is launched.\r\n* `Thread.sleep`.\r\n* `yield`.\r\n* Now, the thread can start the coroutine that was `launch`-ed.\r\n* `delay` is called, suspending the new coroutine.\r\n* While the new coroutine is suspended, the old one prints the text.\r\n* The new coroutine wakes up and also prints its text.\r\n\r\n**That said**, this example *should* work the way you describe:\r\n\r\n```kotlin\r\nimport kotlinx.coroutines.*\r\n\r\nfun main() = runBlocking {\r\n launch(start = CoroutineStart.UNDISPATCHED) {\r\n delay(1)\r\n println(\"This should be first\")\r\n }\r\n Thread.sleep(1000)\r\n yield()\r\n println(\"This should be second\")\r\n}\r\n```\r\n\r\nYet it, too, doesn't.\r\n\r\nSo, it looks like there is a real bug here, but at the same time, the example you've submitted *is* working as intended.\nOops! I guess when I was simplifying my reproducer code, I accidentally simplified it too much. Thank you for fixing my mistake. Your explanation makes complete sense and I can now see why the code I shared is actually not demonstrating the bug \ud83e\udd26.\nThe reason behind that behaviour is that internally, there are two event loops -- one is the regular tasks queue, and the other one is the timed tasks queue.\r\n\r\nWhen a timed event fires (meaning it becomes eligible for execution), it is moved to the tasks queue first (which is FIFO), and then the task queue is processed. \r\n\r\nIn theory, we can workaround that by nano-timestamping each event and providing some semi-strict ordering, or by checking timed queue on each regular enqueue, but we should be really careful about the consequences \nActually, @roomscape deserves credit for having already identified this: the same analysis is present in the initial message as well. Thanks for the well-researched issue report!\nI took a shortcut and looked at the minified example and expected/actual results first, and then immediately started to think about the reasons \ud83d\ude05 \r\nThanks, @roomscape, indeed!", "created_at": "2024-05-27T14:31:09Z", "version": "1.8", "FAIL_TO_PASS": [ "gradle_test_execution" ], "PASS_TO_PASS": [], "ERROR_TO_PASS": [], "environment_setup_commit": "cd696d3f8f4afdbc735915c2bded974616331b55" }, { "repo": "Kotlin/kotlinx.coroutines", "pull_number": 4303, "instance_id": "Kotlin__kotlinx.coroutines-4303", "issue_numbers": [ "4296" ], "base_commit": "2cafea468e69285f5e2091d6854eab874fafaa11", "patch": "diff --git a/kotlinx-coroutines-core/common/src/AbstractCoroutine.kt b/kotlinx-coroutines-core/common/src/AbstractCoroutine.kt\nindex d2f79c1381..2d6273acc9 100644\n--- a/kotlinx-coroutines-core/common/src/AbstractCoroutine.kt\n+++ b/kotlinx-coroutines-core/common/src/AbstractCoroutine.kt\n@@ -5,6 +5,7 @@ package kotlinx.coroutines\n import kotlinx.coroutines.CoroutineStart.*\n import kotlinx.coroutines.intrinsics.*\n import kotlin.coroutines.*\n+import kotlinx.coroutines.internal.ScopeCoroutine\n \n /**\n * Abstract base class for implementation of coroutines in coroutine builders.\n@@ -100,6 +101,15 @@ public abstract class AbstractCoroutine(\n afterResume(state)\n }\n \n+ /**\n+ * Invoked when the corresponding `AbstractCoroutine` was **conceptually** resumed, but not mechanically.\n+ * Currently, this function only invokes `resume` on the underlying continuation for [ScopeCoroutine]\n+ * or does nothing otherwise.\n+ *\n+ * Examples of resumes:\n+ * - `afterCompletion` calls when the corresponding `Job` changed its state (i.e. got cancelled)\n+ * - [AbstractCoroutine.resumeWith] was invoked\n+ */\n protected open fun afterResume(state: Any?): Unit = afterCompletion(state)\n \n internal final override fun handleOnCompletionException(exception: Throwable) {\ndiff --git a/kotlinx-coroutines-core/common/src/internal/Scopes.kt b/kotlinx-coroutines-core/common/src/internal/Scopes.kt\nindex 7e561c83dc..9b830bd5c9 100644\n--- a/kotlinx-coroutines-core/common/src/internal/Scopes.kt\n+++ b/kotlinx-coroutines-core/common/src/internal/Scopes.kt\n@@ -23,6 +23,13 @@ internal open class ScopeCoroutine(\n uCont.intercepted().resumeCancellableWith(recoverResult(state, uCont))\n }\n \n+ /**\n+ * Invoked when a scoped coorutine was completed in an undispatched manner directly\n+ * at the place of its start because it never suspended.\n+ */\n+ open fun afterCompletionUndispatched() {\n+ }\n+\n override fun afterResume(state: Any?) {\n // Resume direct because scope is already in the correct context\n uCont.resumeWith(recoverResult(state, uCont))\ndiff --git a/kotlinx-coroutines-core/common/src/intrinsics/Undispatched.kt b/kotlinx-coroutines-core/common/src/intrinsics/Undispatched.kt\nindex 254182b387..511199701a 100644\n--- a/kotlinx-coroutines-core/common/src/intrinsics/Undispatched.kt\n+++ b/kotlinx-coroutines-core/common/src/intrinsics/Undispatched.kt\n@@ -79,6 +79,7 @@ private inline fun ScopeCoroutine.undispatchedResult(\n if (result === COROUTINE_SUSPENDED) return COROUTINE_SUSPENDED // (1)\n val state = makeCompletingOnce(result)\n if (state === COMPLETING_WAITING_CHILDREN) return COROUTINE_SUSPENDED // (2)\n+ afterCompletionUndispatched()\n return if (state is CompletedExceptionally) { // (3)\n when {\n shouldThrow(state.cause) -> throw recoverStackTrace(state.cause, uCont)\ndiff --git a/kotlinx-coroutines-core/jvm/src/CoroutineContext.kt b/kotlinx-coroutines-core/jvm/src/CoroutineContext.kt\nindex ae8275f86f..7628d6ac85 100644\n--- a/kotlinx-coroutines-core/jvm/src/CoroutineContext.kt\n+++ b/kotlinx-coroutines-core/jvm/src/CoroutineContext.kt\n@@ -185,7 +185,8 @@ internal actual class UndispatchedCoroutineactual constructor (\n * `withContext` for the sake of logging, MDC, tracing etc., meaning that there exists thousands of\n * undispatched coroutines.\n * Each access to Java's [ThreadLocal] leaves a footprint in the corresponding Thread's `ThreadLocalMap`\n- * that is cleared automatically as soon as the associated thread-local (-> UndispatchedCoroutine) is garbage collected.\n+ * that is cleared automatically as soon as the associated thread-local (-> UndispatchedCoroutine) is garbage collected\n+ * when either the corresponding thread is GC'ed or it cleans up its stale entries on other TL accesses.\n * When such coroutines are promoted to old generation, `ThreadLocalMap`s become bloated and an arbitrary accesses to thread locals\n * start to consume significant amount of CPU because these maps are open-addressed and cleaned up incrementally on each access.\n * (You can read more about this effect as \"GC nepotism\").\n@@ -253,18 +254,26 @@ internal actual class UndispatchedCoroutineactual constructor (\n }\n }\n \n+ override fun afterCompletionUndispatched() {\n+ clearThreadLocal()\n+ }\n+\n override fun afterResume(state: Any?) {\n+ clearThreadLocal()\n+ // resume undispatched -- update context but stay on the same dispatcher\n+ val result = recoverResult(state, uCont)\n+ withContinuationContext(uCont, null) {\n+ uCont.resumeWith(result)\n+ }\n+ }\n+\n+ private fun clearThreadLocal() {\n if (threadLocalIsSet) {\n threadStateToRecover.get()?.let { (ctx, value) ->\n restoreThreadContext(ctx, value)\n }\n threadStateToRecover.remove()\n }\n- // resume undispatched -- update context but stay on the same dispatcher\n- val result = recoverResult(state, uCont)\n- withContinuationContext(uCont, null) {\n- uCont.resumeWith(result)\n- }\n }\n }\n \n", "test_patch": "diff --git a/kotlinx-coroutines-core/jvm/test/ThreadLocalsLeaksTest.kt b/kotlinx-coroutines-core/jvm/test/ThreadLocalsLeaksTest.kt\nnew file mode 100644\nindex 0000000000..19d42fe01c\n--- /dev/null\n+++ b/kotlinx-coroutines-core/jvm/test/ThreadLocalsLeaksTest.kt\n@@ -0,0 +1,100 @@\n+package kotlinx.coroutines\n+\n+import kotlinx.coroutines.testing.TestBase\n+import java.lang.ref.WeakReference\n+import kotlin.coroutines.AbstractCoroutineContextElement\n+import kotlin.coroutines.Continuation\n+import kotlin.coroutines.ContinuationInterceptor\n+import kotlin.coroutines.CoroutineContext\n+import kotlin.test.Test\n+\n+/*\n+ * This is an adapted verion of test from #4296.\n+ *\n+ * qwwdfsad: the test relies on System.gc() actually collecting the garbage.\n+ * If these tests flake on CI, first check that JDK/GC setup in not an issue.\n+ */\n+class ThreadLocalCustomContinuationInterceptorTest : TestBase() {\n+\n+ private class CustomContinuationInterceptor(private val delegate: ContinuationInterceptor) :\n+ AbstractCoroutineContextElement(ContinuationInterceptor), ContinuationInterceptor {\n+\n+ override fun interceptContinuation(continuation: Continuation): Continuation {\n+ return delegate.interceptContinuation(continuation)\n+ }\n+ }\n+\n+ private class CustomNeverEqualContinuationInterceptor(private val delegate: ContinuationInterceptor) :\n+ AbstractCoroutineContextElement(ContinuationInterceptor), ContinuationInterceptor {\n+\n+ override fun interceptContinuation(continuation: Continuation): Continuation {\n+ return delegate.interceptContinuation(continuation)\n+ }\n+\n+ override fun equals(other: Any?) = false\n+ }\n+\n+ @Test(timeout = 20_000L)\n+ fun testDefaultDispatcherNoSuspension() = ensureCoroutineContextGCed(Dispatchers.Default, suspend = false)\n+\n+ @Test(timeout = 20_000L)\n+ fun testDefaultDispatcher() = ensureCoroutineContextGCed(Dispatchers.Default, suspend = true)\n+\n+\n+ @Test(timeout = 20_000L)\n+ fun testNonCoroutineDispatcher() = ensureCoroutineContextGCed(\n+ CustomContinuationInterceptor(Dispatchers.Default),\n+ suspend = true\n+ )\n+\n+ @Test(timeout = 20_000L)\n+ fun testNonCoroutineDispatcherSuspension() = ensureCoroutineContextGCed(\n+ CustomContinuationInterceptor(Dispatchers.Default),\n+ suspend = false\n+ )\n+\n+ // Note asymmetric equals codepath never goes through the undispatched withContext, thus the separate test case\n+\n+ @Test(timeout = 20_000L)\n+ fun testNonCoroutineDispatcherAsymmetricEquals() =\n+ ensureCoroutineContextGCed(\n+ CustomNeverEqualContinuationInterceptor(Dispatchers.Default),\n+ suspend = true\n+ )\n+\n+ @Test(timeout = 20_000L)\n+ fun testNonCoroutineDispatcherAsymmetricEqualsSuspension() =\n+ ensureCoroutineContextGCed(\n+ CustomNeverEqualContinuationInterceptor(Dispatchers.Default),\n+ suspend = false\n+ )\n+\n+\n+ @Volatile\n+ private var letThatSinkIn: Any = \"What is my purpose? To frag the garbage collctor\"\n+\n+ private fun ensureCoroutineContextGCed(coroutineContext: CoroutineContext, suspend: Boolean) {\n+ fun forceGcUntilRefIsCleaned(ref: WeakReference) {\n+ while (ref.get() != null) {\n+ System.gc()\n+ letThatSinkIn = LongArray(1024 * 1024)\n+ }\n+ }\n+\n+ runTest {\n+ lateinit var ref: WeakReference\n+ val job = GlobalScope.launch(coroutineContext) {\n+ val coroutineName = CoroutineName(\"Yo\")\n+ ref = WeakReference(coroutineName)\n+ withContext(coroutineName) {\n+ if (suspend) {\n+ delay(1)\n+ }\n+ }\n+ }\n+ job.join()\n+\n+ forceGcUntilRefIsCleaned(ref)\n+ }\n+ }\n+}\n", "problem_statement": "UndispatchedCoroutine leaks CoroutineContext via thread local when using custom ContinuationInterceptor\n# Bug description\r\n\r\nTo fix #2930 (thread locals using `ThreadContextElement` not cleaned up), #3252 introduce a little hack ([source](https://github.com/Kotlin/kotlinx.coroutines/blob/6c6df2b850382887462eeaf51f21f58bd982491d/kotlinx-coroutines-core/jvm/src/CoroutineContext.kt#L214-L243)) in `UndispatchedCoroutine` which immediately saves the previous thread context to `UndispatchedCoroutine.threadStateToRecover` within the `UndispatchedCoroutine` constructor, only when the ContinuationInterceptor is not a CoroutineDispatcher:\r\n\r\n```kotlin\r\ninternal actual class UndispatchedCoroutineactual constructor () : ScopeCoroutine() {\r\n init {\r\n if (uCont.context[ContinuationInterceptor] !is CoroutineDispatcher) {\r\n val values = updateThreadContext(context, null)\r\n restoreThreadContext(context, values)\r\n saveThreadContext(context, values)\r\n }\r\n }\r\n```\r\n\r\nIf the continuation doesn't suspend, then `UndispatchedCoroutine.afterResume()` isn't invoked and `UndispatchedCoroutine.threadStateToRecover.remove()` is not called.\r\n\r\nOne thing of note, the javadoc for `UndispatchedCoroutine.threadStateToRecover` claims this:\r\n\r\n```kotlin\r\n * Each access to Java's [ThreadLocal] leaves a footprint in the corresponding Thread's `ThreadLocalMap`\r\n * that is cleared automatically as soon as the associated thread-local (-> UndispatchedCoroutine) is garbage collected.\r\n```\r\n\r\nUnfortunately, that's not exactly correct. When the ThreadLocal is garbage collected, its value actually stays in the `ThreadLocalMap`, until either the thread itself gets garbage collected, or the ThreadLocal map cleans up stale entries, which only happens when using thread locals some more.\r\n\r\nSo when the right conditions apply, the CoroutineContext instance ends up being held in memory long after it's no longer needed.\r\n\r\nTo reproduce this, you need:\r\n\r\n- A CoroutineContext that contains a ContinuationInterceptor that is not a CoroutineDispatcher (to trigger the UndispatchedCoroutine constructor hack)\r\n- Call `withContext()`, changing the CoroutineContext but without changing the ContinuationInterceptor (to trigger the `withContext()` fast path 2 that starts the coroutine on the same ContinuationInterceptor, wrapping it with UndispatchedCoroutine.\r\n\r\nHere's a repro: https://github.com/Kotlin/kotlinx.coroutines/pull/4295\r\n\r\n```kotlin\r\npackage kotlinx.coroutines\r\n\r\nimport kotlinx.coroutines.testing.*\r\nimport org.junit.Test\r\nimport java.lang.ref.*\r\nimport kotlin.coroutines.*\r\nimport kotlin.test.*\r\n\r\nclass CustomContinuationInterceptorTest : TestBase() {\r\n\r\n fun `CoroutineDispatcher not suspending does not leak CoroutineContext`() =\r\n ensureCoroutineContextGCed(Dispatchers.Default, suspend = false)\r\n\r\n @Test\r\n fun `CoroutineDispatcher suspending does not leak CoroutineContext`() =\r\n ensureCoroutineContextGCed(Dispatchers.Default, suspend = true)\r\n\r\n\r\n @Test\r\n fun `CustomContinuationInterceptor suspending does not leak CoroutineContext`() =\r\n ensureCoroutineContextGCed(\r\n CustomContinuationInterceptor(Dispatchers.Default),\r\n suspend = true\r\n )\r\n\r\n // This is the one test that fails\r\n @Test\r\n fun `CustomContinuationInterceptor not suspending leaks CoroutineContext`() =\r\n ensureCoroutineContextGCed(\r\n CustomContinuationInterceptor(Dispatchers.Default),\r\n suspend = false\r\n )\r\n\r\n @Test\r\n fun `CustomNeverEqualContinuationInterceptor suspending does not leak CoroutineContext`() =\r\n ensureCoroutineContextGCed(\r\n CustomNeverEqualContinuationInterceptor(Dispatchers.Default),\r\n suspend = true\r\n )\r\n\r\n @Test\r\n fun `CustomNeverEqualContinuationInterceptor not suspending does not leak CoroutineContext`() =\r\n ensureCoroutineContextGCed(\r\n CustomNeverEqualContinuationInterceptor(Dispatchers.Default),\r\n suspend = false\r\n )\r\n\r\n\r\n private fun ensureCoroutineContextGCed(coroutineContext: CoroutineContext, suspend: Boolean) {\r\n runTest {\r\n lateinit var ref: WeakReference\r\n val job = GlobalScope.launch(coroutineContext) {\r\n val coroutineName = CoroutineName(\"Yo\")\r\n ref = WeakReference(coroutineName)\r\n withContext(coroutineName) {\r\n if (suspend) {\r\n delay(1)\r\n }\r\n }\r\n }\r\n job.join()\r\n\r\n System.gc()\r\n assertNull(ref.get())\r\n }\r\n }\r\n\r\n}\r\n\r\nclass CustomContinuationInterceptor(private val delegate: ContinuationInterceptor) :\r\n AbstractCoroutineContextElement(ContinuationInterceptor), ContinuationInterceptor {\r\n\r\n override fun interceptContinuation(continuation: Continuation): Continuation {\r\n return delegate.interceptContinuation(continuation)\r\n }\r\n}\r\n\r\nclass CustomNeverEqualContinuationInterceptor(private val delegate: ContinuationInterceptor) :\r\n AbstractCoroutineContextElement(ContinuationInterceptor), ContinuationInterceptor {\r\n\r\n override fun interceptContinuation(continuation: Continuation): Continuation {\r\n return delegate.interceptContinuation(continuation)\r\n }\r\n\r\n override fun equals(other: Any?) = false\r\n}\r\n```\r\n\r\n# Fix\r\n\r\nI see a few options:\r\n\r\n- Implement #3253 which presumably means the hack can be removed.\r\n- Provide users with a way to escape the `if (uCont.context[ContinuationInterceptor] !is CoroutineDispatcher) {` check somehow (e.g. introduce an additional funky interface..)\r\n\r\n# Workaround\r\n\r\nOverride equals in any custom `ContinuationInterceptor` implementation and have it return always false, to skip the fast way that's creating the UndispatchedCoroutine creation.\r\n\r\n# How we found this\r\n\r\nI ran into some Compose related memory leaks in Square's UI tests back in February, asked the Compose team if they knew anything about that. They didn't. Then yesterday folks from the Compose team reached out because they're enabling leak detection in their test suite and were running into the exact same leak. We worked together on analyzing a heap dump and debugging and eventually root cause it to this bug.\r\n\r\nThe Compose team is looking into whether they can start using CoroutineDispatcher implementations directly in Compose tests (for other reasons as well, e.g. see [this issue](https://issuetracker.google.com/issues/369224650))\r\n\r\nHere's the leaktrace as reported by leakcanary:\r\n\r\n```\r\n====================================\r\nHEAP ANALYSIS RESULT\r\n====================================\r\n1 APPLICATION LEAKS\r\n\r\nReferences underlined with \"~~~\" are likely causes.\r\nLearn more at https://squ.re/leaks.\r\n\r\n44298 bytes retained by leaking objects\r\nSignature: c4797f2a268bbe8b50072affe05b2f82ce29f5ed\r\n\u252c\u2500\u2500\u2500\r\n\u2502 GC Root: Thread object\r\n\u2502\r\n\u251c\u2500 java.lang.Thread instance\r\n\u2502 Leaking: NO (the main thread always runs)\r\n\u2502 Thread name: 'main'\r\n\u2502 \u2193 Thread.threadLocals\r\n\u2502 ~~~~~~~~~~~~\r\n\u251c\u2500 java.lang.ThreadLocal$ThreadLocalMap instance\r\n\u2502 Leaking: UNKNOWN\r\n\u2502 Retaining 446.6 kB in 9221 objects\r\n\u2502 \u2193 ThreadLocal$ThreadLocalMap.table\r\n\u2502 ~~~~~\r\n\u251c\u2500 java.lang.ThreadLocal$ThreadLocalMap$Entry[] array\r\n\u2502 Leaking: UNKNOWN\r\n\u2502 Retaining 446.6 kB in 9220 objects\r\n\u2502 \u2193 ThreadLocal$ThreadLocalMap$Entry[2]\r\n\u2502 ~~~\r\n\u251c\u2500 java.lang.ThreadLocal$ThreadLocalMap$Entry instance\r\n\u2502 Leaking: UNKNOWN\r\n\u2502 Retaining 444.0 kB in 9136 objects\r\n\u2502 \u2193 ThreadLocal$ThreadLocalMap$Entry.value\r\n\u2502 ~~~~~\r\n\u251c\u2500 kotlin.Pair instance\r\n\u2502 Leaking: UNKNOWN\r\n\u2502 Retaining 444.0 kB in 9135 objects\r\n\u2502 \u2193 Pair.first\r\n\u2502 ~~~~~\r\n\u251c\u2500 kotlin.coroutines.CombinedContext instance\r\n\u2502 Leaking: UNKNOWN\r\n\u2502 Retaining 444.0 kB in 9134 objects\r\n\u2502 \u2193 CombinedContext.left\r\n\u2502 ~~~~\r\n\u251c\u2500 kotlin.coroutines.CombinedContext instance\r\n\u2502 Leaking: UNKNOWN\r\n\u2502 Retaining 442.9 kB in 9112 objects\r\n\u2502 \u2193 CombinedContext.left\r\n\u2502 ~~~~\r\n\u251c\u2500 kotlin.coroutines.CombinedContext instance\r\n\u2502 Leaking: UNKNOWN\r\n\u2502 Retaining 442.9 kB in 9111 objects\r\n\u2502 \u2193 CombinedContext.element\r\n\u2502 ~~~~~~~\r\n\u251c\u2500 kotlinx.coroutines.internal.ScopeCoroutine instance\r\n\u2502 Leaking: UNKNOWN\r\n\u2502 Retaining 441.0 kB in 9040 objects\r\n\u2502 \u2193 ScopeCoroutine.uCont\r\n\u2502 ~~~~~\r\n\u251c\u2500 androidx.compose.foundation.gestures.DefaultScrollableState$scroll$2 instance\r\n\u2502 Leaking: UNKNOWN\r\n\u2502 Retaining 441.0 kB in 9038 objects\r\n\u2502 Anonymous subclass of kotlin.coroutines.jvm.internal.SuspendLambda\r\n\u2502 \u2193 DefaultScrollableState$scroll$2.$block\r\n\u2502 ~~~~~~\r\n\u251c\u2500 androidx.compose.foundation.gestures.ScrollingLogic$scroll$2 instance\r\n\u2502 Leaking: UNKNOWN\r\n\u2502 Retaining 104 B in 2 objects\r\n\u2502 Anonymous subclass of kotlin.coroutines.jvm.internal.SuspendLambda\r\n\u2502 \u2193 ScrollingLogic$scroll$2.this$0\r\n\u2502 ~~~~~~\r\n\u251c\u2500 androidx.compose.foundation.gestures.ScrollingLogic instance\r\n\u2502 Leaking: UNKNOWN\r\n\u2502 Retaining 796 B in 33 objects\r\n\u2502 \u2193 ScrollingLogic.overscrollEffect\r\n\u2502 ~~~~~~~~~~~~~~~~\r\n\u251c\u2500 androidx.compose.foundation.AndroidEdgeEffectOverscrollEffect instance\r\n\u2502 Leaking: UNKNOWN\r\n\u2502 Retaining 484 B in 12 objects\r\n\u2502 \u2193 AndroidEdgeEffectOverscrollEffect.edgeEffectWrapper\r\n\u2502 ~~~~~~~~~~~~~~~~~\r\n\u251c\u2500 androidx.compose.foundation.EdgeEffectWrapper instance\r\n\u2502 Leaking: UNKNOWN\r\n\u2502 Retaining 56 B in 1 objects\r\n\u2502 context instance of androidx.activity.ComponentActivity with mDestroyed = true\r\n\u2502 \u2193 EdgeEffectWrapper.context\r\n\u2502 ~~~~~~~\r\n\u2570\u2192 androidx.activity.ComponentActivity instance\r\n Leaking: YES (ObjectWatcher was watching this because androidx.activity.ComponentActivity received Activity#onDestroy() callback and Activity#mDestroyed is true)\r\n Retaining 44.3 kB in 797 objects\r\n key = 6bdc725d-e124-437c-895d-437bf03213af\r\n watchDurationMillis = 5182\r\n retainedDurationMillis = 174\r\n mApplication instance of android.app.Application\r\n mBase instance of android.app.ContextImpl\r\n```\r\n\r\n\r\nFor anyone with access to the ASG slack, here's the investigation thread: https://androidstudygroup.slack.com/archives/CJH03QASH/p1733875296139909?thread_ts=1708204699.328019&cid=CJH03QASH\r\n\r\n\r\n\n", "hints_text": "Thanks for a really comprehensive and easy-to-follow bug report!\r\n\r\nThe issue is clear, and the potential solution is easy to implement (though hard to accept :)) and is hidden in the problem statement: `If the continuation doesn't suspend, then UndispatchedCoroutine.afterResume() isn't invoked`.\r\n\r\nThe [undispatched handling path](https://github.com/Kotlin/kotlinx.coroutines/blob/master/kotlinx-coroutines-core/common/src/intrinsics/Undispatched.kt#L57) should just be aware of that -- either by having an explicit `cleanup function in `ScopedCoroutine` or by if'ing the actual implementation\nI have a prototype that passes your tests (again, thanks!), I'll polish it up tomorrow morning and open a PR. It should make it to 1.10 coroutines with Kotlin 2.1", "created_at": "2024-12-18T16:10:00Z", "version": "1.9", "FAIL_TO_PASS": [ "gradle_test_execution" ], "PASS_TO_PASS": [], "ERROR_TO_PASS": [], "environment_setup_commit": "6c6df2b850382887462eeaf51f21f58bd982491d" }, { "repo": "Kotlin/kotlinx.coroutines", "pull_number": 3731, "instance_id": "Kotlin__kotlinx.coroutines-3731", "issue_numbers": [ "3714" ], "base_commit": "d6f1403e3b502c181b678a954f4160f659dbbd9d", "patch": "diff --git a/.idea/codeStyles/Project.xml b/.idea/codeStyles/Project.xml\nindex 62fd5c7dfd..461a31ed76 100644\n--- a/.idea/codeStyles/Project.xml\n+++ b/.idea/codeStyles/Project.xml\n@@ -12,4 +12,4 @@\n \n \n \n-\n\\ No newline at end of file\n+\ndiff --git a/kotlinx-coroutines-core/jvm/src/internal/ExceptionsConstructor.kt b/kotlinx-coroutines-core/jvm/src/internal/ExceptionsConstructor.kt\nindex de15225266..03308f6137 100644\n--- a/kotlinx-coroutines-core/jvm/src/internal/ExceptionsConstructor.kt\n+++ b/kotlinx-coroutines-core/jvm/src/internal/ExceptionsConstructor.kt\n@@ -32,42 +32,48 @@ internal fun tryCopyException(exception: E): E? {\n \n private fun createConstructor(clz: Class): Ctor {\n val nullResult: Ctor = { null } // Pre-cache class\n- // Skip reflective copy if an exception has additional fields (that are usually populated in user-defined constructors)\n+ // Skip reflective copy if an exception has additional fields (that are typically populated in user-defined constructors)\n if (throwableFields != clz.fieldsCountOrDefault(0)) return nullResult\n /*\n- * Try to reflectively find constructor(), constructor(message, cause), constructor(cause) or constructor(message).\n- * Exceptions are shared among coroutines, so we should copy exception before recovering current stacktrace.\n- */\n- val constructors = clz.constructors.sortedByDescending { it.parameterTypes.size }\n- for (constructor in constructors) {\n- val result = createSafeConstructor(constructor)\n- if (result != null) return result\n- }\n- return nullResult\n-}\n-\n-private fun createSafeConstructor(constructor: Constructor<*>): Ctor? {\n- val p = constructor.parameterTypes\n- return when (p.size) {\n- 2 -> when {\n- p[0] == String::class.java && p[1] == Throwable::class.java ->\n- safeCtor { e -> constructor.newInstance(e.message, e) as Throwable }\n- else -> null\n+ * Try to reflectively find constructor(message, cause), constructor(message), constructor(cause), or constructor(),\n+ * in that order of priority.\n+ * Exceptions are shared among coroutines, so we should copy exception before recovering current stacktrace.\n+ *\n+ * By default, Java's reflection iterates over ctors in the source-code order and the sorting is stable, so we can\n+ * not rely on the order of iteration. Instead, we assign a unique priority to each ctor type.\n+ */\n+ return clz.constructors.map { constructor ->\n+ val p = constructor.parameterTypes\n+ when (p.size) {\n+ 2 -> when {\n+ p[0] == String::class.java && p[1] == Throwable::class.java ->\n+ safeCtor { e -> constructor.newInstance(e.message, e) as Throwable } to 3\n+ else -> null to -1\n+ }\n+ 1 -> when (p[0]) {\n+ String::class.java ->\n+ safeCtor { e -> (constructor.newInstance(e.message) as Throwable).also { it.initCause(e) } } to 2\n+ Throwable::class.java ->\n+ safeCtor { e -> constructor.newInstance(e) as Throwable } to 1\n+ else -> null to -1\n+ }\n+ 0 -> safeCtor { e -> (constructor.newInstance() as Throwable).also { it.initCause(e) } } to 0\n+ else -> null to -1\n }\n- 1 -> when (p[0]) {\n- Throwable::class.java ->\n- safeCtor { e -> constructor.newInstance(e) as Throwable }\n- String::class.java ->\n- safeCtor { e -> (constructor.newInstance(e.message) as Throwable).also { it.initCause(e) } }\n- else -> null\n- }\n- 0 -> safeCtor { e -> (constructor.newInstance() as Throwable).also { it.initCause(e) } }\n- else -> null\n- }\n+ }.maxByOrNull(Pair<*, Int>::second)?.first ?: nullResult\n }\n \n-private inline fun safeCtor(crossinline block: (Throwable) -> Throwable): Ctor =\n- { e -> runCatching { block(e) }.getOrNull() }\n+private fun safeCtor(block: (Throwable) -> Throwable): Ctor = { e ->\n+ runCatching {\n+ val result = block(e)\n+ /*\n+ * Verify that the new exception has the same message as the original one (bail out if not, see #1631)\n+ * or if the new message complies the contract from `Throwable(cause).message` contract.\n+ */\n+ if (e.message != result.message && result.message != e.toString()) null\n+ else result\n+ }.getOrNull()\n+}\n \n private fun Class<*>.fieldsCountOrDefault(defaultValue: Int) =\n kotlin.runCatching { fieldsCount() }.getOrDefault(defaultValue)\ndiff --git a/kotlinx-coroutines-core/jvm/src/internal/StackTraceRecovery.kt b/kotlinx-coroutines-core/jvm/src/internal/StackTraceRecovery.kt\nindex 5193b0dc26..afc9989646 100644\n--- a/kotlinx-coroutines-core/jvm/src/internal/StackTraceRecovery.kt\n+++ b/kotlinx-coroutines-core/jvm/src/internal/StackTraceRecovery.kt\n@@ -33,16 +33,16 @@ private val stackTraceRecoveryClassName = runCatching {\n internal actual fun recoverStackTrace(exception: E): E {\n if (!RECOVER_STACK_TRACES) return exception\n // No unwrapping on continuation-less path: exception is not reported multiple times via slow paths\n- val copy = tryCopyAndVerify(exception) ?: return exception\n+ val copy = tryCopyException(exception) ?: return exception\n return copy.sanitizeStackTrace()\n }\n \n private fun E.sanitizeStackTrace(): E {\n val stackTrace = stackTrace\n val size = stackTrace.size\n- val lastIntrinsic = stackTrace.frameIndex(stackTraceRecoveryClassName)\n+ val lastIntrinsic = stackTrace.indexOfLast { stackTraceRecoveryClassName == it.className }\n val startIndex = lastIntrinsic + 1\n- val endIndex = stackTrace.frameIndex(baseContinuationImplClassName)\n+ val endIndex = stackTrace.firstFrameIndex(baseContinuationImplClassName)\n val adjustment = if (endIndex == -1) 0 else size - endIndex\n val trace = Array(size - lastIntrinsic - adjustment) {\n if (it == 0) {\n@@ -70,7 +70,7 @@ private fun recoverFromStackFrame(exception: E, continuation: Co\n val (cause, recoveredStacktrace) = exception.causeAndStacktrace()\n \n // Try to create an exception of the same type and get stacktrace from continuation\n- val newException = tryCopyAndVerify(cause) ?: return exception\n+ val newException = tryCopyException(cause) ?: return exception\n // Update stacktrace\n val stacktrace = createStackTrace(continuation)\n if (stacktrace.isEmpty()) return exception\n@@ -82,14 +82,6 @@ private fun recoverFromStackFrame(exception: E, continuation: Co\n return createFinalException(cause, newException, stacktrace)\n }\n \n-private fun tryCopyAndVerify(exception: E): E? {\n- val newException = tryCopyException(exception) ?: return null\n- // Verify that the new exception has the same message as the original one (bail out if not, see #1631)\n- // CopyableThrowable has control over its message and thus can modify it the way it wants\n- if (exception !is CopyableThrowable<*> && newException.message != exception.message) return null\n- return newException\n-}\n-\n /*\n * Here we partially copy original exception stackTrace to make current one much prettier.\n * E.g. for\n@@ -109,7 +101,7 @@ private fun tryCopyAndVerify(exception: E): E? {\n private fun createFinalException(cause: E, result: E, resultStackTrace: ArrayDeque): E {\n resultStackTrace.addFirst(ARTIFICIAL_FRAME)\n val causeTrace = cause.stackTrace\n- val size = causeTrace.frameIndex(baseContinuationImplClassName)\n+ val size = causeTrace.firstFrameIndex(baseContinuationImplClassName)\n if (size == -1) {\n result.stackTrace = resultStackTrace.toTypedArray()\n return result\n@@ -157,7 +149,6 @@ private fun mergeRecoveredTraces(recoveredStacktrace: Array,\n }\n }\n \n-@Suppress(\"NOTHING_TO_INLINE\")\n internal actual suspend inline fun recoverAndThrow(exception: Throwable): Nothing {\n if (!RECOVER_STACK_TRACES) throw exception\n suspendCoroutineUninterceptedOrReturn {\n@@ -198,7 +189,7 @@ private fun createStackTrace(continuation: CoroutineStackFrame): ArrayDeque.frameIndex(methodName: String) = indexOfFirst { methodName == it.className }\n+private fun Array.firstFrameIndex(methodName: String) = indexOfFirst { methodName == it.className }\n \n private fun StackTraceElement.elementWiseEquals(e: StackTraceElement): Boolean {\n /*\n", "test_patch": "diff --git a/kotlinx-coroutines-core/jvm/test-resources/stacktraces/channels/testReceiveFromChannel.txt b/kotlinx-coroutines-core/jvm/test-resources/stacktraces/channels/testReceiveFromChannel.txt\nindex 64085ad329..da3558ba30 100644\n--- a/kotlinx-coroutines-core/jvm/test-resources/stacktraces/channels/testReceiveFromChannel.txt\n+++ b/kotlinx-coroutines-core/jvm/test-resources/stacktraces/channels/testReceiveFromChannel.txt\n@@ -1,5 +1,4 @@\n kotlinx.coroutines.RecoverableTestException\n-\tat kotlinx.coroutines.internal.StackTraceRecoveryKt.recoverStackTrace(StackTraceRecovery.kt)\n \tat kotlinx.coroutines.channels.BufferedChannel.receive$suspendImpl(BufferedChannel.kt)\n \tat kotlinx.coroutines.channels.BufferedChannel.receive(BufferedChannel.kt)\n \tat kotlinx.coroutines.exceptions.StackTraceRecoveryChannelsTest.channelReceive(StackTraceRecoveryChannelsTest.kt)\n@@ -7,4 +6,4 @@ kotlinx.coroutines.RecoverableTestException\n \tat kotlinx.coroutines.exceptions.StackTraceRecoveryChannelsTest$channelReceive$1.invokeSuspend(StackTraceRecoveryChannelsTest.kt)\n Caused by: kotlinx.coroutines.RecoverableTestException\n \tat kotlinx.coroutines.exceptions.StackTraceRecoveryChannelsTest$testReceiveFromChannel$1$job$1.invokeSuspend(StackTraceRecoveryChannelsTest.kt)\n-\tat kotlin.coroutines.jvm.internal.BaseContinuationImpl.resumeWith(ContinuationImpl.kt)\n\\ No newline at end of file\n+\tat kotlin.coroutines.jvm.internal.BaseContinuationImpl.resumeWith(ContinuationImpl.kt)\ndiff --git a/kotlinx-coroutines-core/jvm/test-resources/stacktraces/resume-mode/testUnconfined.txt b/kotlinx-coroutines-core/jvm/test-resources/stacktraces/resume-mode/testUnconfined.txt\nindex a8461556d1..9fc7167833 100644\n--- a/kotlinx-coroutines-core/jvm/test-resources/stacktraces/resume-mode/testUnconfined.txt\n+++ b/kotlinx-coroutines-core/jvm/test-resources/stacktraces/resume-mode/testUnconfined.txt\n@@ -1,5 +1,4 @@\n kotlinx.coroutines.RecoverableTestException\n-\tat kotlinx.coroutines.internal.StackTraceRecoveryKt.recoverStackTrace(StackTraceRecovery.kt)\n \tat kotlinx.coroutines.channels.BufferedChannel.receive$suspendImpl(BufferedChannel.kt)\n \tat kotlinx.coroutines.channels.BufferedChannel.receive(BufferedChannel.kt)\n \tat kotlinx.coroutines.exceptions.StackTraceRecoveryResumeModeTest$withContext$2.invokeSuspend(StackTraceRecoveryResumeModeTest.kt)\n@@ -7,4 +6,4 @@ Caused by: kotlinx.coroutines.RecoverableTestException\n \tat kotlinx.coroutines.exceptions.StackTraceRecoveryResumeModeTest.testResumeModeFastPath(StackTraceRecoveryResumeModeTest.kt)\n \tat kotlinx.coroutines.exceptions.StackTraceRecoveryResumeModeTest.access$testResumeModeFastPath(StackTraceRecoveryResumeModeTest.kt)\n \tat kotlinx.coroutines.exceptions.StackTraceRecoveryResumeModeTest$testUnconfined$1.invokeSuspend(StackTraceRecoveryResumeModeTest.kt)\n-\tat kotlin.coroutines.jvm.internal.BaseContinuationImpl.resumeWith(ContinuationImpl.kt)\n\\ No newline at end of file\n+\tat kotlin.coroutines.jvm.internal.BaseContinuationImpl.resumeWith(ContinuationImpl.kt)\ndiff --git a/kotlinx-coroutines-core/jvm/test/exceptions/StackTraceRecoveryCustomExceptionsTest.kt b/kotlinx-coroutines-core/jvm/test/exceptions/StackTraceRecoveryCustomExceptionsTest.kt\nindex d4e19040a5..0f987e56e0 100644\n--- a/kotlinx-coroutines-core/jvm/test/exceptions/StackTraceRecoveryCustomExceptionsTest.kt\n+++ b/kotlinx-coroutines-core/jvm/test/exceptions/StackTraceRecoveryCustomExceptionsTest.kt\n@@ -87,6 +87,26 @@ class StackTraceRecoveryCustomExceptionsTest : TestBase() {\n assertEquals(\"Token OK\", ex.message)\n }\n \n+ @Test\n+ fun testNestedExceptionWithCause() = runTest {\n+ val result = runCatching {\n+ coroutineScope {\n+ throw NestedException(IllegalStateException(\"ERROR\"))\n+ }\n+ }\n+ val ex = result.exceptionOrNull() ?: error(\"Expected to fail\")\n+ assertIs(ex)\n+ assertIs(ex.cause)\n+ val originalCause = ex.cause?.cause\n+ assertIs(originalCause)\n+ assertEquals(\"ERROR\", originalCause.message)\n+ }\n+\n+ class NestedException : RuntimeException {\n+ constructor(cause: Throwable) : super(cause)\n+ constructor() : super()\n+ }\n+\n @Test\n fun testWrongMessageExceptionInChannel() = runTest {\n val result = produce(SupervisorJob() + Dispatchers.Unconfined) {\n", "problem_statement": "recoverStackTrace causes nested exceptions\n\r\n\r\n**Describe the bug**\r\n\r\nWhen throwing an exception in a coroutine scope it sometimes becomes nested one level too deep in the enclosing exception.\r\n\r\nFor example, if I throw a: `TestException(IllegalStateException(\"test\"))` (a TestException with a cause of IllegalStateException with a message), then the coroutine scope will throw an exception that is: `TestException(TestException(IllegalStateException(\"test\")))`.\r\n\r\n**Provide a Reproducer**\r\n\r\nThe following test will fail as a result of this bug:\r\n\r\n```\r\n@Test\r\nfun testNestedException() = runTest {\r\n val result = runCatching {\r\n coroutineScope {\r\n throw NestedException(IllegalStateException(\"ERROR\"))\r\n }\r\n }\r\n val ex = result.exceptionOrNull() ?: error(\"Expected to fail\")\r\n assertTrue(ex is NestedException)\r\n assertTrue(ex.cause is IllegalStateException)\r\n assertEquals(\"ERROR\", (ex.cause as IllegalStateException).message)\r\n}\r\n\r\nclass NestedException : RuntimeException {\r\n constructor(message: String) : super(message)\r\n constructor(cause: Throwable) : super(cause)\r\n constructor() : super()\r\n}\r\n```\r\n\r\nI can get this test to not fail by changing the order of the constructors in the class to:\r\n\r\n```\r\nclass NestedException : RuntimeException {\r\n constructor(cause: Throwable) : super(cause)\r\n constructor(message: String) : super(message)\r\n constructor() : super()\r\n}\r\n```\r\nBut I don't think this is actually a good solution as it shouldn't matter the order of the constructors in my exception, it should work the same way regardless.\r\n\r\nI think the issue is at [this line](https://github.com/Kotlin/kotlinx.coroutines/blob/3fc1c20a87a689c09f062afc9e3ac347829d29f7/kotlinx-coroutines-core/jvm/src/internal/ExceptionsConstructor.kt#L30) where the wrong constructor is being selected (the string constructor instead of the cause constructor).\n", "hints_text": "Thank you for the report! The actual problem is in this line: https://github.com/Kotlin/kotlinx.coroutines/blob/3fc1c20a87a689c09f062afc9e3ac347829d29f7/kotlinx-coroutines-core/jvm/src/internal/ExceptionsConstructor.kt#L44 Instead of ordering the constructors from best to worst, we exit when we find the first one that matches any viable signature.\nThese two constructors should be identical, something is going completely wrong here", "created_at": "2023-05-01T15:44:00Z", "version": "1.7", "FAIL_TO_PASS": [ "gradle_test_execution" ], "PASS_TO_PASS": [], "ERROR_TO_PASS": [], "environment_setup_commit": "26fab9459955d246c16a8609195526cea7dc6f1e" }, { "repo": "Kotlin/kotlinx.coroutines", "pull_number": 3719, "instance_id": "Kotlin__kotlinx.coroutines-3719", "issue_numbers": [ "3706" ], "base_commit": "2653cd23991bcac4ed75018c5a3130f71df77cc2", "patch": "diff --git a/CHANGES.md b/CHANGES.md\nindex c9ce6b27f8..acf2d2c28b 100644\n--- a/CHANGES.md\n+++ b/CHANGES.md\n@@ -1,5 +1,19 @@\n # Change log for kotlinx.coroutines\n \n+## Version 1.7.0-RC\n+\n+* Kotlin version is updated to 1.8.20.\n+* Atomicfu version is updated to 0.20.2.\n+* `JavaFx` version is updated to 17.0.2 in `kotlinx-coroutines-javafx` (#3671).\n+* `previous-compilation-data.bin` file is removed from JAR resources (#3668).\n+* `CoroutineDispatcher.asExecutor()` runs tasks without dispatching if the dispatcher is unconfined (#3683). Thanks @odedniv!\n+* `SharedFlow.toMutableList` lint overload is undeprecated (#3706).\n+* `Channel.invokeOnClose` is promoted to stable API (#3358).\n+* Improved lock contention in `Dispatchers.Default` and `Dispatchers.IO` during the startup phase (#3652).\n+* Fixed a bug that led to threads oversubscription in `Dispatchers.Default` (#3642).\n+* Fixed a bug that allowed `limitedParallelism` to perform dispatches even after the underlying dispatcher was closed (#3672).\n+* Restored binary compatibility of previously experimental `TestScope.runTest(Long)` (#3673).\n+\n ## Version 1.7.0-Beta\n \n ### Core API significant improvements\ndiff --git a/README.md b/README.md\nindex e709730e19..283afb85ba 100644\n--- a/README.md\n+++ b/README.md\n@@ -3,12 +3,12 @@\n [![Kotlin Stable](https://kotl.in/badges/stable.svg)](https://kotlinlang.org/docs/components-stability.html)\n [![JetBrains official project](https://jb.gg/badges/official.svg)](https://confluence.jetbrains.com/display/ALL/JetBrains+on+GitHub)\n [![GitHub license](https://img.shields.io/badge/license-Apache%20License%202.0-blue.svg?style=flat)](https://www.apache.org/licenses/LICENSE-2.0)\n-[![Download](https://img.shields.io/maven-central/v/org.jetbrains.kotlinx/kotlinx-coroutines-core/1.7.0-Beta)](https://central.sonatype.com/artifact/org.jetbrains.kotlinx/kotlinx-coroutines-core/1.7.0-Beta)\n-[![Kotlin](https://img.shields.io/badge/kotlin-1.8.10-blue.svg?logo=kotlin)](http://kotlinlang.org)\n+[![Download](https://img.shields.io/maven-central/v/org.jetbrains.kotlinx/kotlinx-coroutines-core/1.7.0-RC)](https://central.sonatype.com/artifact/org.jetbrains.kotlinx/kotlinx-coroutines-core/1.7.0-RC)\n+[![Kotlin](https://img.shields.io/badge/kotlin-1.8.20-blue.svg?logo=kotlin)](http://kotlinlang.org)\n [![Slack channel](https://img.shields.io/badge/chat-slack-green.svg?logo=slack)](https://kotlinlang.slack.com/messages/coroutines/)\n \n Library support for Kotlin coroutines with [multiplatform](#multiplatform) support.\n-This is a companion version for the Kotlin `1.8.10` release.\n+This is a companion version for the Kotlin `1.8.20` release.\n \n ```kotlin\n suspend fun main() = coroutineScope {\n@@ -85,7 +85,7 @@ Add dependencies (you can also add other modules that you need):\n \n org.jetbrains.kotlinx\n kotlinx-coroutines-core\n- 1.7.0-Beta\n+ 1.7.0-RC\n \n ```\n \n@@ -93,7 +93,7 @@ And make sure that you use the latest Kotlin version:\n \n ```xml\n \n- 1.8.10\n+ 1.8.20\n \n ```\n \n@@ -103,7 +103,7 @@ Add dependencies (you can also add other modules that you need):\n \n ```kotlin\n dependencies {\n- implementation(\"org.jetbrains.kotlinx:kotlinx-coroutines-core:1.7.0-Beta\")\n+ implementation(\"org.jetbrains.kotlinx:kotlinx-coroutines-core:1.7.0-RC\")\n }\n ```\n \n@@ -112,10 +112,10 @@ And make sure that you use the latest Kotlin version:\n ```kotlin\n plugins {\n // For build.gradle.kts (Kotlin DSL)\n- kotlin(\"jvm\") version \"1.8.10\"\n+ kotlin(\"jvm\") version \"1.8.20\"\n \n // For build.gradle (Groovy DSL)\n- id \"org.jetbrains.kotlin.jvm\" version \"1.8.10\"\n+ id \"org.jetbrains.kotlin.jvm\" version \"1.8.20\"\n }\n ```\n \n@@ -133,7 +133,7 @@ Add [`kotlinx-coroutines-android`](ui/kotlinx-coroutines-android)\n module as a dependency when using `kotlinx.coroutines` on Android:\n \n ```kotlin\n-implementation(\"org.jetbrains.kotlinx:kotlinx-coroutines-android:1.7.0-Beta\")\n+implementation(\"org.jetbrains.kotlinx:kotlinx-coroutines-android:1.7.0-RC\")\n ```\n \n This gives you access to the Android [Dispatchers.Main]\n@@ -168,7 +168,7 @@ In common code that should get compiled for different platforms, you can add a d\n ```kotlin\n commonMain {\n dependencies {\n- implementation(\"org.jetbrains.kotlinx:kotlinx-coroutines-core:1.7.0-Beta\")\n+ implementation(\"org.jetbrains.kotlinx:kotlinx-coroutines-core:1.7.0-RC\")\n }\n }\n ```\n@@ -180,7 +180,7 @@ Platform-specific dependencies are recommended to be used only for non-multiplat\n #### JS\n \n Kotlin/JS version of `kotlinx.coroutines` is published as \n-[`kotlinx-coroutines-core-js`](https://central.sonatype.com/artifact/org.jetbrains.kotlinx/kotlinx-coroutines-core-js/1.7.0-Beta)\n+[`kotlinx-coroutines-core-js`](https://central.sonatype.com/artifact/org.jetbrains.kotlinx/kotlinx-coroutines-core-js/1.7.0-RC)\n (follow the link to get the dependency declaration snippet) and as [`kotlinx-coroutines-core`](https://www.npmjs.com/package/kotlinx-coroutines-core) NPM package. \n \n #### Native\ndiff --git a/build.gradle b/build.gradle\nindex e65558b151..0d17d9dd7b 100644\n--- a/build.gradle\n+++ b/build.gradle\n@@ -5,7 +5,10 @@\n \n import org.jetbrains.kotlin.config.KotlinCompilerVersion\n import org.jetbrains.kotlin.gradle.plugin.KotlinPlatformType\n-import org.jetbrains.kotlin.gradle.tasks.AbstractKotlinCompile\n+import org.jetbrains.kotlin.gradle.targets.js.nodejs.NodeJsRootExtension\n+import org.jetbrains.kotlin.gradle.targets.js.nodejs.NodeJsRootPlugin\n+import org.jetbrains.kotlin.gradle.targets.js.yarn.YarnPlugin\n+import org.jetbrains.kotlin.gradle.targets.js.yarn.YarnRootExtension\n import org.jetbrains.kotlin.konan.target.HostManager\n import org.jetbrains.dokka.gradle.DokkaTaskPartial\n \n@@ -361,3 +364,15 @@ allprojects { subProject ->\n tasks.named(\"dokkaHtmlMultiModule\") {\n pluginsMapConfiguration.set([\"org.jetbrains.dokka.base.DokkaBase\": \"\"\"{ \"templatesDir\": \"${projectDir.toString().replace('\\\\', '/')}/dokka-templates\" }\"\"\"])\n }\n+\n+if (CacheRedirector.enabled) {\n+ def yarnRootExtension = rootProject.extensions.findByType(YarnRootExtension.class)\n+ if (yarnRootExtension != null) {\n+ yarnRootExtension.downloadBaseUrl = CacheRedirector.maybeRedirect(yarnRootExtension.downloadBaseUrl)\n+ }\n+\n+ def nodeJsExtension = rootProject.extensions.findByType(NodeJsRootExtension.class)\n+ if (nodeJsExtension != null) {\n+ nodeJsExtension.nodeDownloadBaseUrl = CacheRedirector.maybeRedirect(nodeJsExtension.nodeDownloadBaseUrl)\n+ }\n+}\ndiff --git a/buildSrc/src/main/kotlin/CacheRedirector.kt b/buildSrc/src/main/kotlin/CacheRedirector.kt\nindex bcadd7364e..c0d835159c 100644\n--- a/buildSrc/src/main/kotlin/CacheRedirector.kt\n+++ b/buildSrc/src/main/kotlin/CacheRedirector.kt\n@@ -26,31 +26,33 @@ private val mirroredUrls = listOf(\n \"https://dl.google.com/dl/android/studio/ide-zips\",\n \"https://dl.google.com/go\",\n \"https://download.jetbrains.com\",\n+ \"https://github.com/yarnpkg/yarn/releases/download\",\n \"https://jitpack.io\",\n- \"https://maven.pkg.jetbrains.space/kotlin/p/kotlin/dev\",\n \"https://maven.pkg.jetbrains.space/kotlin/p/kotlin/bootstrap\",\n+ \"https://maven.pkg.jetbrains.space/kotlin/p/kotlin/dev\",\n \"https://maven.pkg.jetbrains.space/kotlin/p/kotlin/eap\",\n+ \"https://nodejs.org/dist\",\n \"https://oss.sonatype.org/content/repositories/releases\",\n \"https://oss.sonatype.org/content/repositories/snapshots\",\n \"https://oss.sonatype.org/content/repositories/staging\",\n \"https://packages.confluent.io/maven/\",\n \"https://plugins.gradle.org/m2\",\n \"https://plugins.jetbrains.com/maven\",\n- \"https://repo1.maven.org/maven2\",\n \"https://repo.grails.org/grails/core\",\n \"https://repo.jenkins-ci.org/releases\",\n \"https://repo.maven.apache.org/maven2\",\n \"https://repo.spring.io/milestone\",\n \"https://repo.typesafe.com/typesafe/ivy-releases\",\n+ \"https://repo1.maven.org/maven2\",\n \"https://services.gradle.org\",\n \"https://www.exasol.com/artifactory/exasol-releases\",\n+ \"https://www.jetbrains.com/intellij-repository/nightly\",\n+ \"https://www.jetbrains.com/intellij-repository/releases\",\n+ \"https://www.jetbrains.com/intellij-repository/snapshots\",\n \"https://www.myget.org/F/intellij-go-snapshots/maven\",\n \"https://www.myget.org/F/rd-model-snapshots/maven\",\n \"https://www.myget.org/F/rd-snapshots/maven\",\n \"https://www.python.org/ftp\",\n- \"https://www.jetbrains.com/intellij-repository/nightly\",\n- \"https://www.jetbrains.com/intellij-repository/releases\",\n- \"https://www.jetbrains.com/intellij-repository/snapshots\"\n )\n \n private val aliases = mapOf(\n@@ -115,4 +117,13 @@ object CacheRedirector {\n fun Project.configure() {\n checkRedirect(repositories, displayName)\n }\n+\n+ @JvmStatic\n+ fun maybeRedirect(url: String): String {\n+ if (!cacheRedirectorEnabled) return url\n+ return URI(url).maybeRedirect()?.toString() ?: url\n+ }\n+\n+ @JvmStatic\n+ val isEnabled get() = cacheRedirectorEnabled\n }\ndiff --git a/buildSrc/src/main/kotlin/Java9Modularity.kt b/buildSrc/src/main/kotlin/Java9Modularity.kt\nindex 27f1bd38cc..ccd7ef33dd 100644\n--- a/buildSrc/src/main/kotlin/Java9Modularity.kt\n+++ b/buildSrc/src/main/kotlin/Java9Modularity.kt\n@@ -143,6 +143,8 @@ object Java9Modularity {\n attributes(\"Multi-Release\" to true)\n }\n from(compileJavaModuleInfo) {\n+ // Include **only** file we are interested in as JavaCompile output also contains some tmp files\n+ include(\"module-info.class\")\n into(\"META-INF/versions/9/\")\n }\n }\ndiff --git a/gradle.properties b/gradle.properties\nindex d31f646d0e..966a90daf6 100644\n--- a/gradle.properties\n+++ b/gradle.properties\n@@ -3,14 +3,14 @@\n #\n \n # Kotlin\n-version=1.7.0-Beta-SNAPSHOT\n+version=1.7.0-RC-SNAPSHOT\n group=org.jetbrains.kotlinx\n-kotlin_version=1.8.10\n+kotlin_version=1.8.20\n \n # Dependencies\n junit_version=4.12\n junit5_version=5.7.0\n-atomicfu_version=0.20.0\n+atomicfu_version=0.20.2\n knit_version=0.4.0\n html_version=0.7.2\n lincheck_version=2.16\n@@ -20,7 +20,7 @@ reactor_version=3.4.1\n reactive_streams_version=1.0.3\n rxjava2_version=2.2.8\n rxjava3_version=3.0.2\n-javafx_version=11.0.2\n+javafx_version=17.0.2\n javafx_plugin_version=0.0.8\n binary_compatibility_validator_version=0.12.0\n kover_version=0.6.1\n@@ -30,7 +30,7 @@ jna_version=5.9.0\n # Android versions\n android_version=4.1.1.4\n androidx_annotation_version=1.1.0\n-robolectric_version=4.4\n+robolectric_version=4.9\n baksmali_version=2.2.7\n \n # JS\ndiff --git a/kotlinx-coroutines-core/build.gradle b/kotlinx-coroutines-core/build.gradle\nindex 2a6dbbc64f..7693966a46 100644\n--- a/kotlinx-coroutines-core/build.gradle\n+++ b/kotlinx-coroutines-core/build.gradle\n@@ -312,12 +312,6 @@ static void configureJvmForLincheck(task, additional = false) {\n task moreTest(dependsOn: [jvmStressTest, jvmLincheckTest, jvmLincheckTestAdditional])\n check.dependsOn moreTest\n \n-tasks.jvmLincheckTest {\n- kover {\n- enabled = false // Always disabled, lincheck doesn't really support coverage\n- }\n-}\n-\n def commonKoverExcludes =\n [\"kotlinx.coroutines.debug.*\", // Tested by debug module\n \"kotlinx.coroutines.channels.ChannelsKt__DeprecatedKt.*\", // Deprecated\n@@ -326,6 +320,9 @@ def commonKoverExcludes =\n ]\n \n kover {\n+ instrumentation {\n+ excludeTasks.add(\"jvmLincheckTest\") // Always disabled, lincheck doesn't really support coverage\n+ }\n filters {\n classes {\n excludes.addAll(commonKoverExcludes)\ndiff --git a/kotlinx-coroutines-core/common/src/JobSupport.kt b/kotlinx-coroutines-core/common/src/JobSupport.kt\nindex 2950ed9814..00c0ec870f 100644\n--- a/kotlinx-coroutines-core/common/src/JobSupport.kt\n+++ b/kotlinx-coroutines-core/common/src/JobSupport.kt\n@@ -208,7 +208,7 @@ public open class JobSupport constructor(active: Boolean) : Job, ChildJob, Paren\n assert { state.isCompleting } // consistency check -- must be marked as completing\n val proposedException = (proposedUpdate as? CompletedExceptionally)?.cause\n // Create the final exception and seal the state so that no more exceptions can be added\n- var wasCancelling = false // KLUDGE: we cannot have contract for our own expect fun synchronized\n+ val wasCancelling: Boolean\n val finalException = synchronized(state) {\n wasCancelling = state.isCancelling\n val exceptions = state.sealLocked(proposedException)\ndiff --git a/kotlinx-coroutines-core/common/src/channels/Channel.kt b/kotlinx-coroutines-core/common/src/channels/Channel.kt\nindex d6f752c740..b14e61bbd2 100644\n--- a/kotlinx-coroutines-core/common/src/channels/Channel.kt\n+++ b/kotlinx-coroutines-core/common/src/channels/Channel.kt\n@@ -105,33 +105,40 @@ public interface SendChannel {\n * If the channel is closed already, the handler is invoked immediately.\n *\n * The meaning of `cause` that is passed to the handler:\n- * * `null` if the channel was closed or cancelled without the corresponding argument\n- * * the cause of `close` or `cancel` otherwise.\n+ * - `null` if the channel was closed normally without the corresponding argument.\n+ * - Instance of [CancellationException] if the channel was cancelled normally without the corresponding argument.\n+ * - The cause of `close` or `cancel` otherwise.\n *\n- * Example of usage (exception handling is omitted):\n+ * ### Execution context and exception safety\n *\n+ * The [handler] is executed as part of the closing or cancelling operation, and only after the channel reaches its final state.\n+ * This means that if the handler throws an exception or hangs, the channel will still be successfully closed or cancelled.\n+ * Unhandled exceptions from [handler] are propagated to the closing or cancelling operation's caller.\n+ *\n+ * Example of usage:\n * ```\n- * val events = Channel(UNLIMITED)\n+ * val events = Channel(UNLIMITED)\n * callbackBasedApi.registerCallback { event ->\n * events.trySend(event)\n+ * .onClosed { /* channel is already closed, but the callback hasn't stopped yet */ }\n * }\n *\n- * val uiUpdater = launch(Dispatchers.Main, parent = UILifecycle) {\n- * events.consume {}\n- * events.cancel()\n+ * val uiUpdater = uiScope.launch(Dispatchers.Main) {\n+ * events.consume { /* handle events */ }\n * }\n- *\n+ * // Stop the callback after the channel is closed or cancelled\n * events.invokeOnClose { callbackBasedApi.stop() }\n * ```\n *\n- * **Note: This is an experimental api.** This function may change its semantics, parameters or return type in the future.\n+ * **Stability note.** This function constitutes a stable API surface, with the only exception being\n+ * that an [IllegalStateException] is thrown when multiple handlers are registered.\n+ * This restriction could be lifted in the future.\n *\n- * @throws UnsupportedOperationException if the underlying channel doesn't support [invokeOnClose].\n+ * @throws UnsupportedOperationException if the underlying channel does not support [invokeOnClose].\n * Implementation note: currently, [invokeOnClose] is unsupported only by Rx-like integrations\n *\n * @throws IllegalStateException if another handler was already registered\n */\n- @ExperimentalCoroutinesApi\n public fun invokeOnClose(handler: (cause: Throwable?) -> Unit)\n \n /**\n@@ -388,7 +395,7 @@ public interface ReceiveChannel {\n * The successful result represents a successful operation with a value of type [T], for example,\n * the result of [Channel.receiveCatching] operation or a successfully sent element as a result of [Channel.trySend].\n *\n- * The failed result represents a failed operation attempt to a channel, but it doesn't necessary indicate that the channel is failed.\n+ * The failed result represents a failed operation attempt to a channel, but it doesn't necessarily indicate that the channel is failed.\n * E.g. when the channel is full, [Channel.trySend] returns failed result, but the channel itself is not in the failed state.\n *\n * The closed result represents an operation attempt to a closed channel and also implies that the operation has failed.\ndiff --git a/kotlinx-coroutines-core/common/src/flow/StateFlow.kt b/kotlinx-coroutines-core/common/src/flow/StateFlow.kt\nindex b65340a836..2f3de1565e 100644\n--- a/kotlinx-coroutines-core/common/src/flow/StateFlow.kt\n+++ b/kotlinx-coroutines-core/common/src/flow/StateFlow.kt\n@@ -319,8 +319,8 @@ private class StateFlowImpl(\n updateState(expect ?: NULL, update ?: NULL)\n \n private fun updateState(expectedState: Any?, newState: Any): Boolean {\n- var curSequence = 0\n- var curSlots: Array? = this.slots // benign race, we will not use it\n+ var curSequence: Int\n+ var curSlots: Array? // benign race, we will not use it\n synchronized(this) {\n val oldState = _state.value\n if (expectedState != null && oldState != expectedState) return false // CAS support\ndiff --git a/kotlinx-coroutines-core/common/src/flow/internal/AbstractSharedFlow.kt b/kotlinx-coroutines-core/common/src/flow/internal/AbstractSharedFlow.kt\nindex d263d61227..5dcf0d01ed 100644\n--- a/kotlinx-coroutines-core/common/src/flow/internal/AbstractSharedFlow.kt\n+++ b/kotlinx-coroutines-core/common/src/flow/internal/AbstractSharedFlow.kt\n@@ -41,7 +41,7 @@ internal abstract class AbstractSharedFlow> : Sync\n @Suppress(\"UNCHECKED_CAST\")\n protected fun allocateSlot(): S {\n // Actually create slot under lock\n- var subscriptionCount: SubscriptionCountStateFlow? = null\n+ val subscriptionCount: SubscriptionCountStateFlow?\n val slot = synchronized(this) {\n val slots = when (val curSlots = slots) {\n null -> createSlotArray(2).also { slots = it }\n@@ -72,7 +72,7 @@ internal abstract class AbstractSharedFlow> : Sync\n @Suppress(\"UNCHECKED_CAST\")\n protected fun freeSlot(slot: S) {\n // Release slot under lock\n- var subscriptionCount: SubscriptionCountStateFlow? = null\n+ val subscriptionCount: SubscriptionCountStateFlow?\n val resumes = synchronized(this) {\n nCollectors--\n subscriptionCount = _subscriptionCount // retrieve under lock if initialized\ndiff --git a/kotlinx-coroutines-core/common/src/flow/operators/Lint.kt b/kotlinx-coroutines-core/common/src/flow/operators/Lint.kt\nindex f7c7528d43..d7fec3fec0 100644\n--- a/kotlinx-coroutines-core/common/src/flow/operators/Lint.kt\n+++ b/kotlinx-coroutines-core/common/src/flow/operators/Lint.kt\n@@ -144,9 +144,19 @@ public inline fun SharedFlow.retryWhen(noinline predicate: suspend FlowCo\n level = DeprecationLevel.WARNING\n )\n @InlineOnly\n-public suspend inline fun SharedFlow.toList(destination: MutableList = ArrayList()): List =\n+public suspend inline fun SharedFlow.toList(): List =\n (this as Flow).toList()\n \n+/**\n+ * A specialized version of [Flow.toList] that returns [Nothing]\n+ * to indicate that [SharedFlow] collection never completes.\n+ */\n+@InlineOnly\n+public suspend inline fun SharedFlow.toList(destination: MutableList): Nothing {\n+ (this as Flow).toList(destination)\n+ throw IllegalStateException(\"this code is supposed to be unreachable\")\n+}\n+\n /**\n * @suppress\n */\n@@ -156,9 +166,19 @@ public suspend inline fun SharedFlow.toList(destination: MutableList =\n level = DeprecationLevel.WARNING\n )\n @InlineOnly\n-public suspend inline fun SharedFlow.toSet(destination: MutableSet = LinkedHashSet()): Set =\n+public suspend inline fun SharedFlow.toSet(): Set =\n (this as Flow).toSet()\n \n+/**\n+ * A specialized version of [Flow.toSet] that returns [Nothing]\n+ * to indicate that [SharedFlow] collection never completes.\n+ */\n+@InlineOnly\n+public suspend inline fun SharedFlow.toSet(destination: MutableSet): Nothing {\n+ (this as Flow).toSet(destination)\n+ throw IllegalStateException(\"this code is supposed to be unreachable\")\n+}\n+\n /**\n * @suppress\n */\ndiff --git a/kotlinx-coroutines-core/common/src/internal/LimitedDispatcher.kt b/kotlinx-coroutines-core/common/src/internal/LimitedDispatcher.kt\nindex 8d814d566d..374e53b7b4 100644\n--- a/kotlinx-coroutines-core/common/src/internal/LimitedDispatcher.kt\n+++ b/kotlinx-coroutines-core/common/src/internal/LimitedDispatcher.kt\n@@ -7,7 +7,6 @@ package kotlinx.coroutines.internal\n import kotlinx.atomicfu.*\n import kotlinx.coroutines.*\n import kotlin.coroutines.*\n-import kotlin.jvm.*\n \n /**\n * The result of .limitedParallelism(x) call, a dispatcher\n@@ -27,7 +26,7 @@ import kotlin.jvm.*\n internal class LimitedDispatcher(\n private val dispatcher: CoroutineDispatcher,\n private val parallelism: Int\n-) : CoroutineDispatcher(), Runnable, Delay by (dispatcher as? Delay ?: DefaultDelay) {\n+) : CoroutineDispatcher(), Delay by (dispatcher as? Delay ?: DefaultDelay) {\n \n // Atomic is necessary here for the sake of K/N memory ordering,\n // there is no need in atomic operations for this property\n@@ -45,61 +44,37 @@ internal class LimitedDispatcher(\n return super.limitedParallelism(parallelism)\n }\n \n- override fun run() {\n- var fairnessCounter = 0\n- while (true) {\n- val task = queue.removeFirstOrNull()\n- if (task != null) {\n- try {\n- task.run()\n- } catch (e: Throwable) {\n- handleCoroutineException(EmptyCoroutineContext, e)\n- }\n- // 16 is our out-of-thin-air constant to emulate fairness. Used in JS dispatchers as well\n- if (++fairnessCounter >= 16 && dispatcher.isDispatchNeeded(this)) {\n- // Do \"yield\" to let other views to execute their runnable as well\n- // Note that we do not decrement 'runningWorkers' as we still committed to do our part of work\n- dispatcher.dispatch(this, this)\n- return\n- }\n- continue\n- }\n-\n- synchronized(workerAllocationLock) {\n- runningWorkers.decrementAndGet()\n- if (queue.size == 0) return\n- runningWorkers.incrementAndGet()\n- fairnessCounter = 0\n- }\n- }\n- }\n-\n override fun dispatch(context: CoroutineContext, block: Runnable) {\n- dispatchInternal(block) {\n- dispatcher.dispatch(this, this)\n+ dispatchInternal(block) { worker ->\n+ dispatcher.dispatch(this, worker)\n }\n }\n \n @InternalCoroutinesApi\n override fun dispatchYield(context: CoroutineContext, block: Runnable) {\n- dispatchInternal(block) {\n- dispatcher.dispatchYield(this, this)\n+ dispatchInternal(block) { worker ->\n+ dispatcher.dispatchYield(this, worker)\n }\n }\n \n- private inline fun dispatchInternal(block: Runnable, dispatch: () -> Unit) {\n+ /**\n+ * Tries to dispatch the given [block].\n+ * If there are not enough workers, it starts a new one via [startWorker].\n+ */\n+ private inline fun dispatchInternal(block: Runnable, startWorker: (Worker) -> Unit) {\n // Add task to queue so running workers will be able to see that\n- if (addAndTryDispatching(block)) return\n- /*\n- * Protect against the race when the number of workers is enough,\n- * but one (because of synchronized serialization) attempts to complete,\n- * and we just observed the number of running workers smaller than the actual\n- * number (hit right between `--runningWorkers` and `++runningWorkers` in `run()`)\n- */\n+ queue.addLast(block)\n+ if (runningWorkers.value >= parallelism) return\n+ // allocation may fail if some workers were launched in parallel or a worker temporarily decreased\n+ // `runningWorkers` when they observed an empty queue.\n if (!tryAllocateWorker()) return\n- dispatch()\n+ val task = obtainTaskOrDeallocateWorker() ?: return\n+ startWorker(Worker(task))\n }\n \n+ /**\n+ * Tries to obtain the permit to start a new worker.\n+ */\n private fun tryAllocateWorker(): Boolean {\n synchronized(workerAllocationLock) {\n if (runningWorkers.value >= parallelism) return false\n@@ -108,9 +83,49 @@ internal class LimitedDispatcher(\n }\n }\n \n- private fun addAndTryDispatching(block: Runnable): Boolean {\n- queue.addLast(block)\n- return runningWorkers.value >= parallelism\n+ /**\n+ * Obtains the next task from the queue, or logically deallocates the worker if the queue is empty.\n+ */\n+ private fun obtainTaskOrDeallocateWorker(): Runnable? {\n+ while (true) {\n+ when (val nextTask = queue.removeFirstOrNull()) {\n+ null -> synchronized(workerAllocationLock) {\n+ runningWorkers.decrementAndGet()\n+ if (queue.size == 0) return null\n+ runningWorkers.incrementAndGet()\n+ }\n+ else -> return nextTask\n+ }\n+ }\n+ }\n+\n+ /**\n+ * A worker that polls the queue and runs tasks until there are no more of them.\n+ *\n+ * It always stores the next task to run. This is done in order to prevent the possibility of the fairness\n+ * re-dispatch happening when there are no more tasks in the queue. This is important because, after all the\n+ * actual tasks are done, nothing prevents the user from closing the dispatcher and making it incorrect to\n+ * perform any more dispatches.\n+ */\n+ private inner class Worker(private var currentTask: Runnable) : Runnable {\n+ override fun run() {\n+ var fairnessCounter = 0\n+ while (true) {\n+ try {\n+ currentTask.run()\n+ } catch (e: Throwable) {\n+ handleCoroutineException(EmptyCoroutineContext, e)\n+ }\n+ currentTask = obtainTaskOrDeallocateWorker() ?: return\n+ // 16 is our out-of-thin-air constant to emulate fairness. Used in JS dispatchers as well\n+ if (++fairnessCounter >= 16 && dispatcher.isDispatchNeeded(this@LimitedDispatcher)) {\n+ // Do \"yield\" to let other views execute their runnable as well\n+ // Note that we do not decrement 'runningWorkers' as we are still committed to our part of work\n+ dispatcher.dispatch(this@LimitedDispatcher, this)\n+ return\n+ }\n+ }\n+ }\n }\n }\n \ndiff --git a/kotlinx-coroutines-core/common/src/internal/Synchronized.common.kt b/kotlinx-coroutines-core/common/src/internal/Synchronized.common.kt\nindex 059b234d8f..7107945a55 100644\n--- a/kotlinx-coroutines-core/common/src/internal/Synchronized.common.kt\n+++ b/kotlinx-coroutines-core/common/src/internal/Synchronized.common.kt\n@@ -5,6 +5,7 @@\n package kotlinx.coroutines.internal\n \n import kotlinx.coroutines.*\n+import kotlin.contracts.*\n \n /**\n * @suppress **This an internal API and should not be used from general code.**\n@@ -16,4 +17,16 @@ public expect open class SynchronizedObject() // marker abstract class\n * @suppress **This an internal API and should not be used from general code.**\n */\n @InternalCoroutinesApi\n-public expect inline fun synchronized(lock: SynchronizedObject, block: () -> T): T\n+public expect inline fun synchronizedImpl(lock: SynchronizedObject, block: () -> T): T\n+\n+/**\n+ * @suppress **This an internal API and should not be used from general code.**\n+ */\n+@OptIn(ExperimentalContracts::class)\n+@InternalCoroutinesApi\n+public inline fun synchronized(lock: SynchronizedObject, block: () -> T): T {\n+ contract {\n+ callsInPlace(block, InvocationKind.EXACTLY_ONCE)\n+ }\n+ return synchronizedImpl(lock, block)\n+}\ndiff --git a/kotlinx-coroutines-core/js/src/internal/Synchronized.kt b/kotlinx-coroutines-core/js/src/internal/Synchronized.kt\nindex dcbb20217d..05db52854f 100644\n--- a/kotlinx-coroutines-core/js/src/internal/Synchronized.kt\n+++ b/kotlinx-coroutines-core/js/src/internal/Synchronized.kt\n@@ -16,5 +16,4 @@ public actual typealias SynchronizedObject = Any\n * @suppress **This an internal API and should not be used from general code.**\n */\n @InternalCoroutinesApi\n-public actual inline fun synchronized(lock: SynchronizedObject, block: () -> T): T =\n- block()\n+public actual inline fun synchronizedImpl(lock: SynchronizedObject, block: () -> T): T = block()\ndiff --git a/kotlinx-coroutines-core/jvm/src/Executors.kt b/kotlinx-coroutines-core/jvm/src/Executors.kt\nindex 4e98e7bc98..121ba3f443 100644\n--- a/kotlinx-coroutines-core/jvm/src/Executors.kt\n+++ b/kotlinx-coroutines-core/jvm/src/Executors.kt\n@@ -108,7 +108,14 @@ public fun CoroutineDispatcher.asExecutor(): Executor =\n (this as? ExecutorCoroutineDispatcher)?.executor ?: DispatcherExecutor(this)\n \n private class DispatcherExecutor(@JvmField val dispatcher: CoroutineDispatcher) : Executor {\n- override fun execute(block: Runnable) = dispatcher.dispatch(EmptyCoroutineContext, block)\n+ override fun execute(block: Runnable) {\n+ if (dispatcher.isDispatchNeeded(EmptyCoroutineContext)) {\n+ dispatcher.dispatch(EmptyCoroutineContext, block)\n+ } else {\n+ block.run()\n+ }\n+ }\n+\n override fun toString(): String = dispatcher.toString()\n }\n \ndiff --git a/kotlinx-coroutines-core/jvm/src/internal/ResizableAtomicArray.kt b/kotlinx-coroutines-core/jvm/src/internal/ResizableAtomicArray.kt\nindex f949d9f5ea..6c98a9dad9 100644\n--- a/kotlinx-coroutines-core/jvm/src/internal/ResizableAtomicArray.kt\n+++ b/kotlinx-coroutines-core/jvm/src/internal/ResizableAtomicArray.kt\n@@ -28,11 +28,12 @@ internal class ResizableAtomicArray(initialLength: Int) {\n val curLen = curArray.length()\n if (index < curLen) {\n curArray[index] = value\n- } else {\n- val newArray = AtomicReferenceArray((index + 1).coerceAtLeast(2 * curLen))\n- for (i in 0 until curLen) newArray[i] = curArray[i]\n- newArray[index] = value\n- array = newArray // copy done\n+ return\n }\n+ // It would be nice to copy array in batch instead of 1 by 1, but it seems like Java has no API for that\n+ val newArray = AtomicReferenceArray((index + 1).coerceAtLeast(2 * curLen))\n+ for (i in 0 until curLen) newArray[i] = curArray[i]\n+ newArray[index] = value\n+ array = newArray // copy done\n }\n }\ndiff --git a/kotlinx-coroutines-core/jvm/src/internal/Synchronized.kt b/kotlinx-coroutines-core/jvm/src/internal/Synchronized.kt\nindex 6284f3a099..5b12faaf09 100644\n--- a/kotlinx-coroutines-core/jvm/src/internal/Synchronized.kt\n+++ b/kotlinx-coroutines-core/jvm/src/internal/Synchronized.kt\n@@ -16,5 +16,5 @@ public actual typealias SynchronizedObject = Any\n * @suppress **This an internal API and should not be used from general code.**\n */\n @InternalCoroutinesApi\n-public actual inline fun synchronized(lock: SynchronizedObject, block: () -> T): T =\n+public actual inline fun synchronizedImpl(lock: SynchronizedObject, block: () -> T): T =\n kotlin.synchronized(lock, block)\ndiff --git a/kotlinx-coroutines-core/jvm/src/scheduling/CoroutineScheduler.kt b/kotlinx-coroutines-core/jvm/src/scheduling/CoroutineScheduler.kt\nindex e08f3deedd..5ca3de5726 100644\n--- a/kotlinx-coroutines-core/jvm/src/scheduling/CoroutineScheduler.kt\n+++ b/kotlinx-coroutines-core/jvm/src/scheduling/CoroutineScheduler.kt\n@@ -252,22 +252,31 @@ internal class CoroutineScheduler(\n \n /**\n * State of worker threads.\n- * [workers] is array of lazily created workers up to [maxPoolSize] workers.\n+ * [workers] is a dynamic array of lazily created workers up to [maxPoolSize] workers.\n * [createdWorkers] is count of already created workers (worker with index lesser than [createdWorkers] exists).\n- * [blockingTasks] is count of pending (either in the queue or being executed) tasks\n+ * [blockingTasks] is count of pending (either in the queue or being executed) blocking tasks.\n+ *\n+ * Workers array is also used as a lock for workers' creation and termination sequence.\n *\n * **NOTE**: `workers[0]` is always `null` (never used, works as sentinel value), so\n * workers are 1-indexed, code path in [Worker.trySteal] is a bit faster and index swap during termination\n- * works properly\n+ * works properly.\n+ *\n+ * Initial size is `Dispatchers.Default` size * 2 to prevent unnecessary resizes for slightly or steadily loaded\n+ * applications.\n */\n @JvmField\n- val workers = ResizableAtomicArray(corePoolSize + 1)\n+ val workers = ResizableAtomicArray((corePoolSize + 1) * 2)\n \n /**\n * The `Long` value describing the state of workers in this pool.\n- * Currently includes created, CPU-acquired, and blocking workers, each occupying [BLOCKING_SHIFT] bits.\n+ * Currently, includes created, CPU-acquired, and blocking workers, each occupying [BLOCKING_SHIFT] bits.\n+ *\n+ * State layout (highest to lowest bits):\n+ * | --- number of cpu permits, 22 bits --- | --- number of blocking tasks, 21 bits --- | --- number of created threads, 21 bits --- |\n */\n private val controlState = atomic(corePoolSize.toLong() shl CPU_PERMITS_SHIFT)\n+\n private val createdWorkers: Int inline get() = (controlState.value and CREATED_MASK).toInt()\n private val availableCpuPermits: Int inline get() = availableCpuPermits(controlState.value)\n \n@@ -383,6 +392,10 @@ internal class CoroutineScheduler(\n fun dispatch(block: Runnable, taskContext: TaskContext = NonBlockingContext, tailDispatch: Boolean = false) {\n trackTask() // this is needed for virtual time support\n val task = createTask(block, taskContext)\n+ val isBlockingTask = task.isBlocking\n+ // Invariant: we increment counter **before** publishing the task\n+ // so executing thread can safely decrement the number of blocking tasks\n+ val stateSnapshot = if (isBlockingTask) incrementBlockingTasks() else 0\n // try to submit the task to the local queue and act depending on the result\n val currentWorker = currentWorker()\n val notAdded = currentWorker.submitToLocalQueue(task, tailDispatch)\n@@ -394,12 +407,12 @@ internal class CoroutineScheduler(\n }\n val skipUnpark = tailDispatch && currentWorker != null\n // Checking 'task' instead of 'notAdded' is completely okay\n- if (task.mode == TASK_NON_BLOCKING) {\n+ if (isBlockingTask) {\n+ // Use state snapshot to better estimate the number of running threads\n+ signalBlockingWork(stateSnapshot, skipUnpark = skipUnpark)\n+ } else {\n if (skipUnpark) return\n signalCpuWork()\n- } else {\n- // Increment blocking tasks anyway\n- signalBlockingWork(skipUnpark = skipUnpark)\n }\n }\n \n@@ -413,11 +426,11 @@ internal class CoroutineScheduler(\n return TaskImpl(block, nanoTime, taskContext)\n }\n \n- private fun signalBlockingWork(skipUnpark: Boolean) {\n- // Use state snapshot to avoid thread overprovision\n- val stateSnapshot = incrementBlockingTasks()\n+ // NB: should only be called from 'dispatch' method due to blocking tasks increment\n+ private fun signalBlockingWork(stateSnapshot: Long, skipUnpark: Boolean) {\n if (skipUnpark) return\n if (tryUnpark()) return\n+ // Use state snapshot to avoid accidental thread overprovision\n if (tryCreateWorker(stateSnapshot)) return\n tryUnpark() // Try unpark again in case there was race between permit release and parking\n }\n@@ -456,12 +469,13 @@ internal class CoroutineScheduler(\n }\n }\n \n- /*\n+ /**\n * Returns the number of CPU workers after this function (including new worker) or\n * 0 if no worker was created.\n */\n private fun createNewWorker(): Int {\n- synchronized(workers) {\n+ val worker: Worker\n+ return synchronized(workers) {\n // Make sure we're not trying to resurrect terminated scheduler\n if (isTerminated) return -1\n val state = controlState.value\n@@ -479,12 +493,11 @@ internal class CoroutineScheduler(\n * 2) Make it observable by increment created workers count\n * 3) Only then start the worker, otherwise it may miss its own creation\n */\n- val worker = Worker(newIndex)\n+ worker = Worker(newIndex)\n workers.setSynchronized(newIndex, worker)\n require(newIndex == incrementCreatedWorkers())\n- worker.start()\n- return cpuWorkers + 1\n- }\n+ cpuWorkers + 1\n+ }.also { worker.start() } // Start worker when the lock is released to reduce contention, see #3652\n }\n \n /**\ndiff --git a/kotlinx-coroutines-core/native/src/Debug.kt b/kotlinx-coroutines-core/native/src/Debug.kt\nindex f17c2ed7fc..e208addf88 100644\n--- a/kotlinx-coroutines-core/native/src/Debug.kt\n+++ b/kotlinx-coroutines-core/native/src/Debug.kt\n@@ -9,6 +9,7 @@ import kotlin.native.*\n \n internal actual val DEBUG: Boolean = false\n \n+@OptIn(ExperimentalStdlibApi::class)\n internal actual val Any.hexAddress: String get() = identityHashCode().toUInt().toString(16)\n \n internal actual val Any.classSimpleName: String get() = this::class.simpleName ?: \"Unknown\"\ndiff --git a/kotlinx-coroutines-core/native/src/internal/Synchronized.kt b/kotlinx-coroutines-core/native/src/internal/Synchronized.kt\nindex edbd3fde0c..8a8ecfe393 100644\n--- a/kotlinx-coroutines-core/native/src/internal/Synchronized.kt\n+++ b/kotlinx-coroutines-core/native/src/internal/Synchronized.kt\n@@ -17,4 +17,4 @@ public actual typealias SynchronizedObject = kotlinx.atomicfu.locks.Synchronized\n * @suppress **This an internal API and should not be used from general code.**\n */\n @InternalCoroutinesApi\n-public actual inline fun synchronized(lock: SynchronizedObject, block: () -> T): T = lock.withLock2(block)\n+public actual inline fun synchronizedImpl(lock: SynchronizedObject, block: () -> T): T = lock.withLock2(block)\ndiff --git a/kotlinx-coroutines-core/nativeDarwin/src/Dispatchers.kt b/kotlinx-coroutines-core/nativeDarwin/src/Dispatchers.kt\nindex a5588d853d..edc0a13ce8 100644\n--- a/kotlinx-coroutines-core/nativeDarwin/src/Dispatchers.kt\n+++ b/kotlinx-coroutines-core/nativeDarwin/src/Dispatchers.kt\n@@ -20,7 +20,7 @@ internal actual fun createDefaultDispatcher(): CoroutineDispatcher = DarwinGloba\n private object DarwinGlobalQueueDispatcher : CoroutineDispatcher() {\n override fun dispatch(context: CoroutineContext, block: Runnable) {\n autoreleasepool {\n- dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT.convert(), 0)) {\n+ dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT.convert(), 0u)) {\n block.run()\n }\n }\ndiff --git a/kotlinx-coroutines-debug/README.md b/kotlinx-coroutines-debug/README.md\nindex 24d0084be4..ff9ba9fffa 100644\n--- a/kotlinx-coroutines-debug/README.md\n+++ b/kotlinx-coroutines-debug/README.md\n@@ -61,7 +61,7 @@ stacktraces will be dumped to the console.\n ### Using as JVM agent\n \n Debug module can also be used as a standalone JVM agent to enable debug probes on the application startup.\n-You can run your application with an additional argument: `-javaagent:kotlinx-coroutines-debug-1.7.0-Beta.jar`.\n+You can run your application with an additional argument: `-javaagent:kotlinx-coroutines-debug-1.7.0-RC.jar`.\n Additionally, on Linux and Mac OS X you can use `kill -5 $pid` command in order to force your application to print all alive coroutines.\n When used as Java agent, `\"kotlinx.coroutines.debug.enable.creation.stack.trace\"` system property can be used to control \n [DebugProbes.enableCreationStackTraces] along with agent startup.\ndiff --git a/ui/coroutines-guide-ui.md b/ui/coroutines-guide-ui.md\nindex 127097e702..e00d74edee 100644\n--- a/ui/coroutines-guide-ui.md\n+++ b/ui/coroutines-guide-ui.md\n@@ -110,7 +110,7 @@ Add dependencies on `kotlinx-coroutines-android` module to the `dependencies { .\n `app/build.gradle` file:\n \n ```groovy\n-implementation \"org.jetbrains.kotlinx:kotlinx-coroutines-android:1.7.0-Beta\"\n+implementation \"org.jetbrains.kotlinx:kotlinx-coroutines-android:1.7.0-RC\"\n ```\n \n You can clone [kotlinx.coroutines](https://github.com/Kotlin/kotlinx.coroutines) project from GitHub onto your \n", "test_patch": "diff --git a/integration-testing/gradle.properties b/integration-testing/gradle.properties\nindex b8485eaeb2..4644d2346a 100644\n--- a/integration-testing/gradle.properties\n+++ b/integration-testing/gradle.properties\n@@ -1,5 +1,5 @@\n-kotlin_version=1.8.10\n-coroutines_version=1.7.0-Beta-SNAPSHOT\n+kotlin_version=1.8.20\n+coroutines_version=1.7.0-RC-SNAPSHOT\n asm_version=9.3\n \n kotlin.code.style=official\ndiff --git a/integration-testing/src/mavenTest/kotlin/MavenPublicationMetaInfValidator.kt b/integration-testing/src/mavenTest/kotlin/MavenPublicationMetaInfValidator.kt\nnew file mode 100644\nindex 0000000000..8ed2b823f7\n--- /dev/null\n+++ b/integration-testing/src/mavenTest/kotlin/MavenPublicationMetaInfValidator.kt\n@@ -0,0 +1,70 @@\n+/*\n+ * Copyright 2016-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.\n+ */\n+\n+package kotlinx.coroutines.validator\n+\n+import org.junit.Test\n+import org.objectweb.asm.*\n+import org.objectweb.asm.ClassReader.*\n+import org.objectweb.asm.ClassWriter.*\n+import org.objectweb.asm.Opcodes.*\n+import java.util.jar.*\n+import kotlin.test.*\n+\n+class MavenPublicationMetaInfValidator {\n+\n+ @Test\n+ fun testMetaInfCoreStructure() {\n+ val clazz = Class.forName(\"kotlinx.coroutines.Job\")\n+ JarFile(clazz.protectionDomain.codeSource.location.file).checkMetaInfStructure(\n+ setOf(\n+ \"MANIFEST.MF\",\n+ \"kotlinx-coroutines-core.kotlin_module\",\n+ \"com.android.tools/proguard/coroutines.pro\",\n+ \"com.android.tools/r8/coroutines.pro\",\n+ \"proguard/coroutines.pro\",\n+ \"versions/9/module-info.class\",\n+ \"kotlinx_coroutines_core.version\"\n+ )\n+ )\n+ }\n+\n+ @Test\n+ fun testMetaInfAndroidStructure() {\n+ val clazz = Class.forName(\"kotlinx.coroutines.android.HandlerDispatcher\")\n+ JarFile(clazz.protectionDomain.codeSource.location.file).checkMetaInfStructure(\n+ setOf(\n+ \"MANIFEST.MF\",\n+ \"kotlinx-coroutines-android.kotlin_module\",\n+ \"services/kotlinx.coroutines.CoroutineExceptionHandler\",\n+ \"services/kotlinx.coroutines.internal.MainDispatcherFactory\",\n+ \"com.android.tools/r8-from-1.6.0/coroutines.pro\",\n+ \"com.android.tools/r8-upto-3.0.0/coroutines.pro\",\n+ \"com.android.tools/proguard/coroutines.pro\",\n+ \"proguard/coroutines.pro\",\n+ \"versions/9/module-info.class\",\n+ \"kotlinx_coroutines_android.version\"\n+ )\n+ )\n+ }\n+\n+ private fun JarFile.checkMetaInfStructure(expected: Set) {\n+ val actual = HashSet()\n+ for (e in entries()) {\n+ if (e.isDirectory() || !e.realName.contains(\"META-INF\")) {\n+ continue\n+ }\n+ val partialName = e.realName.substringAfter(\"META-INF/\")\n+ actual.add(partialName)\n+ }\n+\n+ if (actual != expected) {\n+ val intersection = actual.intersect(expected)\n+ val mismatch = actual.subtract(intersection) + expected.subtract(intersection)\n+ fail(\"Mismatched files: \" + mismatch)\n+ }\n+\n+ close()\n+ }\n+}\ndiff --git a/kotlinx-coroutines-core/common/test/channels/BasicOperationsTest.kt b/kotlinx-coroutines-core/common/test/channels/BasicOperationsTest.kt\nindex aeb6199134..1f9b6fa739 100644\n--- a/kotlinx-coroutines-core/common/test/channels/BasicOperationsTest.kt\n+++ b/kotlinx-coroutines-core/common/test/channels/BasicOperationsTest.kt\n@@ -85,6 +85,45 @@ class BasicOperationsTest : TestBase() {\n }\n }\n \n+ @Test\n+ fun testCancelledChannelInvokeOnClose() {\n+ val ch = Channel()\n+ ch.invokeOnClose { assertIs(it) }\n+ ch.cancel()\n+ }\n+\n+ @Test\n+ fun testCancelledChannelWithCauseInvokeOnClose() {\n+ val ch = Channel()\n+ ch.invokeOnClose { assertIs(it) }\n+ ch.cancel(TimeoutCancellationException(\"\"))\n+ }\n+\n+ @Test\n+ fun testThrowingInvokeOnClose() = runTest {\n+ val channel = Channel()\n+ channel.invokeOnClose {\n+ assertNull(it)\n+ expect(3)\n+ throw TestException()\n+ }\n+\n+ launch {\n+ try {\n+ expect(2)\n+ channel.close()\n+ } catch (e: TestException) {\n+ expect(4)\n+ }\n+ }\n+ expect(1)\n+ yield()\n+ assertTrue(channel.isClosedForReceive)\n+ assertTrue(channel.isClosedForSend)\n+ assertFalse(channel.close())\n+ finish(5)\n+ }\n+\n @Suppress(\"ReplaceAssertBooleanWithAssertEquality\")\n private suspend fun testReceiveCatching(kind: TestChannelKind) = coroutineScope {\n reset()\n@@ -124,7 +163,7 @@ class BasicOperationsTest : TestBase() {\n channel.trySend(2)\n .onSuccess { expectUnreached() }\n .onClosed {\n- assertTrue { it is ClosedSendChannelException}\n+ assertTrue { it is ClosedSendChannelException }\n if (!kind.isConflated) {\n assertEquals(42, channel.receive())\n }\ndiff --git a/kotlinx-coroutines-core/common/test/flow/operators/LintTest.kt b/kotlinx-coroutines-core/common/test/flow/operators/LintTest.kt\nnew file mode 100644\nindex 0000000000..9cf6cbb958\n--- /dev/null\n+++ b/kotlinx-coroutines-core/common/test/flow/operators/LintTest.kt\n@@ -0,0 +1,31 @@\n+/*\n+ * Copyright 2016-2023 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.\n+ */\n+\n+package kotlinx.coroutines.flow.operators\n+\n+import kotlinx.coroutines.*\n+import kotlinx.coroutines.flow.*\n+import kotlin.test.*\n+\n+class LintTest: TestBase() {\n+ /**\n+ * Tests that using [SharedFlow.toList] and similar functions by passing a mutable collection does add values\n+ * to the provided collection.\n+ */\n+ @Test\n+ fun testSharedFlowToCollection() = runTest {\n+ val sharedFlow = MutableSharedFlow()\n+ val list = mutableListOf()\n+ val set = mutableSetOf()\n+ val jobs = listOf(suspend { sharedFlow.toList(list) }, { sharedFlow.toSet(set) }).map {\n+ launch(Dispatchers.Unconfined) { it() }\n+ }\n+ repeat(10) {\n+ sharedFlow.emit(it)\n+ }\n+ jobs.forEach { it.cancelAndJoin() }\n+ assertEquals((0..9).toList(), list)\n+ assertEquals((0..9).toSet(), set)\n+ }\n+}\ndiff --git a/kotlinx-coroutines-core/concurrent/test/LimitedParallelismConcurrentTest.kt b/kotlinx-coroutines-core/concurrent/test/LimitedParallelismConcurrentTest.kt\nindex 7d82a67baf..49fe93f608 100644\n--- a/kotlinx-coroutines-core/concurrent/test/LimitedParallelismConcurrentTest.kt\n+++ b/kotlinx-coroutines-core/concurrent/test/LimitedParallelismConcurrentTest.kt\n@@ -7,6 +7,7 @@ package kotlinx.coroutines\n import kotlinx.atomicfu.*\n import kotlinx.coroutines.*\n import kotlinx.coroutines.exceptions.*\n+import kotlin.coroutines.*\n import kotlin.test.*\n \n class LimitedParallelismConcurrentTest : TestBase() {\n@@ -58,4 +59,37 @@ class LimitedParallelismConcurrentTest : TestBase() {\n joinAll(j1, j2)\n executor.close()\n }\n+\n+ /**\n+ * Tests that, when no tasks are present, the limited dispatcher does not dispatch any tasks.\n+ * This is important for the case when a dispatcher is closeable and the [CoroutineDispatcher.limitedParallelism]\n+ * machinery could trigger a dispatch after the dispatcher is closed.\n+ */\n+ @Test\n+ fun testNotDoingDispatchesWhenNoTasksArePresent() = runTest {\n+ class NaggingDispatcher: CoroutineDispatcher() {\n+ val closed = atomic(false)\n+ override fun dispatch(context: CoroutineContext, block: Runnable) {\n+ if (closed.value)\n+ fail(\"Dispatcher was closed, but still dispatched a task\")\n+ Dispatchers.Default.dispatch(context, block)\n+ }\n+ fun close() {\n+ closed.value = true\n+ }\n+ }\n+ repeat(stressTestMultiplier * 500_000) {\n+ val dispatcher = NaggingDispatcher()\n+ val view = dispatcher.limitedParallelism(1)\n+ val deferred = CompletableDeferred()\n+ val job = launch(view) {\n+ deferred.await()\n+ }\n+ launch(Dispatchers.Default) {\n+ deferred.complete(Unit)\n+ }\n+ job.join()\n+ dispatcher.close()\n+ }\n+ }\n }\ndiff --git a/kotlinx-coroutines-core/jvm/test/ExecutorsTest.kt b/kotlinx-coroutines-core/jvm/test/ExecutorsTest.kt\nindex ebf08a03d0..6e5b18f7e9 100644\n--- a/kotlinx-coroutines-core/jvm/test/ExecutorsTest.kt\n+++ b/kotlinx-coroutines-core/jvm/test/ExecutorsTest.kt\n@@ -81,6 +81,22 @@ class ExecutorsTest : TestBase() {\n finish(4)\n }\n \n+ @Test\n+ fun testCustomDispatcherToExecutorDispatchNotNeeded() {\n+ expect(1)\n+ val dispatcher = object : CoroutineDispatcher() {\n+ override fun isDispatchNeeded(context: CoroutineContext) = false\n+\n+ override fun dispatch(context: CoroutineContext, block: Runnable) {\n+ fail(\"should not dispatch\")\n+ }\n+ }\n+ dispatcher.asExecutor().execute {\n+ expect(2)\n+ }\n+ finish(3)\n+ }\n+\n @Test\n fun testTwoThreads() {\n val ctx1 = newSingleThreadContext(\"Ctx1\")\n@@ -106,4 +122,4 @@ class ExecutorsTest : TestBase() {\n dispatcher.close()\n check(executorService.isShutdown)\n }\n-}\n\\ No newline at end of file\n+}\ndiff --git a/kotlinx-coroutines-core/jvm/test/TestBase.kt b/kotlinx-coroutines-core/jvm/test/TestBase.kt\nindex 6a013fa1da..f9e5466b44 100644\n--- a/kotlinx-coroutines-core/jvm/test/TestBase.kt\n+++ b/kotlinx-coroutines-core/jvm/test/TestBase.kt\n@@ -97,10 +97,10 @@ public actual open class TestBase(private var disableOutCheck: Boolean) {\n \n private fun printError(message: String, cause: Throwable) {\n setError(cause)\n- println(\"$message: $cause\")\n- cause.printStackTrace(System.out)\n- println(\"--- Detected at ---\")\n- Throwable().printStackTrace(System.out)\n+ System.err.println(\"$message: $cause\")\n+ cause.printStackTrace(System.err)\n+ System.err.println(\"--- Detected at ---\")\n+ Throwable().printStackTrace(System.err)\n }\n \n /**\ndiff --git a/kotlinx-coroutines-core/jvm/test/scheduling/CoroutineSchedulerInternalApiStressTest.kt b/kotlinx-coroutines-core/jvm/test/scheduling/CoroutineSchedulerInternalApiStressTest.kt\nindex 22b9b02916..2ec714ffb6 100644\n--- a/kotlinx-coroutines-core/jvm/test/scheduling/CoroutineSchedulerInternalApiStressTest.kt\n+++ b/kotlinx-coroutines-core/jvm/test/scheduling/CoroutineSchedulerInternalApiStressTest.kt\n@@ -80,8 +80,8 @@ class CoroutineSchedulerInternalApiStressTest : TestBase() {\n }\n }\n completionLatch.countDown()\n-// assertEquals(100, timesHelped)\n-// assertTrue(Thread.currentThread() in observedDefaultThreads, observedDefaultThreads.toString())\n+ assertEquals(100, timesHelped)\n+ assertTrue(Thread.currentThread() in observedDefaultThreads, observedDefaultThreads.toString())\n }\n }\n }\ndiff --git a/kotlinx-coroutines-test/README.md b/kotlinx-coroutines-test/README.md\nindex 2bdf1d8216..f2805086bb 100644\n--- a/kotlinx-coroutines-test/README.md\n+++ b/kotlinx-coroutines-test/README.md\n@@ -26,7 +26,7 @@ Provided [TestDispatcher] implementations:\n Add `kotlinx-coroutines-test` to your project test dependencies:\n ```\n dependencies {\n- testImplementation 'org.jetbrains.kotlinx:kotlinx-coroutines-test:1.7.0-Beta'\n+ testImplementation 'org.jetbrains.kotlinx:kotlinx-coroutines-test:1.7.0-RC'\n }\n ```\n \ndiff --git a/kotlinx-coroutines-test/api/kotlinx-coroutines-test.api b/kotlinx-coroutines-test/api/kotlinx-coroutines-test.api\nindex bcee73e12e..00d9fb659e 100644\n--- a/kotlinx-coroutines-test/api/kotlinx-coroutines-test.api\n+++ b/kotlinx-coroutines-test/api/kotlinx-coroutines-test.api\n@@ -22,6 +22,7 @@ public final class kotlinx/coroutines/test/TestBuildersKt {\n \tpublic static final fun runTest (Lkotlinx/coroutines/test/TestScope;JLkotlin/jvm/functions/Function2;)V\n \tpublic static synthetic fun runTest$default (Lkotlin/coroutines/CoroutineContext;JLkotlin/jvm/functions/Function2;ILjava/lang/Object;)V\n \tpublic static synthetic fun runTest$default (Lkotlinx/coroutines/test/TestCoroutineScope;JLkotlin/jvm/functions/Function2;ILjava/lang/Object;)V\n+\tpublic static final synthetic fun runTest$default (Lkotlinx/coroutines/test/TestScope;Ljava/lang/Long;Lkotlin/jvm/functions/Function2;Ljava/lang/Integer;Ljava/lang/Object;)V\n \tpublic static final fun runTest-8Mi8wO0 (Lkotlin/coroutines/CoroutineContext;JLkotlin/jvm/functions/Function2;)V\n \tpublic static final fun runTest-8Mi8wO0 (Lkotlinx/coroutines/test/TestScope;JLkotlin/jvm/functions/Function2;)V\n \tpublic static synthetic fun runTest-8Mi8wO0$default (Lkotlin/coroutines/CoroutineContext;JLkotlin/jvm/functions/Function2;ILjava/lang/Object;)V\ndiff --git a/kotlinx-coroutines-test/common/src/TestBuilders.kt b/kotlinx-coroutines-test/common/src/TestBuilders.kt\nindex 15cd1fba4a..8ae075a706 100644\n--- a/kotlinx-coroutines-test/common/src/TestBuilders.kt\n+++ b/kotlinx-coroutines-test/common/src/TestBuilders.kt\n@@ -570,3 +570,16 @@ internal fun throwAll(head: Throwable?, other: List) {\n }\n \n internal expect fun dumpCoroutines()\n+\n+@Deprecated(\n+ \"This is for binary compatibility with the `runTest` overload that existed at some point\",\n+ level = DeprecationLevel.HIDDEN\n+)\n+@JvmName(\"runTest\\$default\")\n+@Suppress(\"DEPRECATION\", \"UNUSED_PARAMETER\")\n+public fun TestScope.runTestLegacy(\n+ dispatchTimeoutMs: Long?,\n+ testBody: suspend TestScope.() -> Unit,\n+ unused1: Int?,\n+ unused2: Any?,\n+): TestResult = runTest(dispatchTimeoutMs ?: 60_000, testBody)\n", "problem_statement": "`SharedFlow.toList(mutableList)`: difference behavior between 1.6.4 vs 1.7.0-Beta\nSometimes, I use this method to write simple test on SharedFlow.\nVersion 1.6.4 works well.\nSince 1.7.0-Beta, this method is deprecated and the implementation seem be wrong\n\n```kotlin\nval acc = MutableList()\nval job = scope.launch(start = Undispatched) {\n sharedFlow.toList(acc)\n}\n\n// later...\n\njob.cancel()\nassertContentEquals(\n expected = ...,\n actual = acc\n)\n```\n\nIMO, the correct impl. is `SharedFlow.toList(acc) = (this as Flow).toList(acc)`\n", "hints_text": "", "created_at": "2023-04-18T15:06:11Z", "version": "1.7", "FAIL_TO_PASS": [ "gradle_test_execution" ], "PASS_TO_PASS": [], "ERROR_TO_PASS": [], "environment_setup_commit": "26fab9459955d246c16a8609195526cea7dc6f1e" }, { "repo": "Kotlin/kotlinx.coroutines", "pull_number": 4076, "instance_id": "Kotlin__kotlinx.coroutines-4076", "issue_numbers": [ "4071" ], "base_commit": "db1e6af39fb31d14a2f6d911eb7747b901ccc2fc", "patch": "diff --git a/kotlinx-coroutines-core/common/src/flow/operators/Delay.kt b/kotlinx-coroutines-core/common/src/flow/operators/Delay.kt\nindex cad34a0d55..2a701c0c12 100644\n--- a/kotlinx-coroutines-core/common/src/flow/operators/Delay.kt\n+++ b/kotlinx-coroutines-core/common/src/flow/operators/Delay.kt\n@@ -394,6 +394,7 @@ private fun Flow.timeoutInternal(\n value.onSuccess {\n downStream.emit(it)\n }.onClosed {\n+ it?.let { throw it }\n return@onReceiveCatching false\n }\n return@onReceiveCatching true\n", "test_patch": "diff --git a/kotlinx-coroutines-core/common/test/flow/operators/TimeoutTest.kt b/kotlinx-coroutines-core/common/test/flow/operators/TimeoutTest.kt\nindex a2ca101ef0..0162a216c3 100644\n--- a/kotlinx-coroutines-core/common/test/flow/operators/TimeoutTest.kt\n+++ b/kotlinx-coroutines-core/common/test/flow/operators/TimeoutTest.kt\n@@ -237,6 +237,17 @@ class TimeoutTest : TestBase() {\n testImmediateTimeout(-1.seconds)\n }\n \n+ @Test\n+ fun testClosing() = runTest {\n+ assertFailsWith {\n+ channelFlow { close(TestException()) }\n+ .timeout(Duration.INFINITE)\n+ .collect {\n+ expectUnreached()\n+ }\n+ }\n+ }\n+\n private fun testImmediateTimeout(timeout: Duration) {\n expect(1)\n val flow = emptyFlow().timeout(timeout)\n", "problem_statement": "Callbackflow close exception misbehavior with timeout\n**Describe the bug**\r\n\r\nWhen `callbackflow` is chained with `timeout` directly, and closed with an exception, the exception won't be sent to downstream. \r\n\r\n Coroutines version 1.8.0. Kotlin version 1.9.21.\r\n\r\n**Provide a Reproducer**\r\n\r\n```\r\nval flow = callbackFlow {\r\n close(IllegalStateException(\"Test Exception\"))\r\n}.timeout(5.seconds)\r\ntry {\r\n flow.collect()\r\n} catch (e: Exception) {\r\n println(\"exception got: $e\")\r\n}\r\n```\r\nI expect this to print:\r\n`exception got: java.lang.IllegalStateException: Test Exception`\r\n\r\nBut no exception is caught.\r\n\r\nHowever, if I add any operator between callbackflow and timeout, it works as expected, \r\n```\r\nval flow = callbackFlow {\r\n close(IllegalStateException(\"Test Exception\"))\r\n}.catch{throw it}.timeout(5.seconds)\r\ntry {\r\n flow.collect()\r\n} catch (e: Exception) {\r\n println(\"exception got: $e\")\r\n}\r\n```\r\n\n", "hints_text": "", "created_at": "2024-03-25T13:27:37Z", "version": "1.8", "FAIL_TO_PASS": [ "gradle_test_execution" ], "PASS_TO_PASS": [], "ERROR_TO_PASS": [], "environment_setup_commit": "cd696d3f8f4afdbc735915c2bded974616331b55" }, { "repo": "Kotlin/kotlinx.coroutines", "pull_number": 4072, "instance_id": "Kotlin__kotlinx.coroutines-4072", "issue_numbers": [ "4071" ], "base_commit": "60d2fe8471ce4d289d526f04b51389b06b1c064f", "patch": "diff --git a/kotlinx-coroutines-core/common/src/flow/operators/Delay.kt b/kotlinx-coroutines-core/common/src/flow/operators/Delay.kt\nindex cad34a0d55..2a701c0c12 100644\n--- a/kotlinx-coroutines-core/common/src/flow/operators/Delay.kt\n+++ b/kotlinx-coroutines-core/common/src/flow/operators/Delay.kt\n@@ -394,6 +394,7 @@ private fun Flow.timeoutInternal(\n value.onSuccess {\n downStream.emit(it)\n }.onClosed {\n+ it?.let { throw it }\n return@onReceiveCatching false\n }\n return@onReceiveCatching true\n", "test_patch": "diff --git a/kotlinx-coroutines-core/common/test/flow/operators/TimeoutTest.kt b/kotlinx-coroutines-core/common/test/flow/operators/TimeoutTest.kt\nindex a2ca101ef0..0162a216c3 100644\n--- a/kotlinx-coroutines-core/common/test/flow/operators/TimeoutTest.kt\n+++ b/kotlinx-coroutines-core/common/test/flow/operators/TimeoutTest.kt\n@@ -237,6 +237,17 @@ class TimeoutTest : TestBase() {\n testImmediateTimeout(-1.seconds)\n }\n \n+ @Test\n+ fun testClosing() = runTest {\n+ assertFailsWith {\n+ channelFlow { close(TestException()) }\n+ .timeout(Duration.INFINITE)\n+ .collect {\n+ expectUnreached()\n+ }\n+ }\n+ }\n+\n private fun testImmediateTimeout(timeout: Duration) {\n expect(1)\n val flow = emptyFlow().timeout(timeout)\n", "problem_statement": "Callbackflow close exception misbehavior with timeout\n**Describe the bug**\r\n\r\nWhen `callbackflow` is chained with `timeout` directly, and closed with an exception, the exception won't be sent to downstream. \r\n\r\n Coroutines version 1.8.0. Kotlin version 1.9.21.\r\n\r\n**Provide a Reproducer**\r\n\r\n```\r\nval flow = callbackFlow {\r\n close(IllegalStateException(\"Test Exception\"))\r\n}.timeout(5.seconds)\r\ntry {\r\n flow.collect()\r\n} catch (e: Exception) {\r\n println(\"exception got: $e\")\r\n}\r\n```\r\nI expect this to print:\r\n`exception got: java.lang.IllegalStateException: Test Exception`\r\n\r\nBut no exception is caught.\r\n\r\nHowever, if I add any operator between callbackflow and timeout, it works as expected, \r\n```\r\nval flow = callbackFlow {\r\n close(IllegalStateException(\"Test Exception\"))\r\n}.catch{throw it}.timeout(5.seconds)\r\ntry {\r\n flow.collect()\r\n} catch (e: Exception) {\r\n println(\"exception got: $e\")\r\n}\r\n```\r\n\n", "hints_text": "", "created_at": "2024-03-18T14:08:59Z", "version": "1.8", "FAIL_TO_PASS": [ "gradle_test_execution" ], "PASS_TO_PASS": [], "ERROR_TO_PASS": [], "environment_setup_commit": "cd696d3f8f4afdbc735915c2bded974616331b55" }, { "repo": "Kotlin/kotlinx.coroutines", "pull_number": 4272, "instance_id": "Kotlin__kotlinx.coroutines-4272", "issue_numbers": [ "4142" ], "base_commit": "3ed623a5706ac6f4a3bc191150e3ff5caa86eba3", "patch": "diff --git a/kotlinx-coroutines-core/common/src/intrinsics/Undispatched.kt b/kotlinx-coroutines-core/common/src/intrinsics/Undispatched.kt\nindex 511199701a..bb81d442d4 100644\n--- a/kotlinx-coroutines-core/common/src/intrinsics/Undispatched.kt\n+++ b/kotlinx-coroutines-core/common/src/intrinsics/Undispatched.kt\n@@ -38,43 +38,46 @@ internal fun (suspend (R) -> T).startCoroutineUndispatched(receiver: R, c\n *\n * It starts the coroutine using [startCoroutineUninterceptedOrReturn].\n */\n-internal fun ScopeCoroutine.startUndispatchedOrReturn(receiver: R, block: suspend R.() -> T): Any? {\n- return undispatchedResult({ true }) {\n- block.startCoroutineUninterceptedOrReturn(receiver, this)\n- }\n-}\n+internal fun ScopeCoroutine.startUndispatchedOrReturn(\n+ receiver: R, block: suspend R.() -> T\n+): Any? = startUndspatched(alwaysRethrow = true, receiver, block)\n \n /**\n * Same as [startUndispatchedOrReturn], but ignores [TimeoutCancellationException] on fast-path.\n */\n internal fun ScopeCoroutine.startUndispatchedOrReturnIgnoreTimeout(\n receiver: R, block: suspend R.() -> T\n-): Any? {\n- return undispatchedResult({ e -> !(e is TimeoutCancellationException && e.coroutine === this) }) {\n- block.startCoroutineUninterceptedOrReturn(receiver, this)\n- }\n-}\n+): Any? = startUndspatched(alwaysRethrow = false, receiver, block)\n \n-private inline fun ScopeCoroutine.undispatchedResult(\n- shouldThrow: (Throwable) -> Boolean,\n- startBlock: () -> Any?\n+/**\n+ * Starts and handles the result of an undispatched coroutine, potentially with children.\n+ * For example, it handles `coroutineScope { ...suspend of throw, maybe start children... }`\n+ * and `launch(start = UNDISPATCHED) { ... }`\n+ *\n+ * @param alwaysRethrow specifies whether an exception should be unconditioanlly rethrown.\n+ * It is a tweak for 'withTimeout' in order to successfully return values when the block was cancelled:\n+ * i.e. `withTimeout(1ms) { Thread.sleep(1000); 42 }` should not fail.\n+ */\n+private fun ScopeCoroutine.startUndspatched(\n+ alwaysRethrow: Boolean,\n+ receiver: R, block: suspend R.() -> T\n ): Any? {\n val result = try {\n- startBlock()\n+ block.startCoroutineUninterceptedOrReturn(receiver, this)\n+ } catch (e: DispatchException) {\n+ // Special codepath for failing CoroutineDispatcher: rethrow an exception\n+ // immediately without waiting for children to indicate something is wrong\n+ dispatchExceptionAndMakeCompleting(e)\n } catch (e: Throwable) {\n CompletedExceptionally(e)\n }\n+\n /*\n- * We're trying to complete our undispatched block here and have three code-paths:\n- * (1) Coroutine is suspended.\n- * Otherwise, coroutine had returned result, so we are completing our block (and its job).\n- * (2) If we can't complete it or started waiting for children, we suspend.\n- * (3) If we have successfully completed the coroutine state machine here,\n- * then we take the actual final state of the coroutine from makeCompletingOnce and return it.\n- *\n- * shouldThrow parameter is a special code path for timeout coroutine:\n- * If timeout is exceeded, but withTimeout() block was not suspended, we would like to return block value,\n- * not a timeout exception.\n+ * We are trying to complete our undispatched block with the following possible codepaths:\n+ * 1) The coroutine just suspended. I.e. `coroutineScope { .. suspend here }`.\n+ * Then just suspend\n+ * 2) The coroutine completed with something, but has active children. Wait for them, also suspend\n+ * 3) The coroutine succesfully completed. Return or rethrow its result.\n */\n if (result === COROUTINE_SUSPENDED) return COROUTINE_SUSPENDED // (1)\n val state = makeCompletingOnce(result)\n@@ -82,7 +85,7 @@ private inline fun ScopeCoroutine.undispatchedResult(\n afterCompletionUndispatched()\n return if (state is CompletedExceptionally) { // (3)\n when {\n- shouldThrow(state.cause) -> throw recoverStackTrace(state.cause, uCont)\n+ alwaysRethrow || notOwnTimeout(state.cause) -> throw recoverStackTrace(state.cause, uCont)\n result is CompletedExceptionally -> throw recoverStackTrace(result.cause, uCont)\n else -> result\n }\n@@ -90,3 +93,12 @@ private inline fun ScopeCoroutine.undispatchedResult(\n state.unboxState()\n }\n }\n+\n+private fun ScopeCoroutine<*>.notOwnTimeout(cause: Throwable): Boolean {\n+ return cause !is TimeoutCancellationException || cause.coroutine !== this\n+}\n+\n+private fun ScopeCoroutine<*>.dispatchExceptionAndMakeCompleting(e: DispatchException): Nothing {\n+ makeCompleting(CompletedExceptionally(e.cause))\n+ throw recoverStackTrace(e.cause, uCont)\n+}\n", "test_patch": "diff --git a/kotlinx-coroutines-core/common/test/ExperimentalDispatchModeTest.kt b/kotlinx-coroutines-core/common/test/UnconfinedCancellationTest.kt\nsimilarity index 97%\nrename from kotlinx-coroutines-core/common/test/ExperimentalDispatchModeTest.kt\nrename to kotlinx-coroutines-core/common/test/UnconfinedCancellationTest.kt\nindex 98c5e66727..59845d841b 100644\n--- a/kotlinx-coroutines-core/common/test/ExperimentalDispatchModeTest.kt\n+++ b/kotlinx-coroutines-core/common/test/UnconfinedCancellationTest.kt\n@@ -3,7 +3,7 @@ package kotlinx.coroutines\n import kotlinx.coroutines.testing.*\n import kotlin.test.*\n \n-class ExperimentalDispatchModeTest : TestBase() {\n+class UnconfinedCancellationTest : TestBase() {\n @Test\n fun testUnconfinedCancellation() = runTest {\n val parent = Job()\ndiff --git a/kotlinx-coroutines-core/jvm/test/FailFastOnStartTest.kt b/kotlinx-coroutines-core/jvm/test/FailFastOnStartTest.kt\nindex ae3c503d60..022fb6b630 100644\n--- a/kotlinx-coroutines-core/jvm/test/FailFastOnStartTest.kt\n+++ b/kotlinx-coroutines-core/jvm/test/FailFastOnStartTest.kt\n@@ -4,9 +4,15 @@ package kotlinx.coroutines\n \n import kotlinx.coroutines.testing.*\n import kotlinx.coroutines.channels.*\n+import kotlinx.coroutines.flow.emptyFlow\n+import kotlinx.coroutines.flow.flow\n+import kotlinx.coroutines.flow.flowOn\n import org.junit.*\n import org.junit.Test\n import org.junit.rules.*\n+import kotlin.coroutines.Continuation\n+import kotlin.coroutines.EmptyCoroutineContext\n+import kotlin.coroutines.startCoroutine\n import kotlin.test.*\n \n class FailFastOnStartTest : TestBase() {\n@@ -81,4 +87,24 @@ class FailFastOnStartTest : TestBase() {\n fun testAsyncNonChild() = runTest(expected = ::mainException) {\n async(Job() + Dispatchers.Main) { fail() }\n }\n+\n+ @Test\n+ fun testFlowOn() {\n+ // See #4142, this test ensures that `coroutineScope { produce(failingDispatcher, ATOMIC) }`\n+ // rethrows an exception. It does not help with the completion of such a coroutine though.\n+ // `suspend {}` + start coroutine with custom `completion` to avoid waiting for test completion\n+ expect(1)\n+ val caller = suspend {\n+ try {\n+ emptyFlow().flowOn(Dispatchers.Main).collect { fail() }\n+ } catch (e: Throwable) {\n+ assertTrue(mainException(e))\n+ expect(2)\n+ }\n+ }\n+\n+ caller.startCoroutine(Continuation(EmptyCoroutineContext) {\n+ finish(3)\n+ })\n+ }\n }\n", "problem_statement": "Flow collection silently hangs when dispatcher throws an exception\nSteps to reproduce:\r\n```\r\n flowOf(1, 2, 3)\r\n .flowOn(Dispatchers.Main.immediate) // Should be not present in the classpath\r\n .collect {\r\n println(\"collect: $it\")\r\n }\r\n```\r\n\r\nOriginal report: https://github.com/JetBrains/compose-multiplatform/issues/4835\n", "hints_text": "", "created_at": "2024-11-11T11:58:59Z", "version": "1.10", "FAIL_TO_PASS": [ "gradle_test_execution" ], "PASS_TO_PASS": [], "ERROR_TO_PASS": [], "environment_setup_commit": "33b18cda35f302992aaff438b690f0a9b6664d72" }, { "repo": "Kotlin/kotlinx.coroutines", "pull_number": 4038, "instance_id": "Kotlin__kotlinx.coroutines-4038", "issue_numbers": [ "4035" ], "base_commit": "761bdebfdcfa02de4755d8321e7916cb96d20da1", "patch": "diff --git a/kotlinx-coroutines-core/common/src/flow/internal/Combine.kt b/kotlinx-coroutines-core/common/src/flow/internal/Combine.kt\nindex eb82426760..60fcc8e04c 100644\n--- a/kotlinx-coroutines-core/common/src/flow/internal/Combine.kt\n+++ b/kotlinx-coroutines-core/common/src/flow/internal/Combine.kt\n@@ -102,7 +102,7 @@ internal fun zipImpl(flow: Flow, flow2: Flow, transform: sus\n val collectJob = Job()\n (second as SendChannel<*>).invokeOnClose {\n // Optimization to avoid AFE allocation when the other flow is done\n- if (collectJob.isActive) collectJob.cancel(AbortFlowException(this@unsafeFlow))\n+ if (collectJob.isActive) collectJob.cancel(AbortFlowException(collectJob))\n }\n \n try {\n@@ -124,14 +124,14 @@ internal fun zipImpl(flow: Flow, flow2: Flow, transform: sus\n flow.collect { value ->\n withContextUndispatched(scopeContext, Unit, cnt) {\n val otherValue = second.receiveCatching().getOrElse {\n- throw it ?:AbortFlowException(this@unsafeFlow)\n+ throw it ?: AbortFlowException(collectJob)\n }\n emit(transform(value, NULL.unbox(otherValue)))\n }\n }\n }\n } catch (e: AbortFlowException) {\n- e.checkOwnership(owner = this@unsafeFlow)\n+ e.checkOwnership(owner = collectJob)\n } finally {\n second.cancel()\n }\ndiff --git a/kotlinx-coroutines-core/common/src/flow/internal/FlowExceptions.common.kt b/kotlinx-coroutines-core/common/src/flow/internal/FlowExceptions.common.kt\nindex 999e117e7c..628296c3e2 100644\n--- a/kotlinx-coroutines-core/common/src/flow/internal/FlowExceptions.common.kt\n+++ b/kotlinx-coroutines-core/common/src/flow/internal/FlowExceptions.common.kt\n@@ -4,16 +4,17 @@ import kotlinx.coroutines.*\n import kotlinx.coroutines.flow.*\n \n /**\n- * This exception is thrown when operator need no more elements from the flow.\n- * This exception should never escape outside of operator's implementation.\n+ * This exception is thrown when an operator needs no more elements from the flow.\n+ * The operator should never allow this exception to be thrown past its own boundary.\n * This exception can be safely ignored by non-terminal flow operator if and only if it was caught by its owner\n * (see usages of [checkOwnership]).\n+ * Therefore, the [owner] parameter must be unique for every invocation of every operator.\n */\n-internal expect class AbortFlowException(owner: FlowCollector<*>) : CancellationException {\n- public val owner: FlowCollector<*>\n+internal expect class AbortFlowException(owner: Any) : CancellationException {\n+ val owner: Any\n }\n \n-internal fun AbortFlowException.checkOwnership(owner: FlowCollector<*>) {\n+internal fun AbortFlowException.checkOwnership(owner: Any) {\n if (this.owner !== owner) throw this\n }\n \ndiff --git a/kotlinx-coroutines-core/common/src/flow/operators/Limit.kt b/kotlinx-coroutines-core/common/src/flow/operators/Limit.kt\nindex 3d489aa946..d40a92d00b 100644\n--- a/kotlinx-coroutines-core/common/src/flow/operators/Limit.kt\n+++ b/kotlinx-coroutines-core/common/src/flow/operators/Limit.kt\n@@ -46,6 +46,7 @@ public fun Flow.dropWhile(predicate: suspend (T) -> Boolean): Flow = f\n public fun Flow.take(count: Int): Flow {\n require(count > 0) { \"Requested element count $count should be positive\" }\n return flow {\n+ val ownershipMarker = Any()\n var consumed = 0\n try {\n collect { value ->\n@@ -56,18 +57,18 @@ public fun Flow.take(count: Int): Flow {\n if (++consumed < count) {\n return@collect emit(value)\n } else {\n- return@collect emitAbort(value)\n+ return@collect emitAbort(value, ownershipMarker)\n }\n }\n } catch (e: AbortFlowException) {\n- e.checkOwnership(owner = this)\n+ e.checkOwnership(owner = ownershipMarker)\n }\n }\n }\n \n-private suspend fun FlowCollector.emitAbort(value: T) {\n+private suspend fun FlowCollector.emitAbort(value: T, ownershipMarker: Any) {\n emit(value)\n- throw AbortFlowException(this)\n+ throw AbortFlowException(ownershipMarker)\n }\n \n /**\ndiff --git a/kotlinx-coroutines-core/jsAndWasmShared/src/flow/internal/FlowExceptions.kt b/kotlinx-coroutines-core/jsAndWasmShared/src/flow/internal/FlowExceptions.kt\nindex 722911127e..0e780f53a0 100644\n--- a/kotlinx-coroutines-core/jsAndWasmShared/src/flow/internal/FlowExceptions.kt\n+++ b/kotlinx-coroutines-core/jsAndWasmShared/src/flow/internal/FlowExceptions.kt\n@@ -4,6 +4,6 @@ import kotlinx.coroutines.*\n import kotlinx.coroutines.flow.*\n \n internal actual class AbortFlowException actual constructor(\n- actual val owner: FlowCollector<*>\n+ actual val owner: Any\n ) : CancellationException(\"Flow was aborted, no more elements needed\")\n internal actual class ChildCancelledException : CancellationException(\"Child of the scoped flow was cancelled\")\ndiff --git a/kotlinx-coroutines-core/jvm/src/flow/internal/FlowExceptions.kt b/kotlinx-coroutines-core/jvm/src/flow/internal/FlowExceptions.kt\nindex 5ec064c35b..e6f3453359 100644\n--- a/kotlinx-coroutines-core/jvm/src/flow/internal/FlowExceptions.kt\n+++ b/kotlinx-coroutines-core/jvm/src/flow/internal/FlowExceptions.kt\n@@ -4,7 +4,7 @@ import kotlinx.coroutines.*\n import kotlinx.coroutines.flow.*\n \n internal actual class AbortFlowException actual constructor(\n- @JvmField @Transient actual val owner: FlowCollector<*>\n+ @JvmField @Transient actual val owner: Any\n ) : CancellationException(\"Flow was aborted, no more elements needed\") {\n \n override fun fillInStackTrace(): Throwable {\ndiff --git a/kotlinx-coroutines-core/native/src/flow/internal/FlowExceptions.kt b/kotlinx-coroutines-core/native/src/flow/internal/FlowExceptions.kt\nindex ebb47015ec..1109b15fe4 100644\n--- a/kotlinx-coroutines-core/native/src/flow/internal/FlowExceptions.kt\n+++ b/kotlinx-coroutines-core/native/src/flow/internal/FlowExceptions.kt\n@@ -4,7 +4,7 @@ import kotlinx.coroutines.*\n import kotlinx.coroutines.flow.*\n \n internal actual class AbortFlowException actual constructor(\n- actual val owner: FlowCollector<*>\n+ actual val owner: Any\n ) : CancellationException(\"Flow was aborted, no more elements needed\")\n internal actual class ChildCancelledException : CancellationException(\"Child of the scoped flow was cancelled\")\n \n", "test_patch": "diff --git a/kotlinx-coroutines-core/common/test/flow/operators/OnCompletionTest.kt b/kotlinx-coroutines-core/common/test/flow/operators/OnCompletionTest.kt\nindex 8fc9285f5d..14ee53164d 100644\n--- a/kotlinx-coroutines-core/common/test/flow/operators/OnCompletionTest.kt\n+++ b/kotlinx-coroutines-core/common/test/flow/operators/OnCompletionTest.kt\n@@ -308,4 +308,90 @@ class OnCompletionTest : TestBase() {\n .take(1)\n .collect()\n }\n+\n+ /**\n+ * Tests that the operators that are used to limit the flow (like [take] and [zip]) faithfully propagate the\n+ * cancellation exception to the original owner.\n+ */\n+ @Test\n+ fun testOnCompletionBetweenLimitingOperators() = runTest {\n+ // `zip` doesn't eat the exception thrown by `take`:\n+ flowOf(1, 2, 3)\n+ .zip(flowOf(4, 5)) { a, b -> a + b }\n+ .onCompletion {\n+ expect(2)\n+ assertNotNull(it)\n+ }\n+ .take(1)\n+ .collect {\n+ expect(1)\n+ }\n+\n+ // `take` doesn't eat the exception thrown by `zip`:\n+ flowOf(1, 2, 3)\n+ .take(2)\n+ .onCompletion {\n+ expect(4)\n+ assertNotNull(it)\n+ }\n+ .zip(flowOf(4)) { a, b -> a + b }\n+ .collect {\n+ expect(3)\n+ }\n+\n+ // `take` doesn't eat the exception thrown by `first`:\n+ flowOf(1, 2, 3)\n+ .take(2)\n+ .onCompletion {\n+ expect(5)\n+ assertNotNull(it)\n+ }\n+ .first()\n+\n+ // `zip` doesn't eat the exception thrown by `first`:\n+ flowOf(1, 2, 3)\n+ .zip(flowOf(4, 5)) { a, b -> a + b }\n+ .onCompletion {\n+ expect(6)\n+ assertNotNull(it)\n+ }\n+ .first()\n+\n+ // `take` doesn't eat the exception thrown by another `take`:\n+ flowOf(1, 2, 3)\n+ .take(2)\n+ .onCompletion {\n+ expect(8)\n+ assertNotNull(it)\n+ }\n+ .take(1)\n+ .collect {\n+ expect(7)\n+ }\n+\n+ // `zip` doesn't eat the exception thrown by another `zip`:\n+ flowOf(1, 2, 3)\n+ .zip(flowOf(4, 5)) { a, b -> a + b }\n+ .onCompletion {\n+ expect(10)\n+ assertNotNull(it)\n+ }\n+ .zip(flowOf(6)) { a, b -> a + b }\n+ .collect {\n+ expect(9)\n+ }\n+\n+ finish(11)\n+ }\n+\n+ /**\n+ * Tests that emitting new elements after completion doesn't overwrite the old elements.\n+ */\n+ @Test\n+ fun testEmittingElementsAfterCancellation() = runTest {\n+ assertEquals(1, flowOf(1, 2, 3)\n+ .take(100)\n+ .onCompletion { emit(4) }\n+ .first())\n+ }\n }\n", "problem_statement": "Flow hangs even when using terminal operators\n**Describe the bug**\r\n\r\nA flow that uses `take(1)`, `onCompletion { if (it == null) awaitCancellation() }` and `first()` can hang forever instead of returning the first value.\r\n\r\nInterestingly, removing `take(1)` will cause the flow to behave as expected.\r\n\r\n**Provide a Reproducer**\r\nHere is such an example:\r\n```kotlin\r\nflowOf(1)\r\n .take(1)\r\n .onCompletion { if (it == null) awaitCancellation() }\r\n .first()\r\n```\r\n\r\nThis code is expected to return `1`, instead if suspends forever. If you remove `take(1)` it returns `1` as expected.\n", "hints_text": "Sorry, but could you clarify your intentions and why this doesn't match them? Your code literally says: \"await cancellation after everything's finished if the flow completed without errors and didn't need to be cancelled internally.\"\n@dkhalanskyjb the behavior is inconsistent, e.g.\r\n\r\n```\r\nflowOf(1)\r\n .take(1)\r\n .onCompletion { if (it == null) awaitCancellation() }\r\n .first()\r\n```\r\nHangs\r\nwhile \r\n```\r\nflowOf(1)\r\n .take(1)\r\n .onEach { } // no-op operator that doesn't change anything\r\n .onCompletion { if (it == null) awaitCancellation() }\r\n .first()\r\n```\r\nDoesn't\r\n\r\nSimilarly, \r\n```\r\nflowOf(1)\r\n // .take(1) commented take(1). Take(1) is no-op here effectively, as upstream (`flowOf(1)` is also a flow containing only a single element)\r\n .onCompletion { if (it == null) awaitCancellation() }\r\n .first()\r\n```\r\n\r\ndoesn't hang. So the same (from functional perspective) chain behaves differently. \r\n\r\n> \"await cancellation after everything's finished if the flow completed without errors and didn't need to be cancelled internally.\"\r\n\r\nIn this case, that means the second and third snippets are actually those with a bug\nAdding or removing flow operators can change the number of suspensions that collection goes through. That's expected and is intentionally left as an implementation detail. In a future release, the behavior may change. In effect, you have a race condition in your code: either the collection finishes before the last element is emitted, or it doesn't. So, there's no bug so far.\nBut `first` should abort collection after the first emission so it seems strange that it would hang. It also doesn't hang if you instead do `emitAll(flow { awaitCancellation() })`.\r\n\r\nAlso, how can there be a race condition when a single thread is involved? \r\n\r\nThe code also should not have any issues since an operator like `take` could only do its work _after_ the downstream collector has received the item and since the terminal operator (`first`) throws an abort exception, that should bubble up and abort all collection.\r\n\r\nI see the timeline as:\r\n1. `flowOf` emits an item\r\n2. `take` emits this item\r\n3. `onCompletion` emits this item\r\n4. `first` receives the item\r\n5. `first` throws an abort exception\r\n6. This exception is intercepted by `onCompletion ` which calls the block with it (the block itself does nothing at this point)\r\n7. The exception rethrown by `onCompletion `\r\n8. It bubbles up and finally is caught by the `first` operator.\r\n\r\nJudging by the implementation, I don't see how this code should behave differently than:\r\n```kotlin\r\nflowOf(1)\r\n .take(1)\r\n .let { upstream ->\r\n flow {\r\n emitAll(upstream)\r\n awaitCancellation()\r\n }\r\n }\r\n```\r\n\r\nI don't see why/how `onCompletion` would get called with `null` since `first` throws.\n> But `first` should abort collection after the first emission so it seems strange that it would hang.\r\n\r\n`take` is optimized to immediately signal completion after the required number of elements was emitted. We could also tweak the behavior of `flowOf` so that it also does that. Right now, `flowOf` is simply implemented as\r\n\r\n```kotlin\r\npublic fun flowOf(vararg elements: T): Flow = flow {\r\n for (element in elements) {\r\n emit(element)\r\n }\r\n // <-- this line\r\n} // <-- this brace\r\n```\r\n(https://github.com/Kotlin/kotlinx.coroutines/blob/1a0287ca3fb5d6c59594d62131e878da4929c5f8/kotlinx-coroutines-core/common/src/flow/Builders.kt#L122)\r\n\r\nAfter the last `emit` is called, \"this line\" still needs to execute. Flow is considered completed only when \"this brace\" is reached. We know that there's nothing going on in \"this line\", but the flow machinery doesn't. So, in `flowOf(1).first()`, `first` signals that it doesn't need further elements\u2014even though there are none.\r\n\r\nWe could tweak this behavior of `flowOf`, but it's not clear what would be the reason for us to do so.\r\n\r\n> Also, how can there be a race condition when a single thread is involved?\r\n\r\nEasy:\r\n\r\n```kotlin\r\nrunBlocking {\r\n launch {\r\n repeat(100) { yield() }\r\n println(\"A\")\r\n }\r\n launch {\r\n repeat(100) { yield() }\r\n println(\"B\")\r\n }\r\n}\r\n```\r\nA slight change in implementation of either `A` or `B` (changing 100 to 102 or 98) will change the order of operations.\r\n\r\nThe code is still *deterministic*: rerunning it several times will yield the same result. But the race is there: there's no explicit dependency between the moments of `A` and `B`, so changing one thing could lead to the order of execution being changed.\r\n\r\n> The code also should not have any issues since an operator like take could only do its work after the downstream collector has received the item and since the terminal operator (first) throws an abort exception, that should bubble up and abort all collection.\r\n\r\nThis would be the case, but the result of `take` doesn't need to be cancelled. It is implemented in such a way that it succeeds in signaling that it emitted all the elements before the exception from `first` needs to be thrown.\r\n\r\n> I see the timeline as:\r\n\r\nThe problem is at point 2. It essentially emits a \"here's the item, but also, I'm done.\"\nThough this is all theoretical. It can be fun to dig into implementation details, but clearly, no one would write the code like the one in the opening post: they'd just write `1` (or `awaitCancellation().let { 1 }` if the intention was to call `awaitCancellation`). If you can show a case where this particular change in the number of suspensions is causing issues in realistic code, we can discuss more specifically how to rewrite your code to avoid data races.\nThis is interesting and super helpful.\r\nYou say this:\r\n> This would be the case, but the result of take doesn't need to be cancelled. It is implemented in such a way that it succeeds in signaling that it emitted all the elements before the exception from first needs to be thrown.\r\n\r\nBut looking at the implementation, I see that `take` calls `emitAbort` which just calls `emit` and throws. But since `emit` is called first, that means that the `first` operator will see receive the item _before_ that throw call and since `first` itself throws shouldn't that just bubble up and `take` never throws (or completes)?\nOh, yeah. Yes, you are right. This is *not* due to an extra suspension in `flowOf`, as I initially presumed. Sorry for misleading you, and thanks for pursuing this!\r\n\r\nA side note: now that I think about it, a well-behaved `first` does not suffer from a concurrent race: we want every implementation of `first` to *immediately* cancel the flow after the first element is received, so no other non-cleanup code is executed. For example, `flow { emit(1); println(\"X\"); emit(2) }.first()` should never print `X`. So, there is no way for `first` to complete processing the first element without throwing an exception, and consequently, for `onCompletion` not to catch it.\r\n\r\nI've localized the issue. Here's the fun part: the following will also hang!\r\n\r\n```kotlin\r\nflowOf(1, 2, 3)\r\n .take(100) // won't hang if this is removed\r\n .onCompletion { if (it == null) awaitCancellation() }\r\n .first()\r\n```\r\n\r\nThat's clearly a bug, because `flowOf(1, 2, 3).take(100)` has three elements, `first()` only returns one, and `onCompletion` guarantees (https://kotlinlang.org/api/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.flow/on-completion.html):\r\n> [...] this operator reports exception that occur both upstream and downstream and observe exceptions that are thrown to cancel the flow. **Exception is empty if and only if the flow had fully completed successfully**\nAh, great find. I think I understand a bit more now. Does this mean that an operator like `first` will only abort when the flow tries to emit again (or suspend?)?\nNo-no, the opposite: `first` will force the emissions to stop immediately (as it should), or there would be a waste of computations. That's why there are no data races in sensible implementations of `first` for `Flow`.\r\n\r\nThe issue is due to an internal implementation detail: when `first` signals \"No more elements, please,\" `take`, who can also raise the same request, sees the exception and goes, \"Oh, so I guess **I** asked the flow to stop emitting, and it did stop. The goal of that exception accomplished, no one else needs to see the exception\" (including `onCompletion`). So it doesn't raise the exception further.\nAh, so `take` is missing an owner check then? Or rather the owner check isn't correctly implemented.", "created_at": "2024-02-08T09:44:19Z", "version": "1.8", "FAIL_TO_PASS": [ "gradle_test_execution" ], "PASS_TO_PASS": [], "ERROR_TO_PASS": [], "environment_setup_commit": "cd696d3f8f4afdbc735915c2bded974616331b55" }, { "repo": "Kotlin/kotlinx.coroutines", "pull_number": 3580, "instance_id": "Kotlin__kotlinx.coroutines-3580", "issue_numbers": [ "3452" ], "base_commit": "67e21b2424937c234b83dc5acab5d8ae4d033533", "patch": "diff --git a/kotlinx-coroutines-core/jdk8/src/future/Future.kt b/kotlinx-coroutines-core/jdk8/src/future/Future.kt\nindex 4d9a01ac70..f7b4fdca0d 100644\n--- a/kotlinx-coroutines-core/jdk8/src/future/Future.kt\n+++ b/kotlinx-coroutines-core/jdk8/src/future/Future.kt\n@@ -58,10 +58,12 @@ private class CompletableFutureCoroutine(\n }\n \n override fun onCancelled(cause: Throwable, handled: Boolean) {\n- if (!future.completeExceptionally(cause) && !handled) {\n- // prevents loss of exception that was not handled by parent & could not be set to CompletableFuture\n- handleCoroutineException(context, cause)\n- }\n+ /*\n+ * Here we can potentially lose the cause if the failure is racing with future's\n+ * external cancellation. We are consistent with other future implementations\n+ * (LF, FT, CF) and give up on such exception.\n+ */\n+ future.completeExceptionally(cause)\n }\n }\n \n", "test_patch": "diff --git a/kotlinx-coroutines-core/jvm/test/jdk8/future/FutureTest.kt b/kotlinx-coroutines-core/jvm/test/jdk8/future/FutureTest.kt\nindex 372e79ef1d..eda3816511 100644\n--- a/kotlinx-coroutines-core/jvm/test/jdk8/future/FutureTest.kt\n+++ b/kotlinx-coroutines-core/jvm/test/jdk8/future/FutureTest.kt\n@@ -392,11 +392,7 @@ class FutureTest : TestBase() {\n }\n \n @Test\n- fun testUnhandledExceptionOnExternalCompletion() = runTest(\n- unhandled = listOf(\n- { it -> it is TestException } // exception is unhandled because there is no parent\n- )\n- ) {\n+ fun testUnhandledExceptionOnExternalCompletionIsNotReported() = runTest {\n expect(1)\n // No parent here (NonCancellable), so nowhere to propagate exception\n val result = future(NonCancellable + Dispatchers.Unconfined) {\n", "problem_statement": "CoroutineScope.future() may trigger global exception handler on cancellation\n### Expected behavior\r\n\r\n`future` coroutine builder delivers all errors via the returned object, just like `async`.\r\n\r\n### Actual behavior\r\n\r\n`future` coroutine builder can suddenly trigger global exception handler that may crash the application.\r\n\r\nSample code:\r\n```kotlin\r\nfun main() {\r\n val future = GlobalScope.future {\r\n error(\"foo\")\r\n }\r\n future.cancel(true)\r\n Thread.sleep(100)\r\n}\r\n```\r\n\r\nResult:\r\n`Exception in thread \"DefaultDispatcher-worker-1\" java.lang.IllegalStateException: foo`\n", "hints_text": "I believe `CompletableFutureCorotine` should not attempt to handle the exception in any other way than completing the returned `CompletableFuture`. For now, [this is not the case](https://github.com/Kotlin/kotlinx.coroutines/blob/d88a8c227a295f91251960c8fe6b21a02ddf704b/integration/kotlinx-coroutines-jdk8/src/future/Future.kt#L63).", "created_at": "2023-01-06T16:12:13Z", "version": "1.6", "FAIL_TO_PASS": [ "gradle_test_execution" ], "PASS_TO_PASS": [], "ERROR_TO_PASS": [], "environment_setup_commit": "4116d4a178f32b1241db8247a38cd2823fb8b03e" }, { "repo": "pinterest/ktlint", "pull_number": 2125, "instance_id": "pinterest__ktlint-2125", "issue_numbers": [ "2094" ], "base_commit": "e69ac9eba83926c3682a20af69ba8735f5657f5d", "patch": "diff --git a/CHANGELOG.md b/CHANGELOG.md\nindex 509cd20084..78898ab3ed 100644\n--- a/CHANGELOG.md\n+++ b/CHANGELOG.md\n@@ -17,6 +17,7 @@ This project adheres to [Semantic Versioning](https://semver.org/).\n * Log message `Format was not able to resolve all violations which (theoretically) can be autocorrected in file ... in 3 consecutive runs of format` is now only displayed in case a new ktlint rule is actually needed. [#2129](https://github.com/pinterest/ktlint/issues/2129)\n * Fix wrapping of function signature in case the opening brace of the function body block exceeds the maximum line length. Fix upsert of whitespace into composite nodes. `function-signature` [#2130](https://github.com/pinterest/ktlint/issues/2130)\n * Fix spacing around colon in annotations `spacing-around-colon` ([#2093](https://github.com/pinterest/ktlint/issues/2093))\n+* Fix indent of IS_EXPRESSION, PREFIX_EXPRESSION and POSTFIX_EXPRESSION in case it contains a linebreak `indent` [#2094](https://github.com/pinterest/ktlint/issues/2094)\n \n ### Changed\n \ndiff --git a/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/IndentationRule.kt b/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/IndentationRule.kt\nindex 3c08326204..3347bffd64 100644\n--- a/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/IndentationRule.kt\n+++ b/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/IndentationRule.kt\n@@ -35,6 +35,7 @@ import com.pinterest.ktlint.rule.engine.core.api.ElementType.FUN\n import com.pinterest.ktlint.rule.engine.core.api.ElementType.FUNCTION_LITERAL\n import com.pinterest.ktlint.rule.engine.core.api.ElementType.IDENTIFIER\n import com.pinterest.ktlint.rule.engine.core.api.ElementType.IF\n+import com.pinterest.ktlint.rule.engine.core.api.ElementType.IS_EXPRESSION\n import com.pinterest.ktlint.rule.engine.core.api.ElementType.KDOC\n import com.pinterest.ktlint.rule.engine.core.api.ElementType.KDOC_END\n import com.pinterest.ktlint.rule.engine.core.api.ElementType.KDOC_LEADING_ASTERISK\n@@ -50,6 +51,8 @@ import com.pinterest.ktlint.rule.engine.core.api.ElementType.OBJECT_DECLARATION\n import com.pinterest.ktlint.rule.engine.core.api.ElementType.OPEN_QUOTE\n import com.pinterest.ktlint.rule.engine.core.api.ElementType.OPERATION_REFERENCE\n import com.pinterest.ktlint.rule.engine.core.api.ElementType.PARENTHESIZED\n+import com.pinterest.ktlint.rule.engine.core.api.ElementType.POSTFIX_EXPRESSION\n+import com.pinterest.ktlint.rule.engine.core.api.ElementType.PREFIX_EXPRESSION\n import com.pinterest.ktlint.rule.engine.core.api.ElementType.PRIMARY_CONSTRUCTOR\n import com.pinterest.ktlint.rule.engine.core.api.ElementType.PROPERTY\n import com.pinterest.ktlint.rule.engine.core.api.ElementType.PROPERTY_ACCESSOR\n@@ -263,6 +266,11 @@ public class IndentationRule :\n node.elementType == USER_TYPE ->\n startIndentContext(node)\n \n+ node.elementType == IS_EXPRESSION ||\n+ node.elementType == PREFIX_EXPRESSION ||\n+ node.elementType == POSTFIX_EXPRESSION ->\n+ startIndentContext(node)\n+\n node.elementType == DELEGATED_SUPER_TYPE_ENTRY ||\n node.elementType == ANNOTATED_EXPRESSION ||\n node.elementType == TYPE_REFERENCE ->\n", "test_patch": "diff --git a/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/IndentationRuleTest.kt b/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/IndentationRuleTest.kt\nindex e35cdb2afc..04748ac966 100644\n--- a/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/IndentationRuleTest.kt\n+++ b/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/IndentationRuleTest.kt\n@@ -5340,6 +5340,63 @@ internal class IndentationRuleTest {\n .hasNoLintViolations()\n }\n \n+ @Test\n+ fun `Issue 2094 - Given a malformed IS_EXPRESSION`() {\n+ val code =\n+ \"\"\"\n+ fun foo(any: Any) =\n+ any is\n+ Foo\n+ \"\"\".trimIndent()\n+ val formattedCode =\n+ \"\"\"\n+ fun foo(any: Any) =\n+ any is\n+ Foo\n+ \"\"\".trimIndent()\n+ indentationRuleAssertThat(code)\n+ .hasLintViolation(3, 1, \"Unexpected indentation (4) (should be 8)\")\n+ .isFormattedAs(formattedCode)\n+ }\n+\n+ @Test\n+ fun `Issue 2094 - Given a malformed PREFIX_EXPRESSION`() {\n+ val code =\n+ \"\"\"\n+ fun foo(value: Int) =\n+ ++\n+ value\n+ \"\"\".trimIndent()\n+ val formattedCode =\n+ \"\"\"\n+ fun foo(value: Int) =\n+ ++\n+ value\n+ \"\"\".trimIndent()\n+ indentationRuleAssertThat(code)\n+ .hasLintViolation(3, 1, \"Unexpected indentation (4) (should be 8)\")\n+ .isFormattedAs(formattedCode)\n+ }\n+\n+ @Test\n+ fun `Issue 2094 - Given a malformed POSTFIX_EXPRESSION`() {\n+ val code =\n+ \"\"\"\n+ fun foo(value: Int) =\n+ --\n+ value\n+ \"\"\".trimIndent()\n+ val formattedCode =\n+ \"\"\"\n+ fun foo(value: Int) =\n+ --\n+ value\n+ \"\"\".trimIndent()\n+ indentationRuleAssertThat(code)\n+ .hasLintViolation(3, 1, \"Unexpected indentation (4) (should be 8)\")\n+ .isFormattedAs(formattedCode)\n+ }\n+\n private companion object {\n val INDENT_STYLE_TAB =\n INDENT_STYLE_PROPERTY to PropertyType.IndentStyleValue.tab\ndiff --git a/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/MultilineExpressionWrappingTest.kt b/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/MultilineExpressionWrappingTest.kt\nindex 6cb2b89728..ab338eec3f 100644\n--- a/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/MultilineExpressionWrappingTest.kt\n+++ b/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/MultilineExpressionWrappingTest.kt\n@@ -574,12 +574,11 @@ class MultilineExpressionWrappingTest {\n fun foo(any: Any) = any is\n Foo\n \"\"\".trimIndent()\n- // TODO: https://github.com/pinterest/ktlint/issues/2094 Fix formatting by indent rule\n val formattedCode =\n \"\"\"\n fun foo(any: Any) =\n any is\n- Foo\n+ Foo\n \"\"\".trimIndent()\n multilineExpressionWrappingAssertThat(code)\n .addAdditionalRuleProvider { IndentationRule() }\n@@ -615,12 +614,11 @@ class MultilineExpressionWrappingTest {\n fun foo(any: Int) = ++\n 42\n \"\"\".trimIndent()\n- // TODO: https://github.com/pinterest/ktlint/issues/2094 Fix formatting by indent rule\n val formattedCode =\n \"\"\"\n fun foo(any: Int) =\n ++\n- 42\n+ 42\n \"\"\".trimIndent()\n multilineExpressionWrappingAssertThat(code)\n .addAdditionalRuleProvider { IndentationRule() }\n", "problem_statement": "Indent IS_EXPRESSION and PREFIX_EXPRESSION\nA multiline IS_EXPRESSION like below:\r\n```\r\nfun foo(any: Any) = any is\r\n Foo\r\n```\r\nis formatted by ktlint `0.49.x` to:\r\n```\r\nfun foo(any: Any) =\r\n any is\r\n Foo\r\n```\r\nwhile below was expected:\r\n```\r\nfun foo(any: Any) =\r\n any is\r\n Foo\r\n```\r\n\r\nSame for PREFIX_EXPRESSION:\r\n```\r\nfun foo(any: Int) = ++\r\n 42\r\n```\n", "hints_text": "", "created_at": "2023-07-12T18:53:40Z", "version": "0.50", "FAIL_TO_PASS": [ "gradle_test_execution" ], "PASS_TO_PASS": [], "ERROR_TO_PASS": [], "environment_setup_commit": "0a2500665d514f27ad06828544c43a6f28924426" }, { "repo": "pinterest/ktlint", "pull_number": 1996, "instance_id": "pinterest__ktlint-1996", "issue_numbers": [ "1971" ], "base_commit": "6e2504586fc3434c9754b76fb932cddb18d82772", "patch": "diff --git a/CHANGELOG.md b/CHANGELOG.md\nindex b7d5f5fdd3..ab67c249ea 100644\n--- a/CHANGELOG.md\n+++ b/CHANGELOG.md\n@@ -15,6 +15,7 @@ This project adheres to [Semantic Versioning](https://semver.org/).\n * Prevent nullpointer exception (NPE) if class without body is followed by multiple blank lines until end of file `no-consecutive-blank-lines` ([#1987](https://github.com/pinterest/ktlint/issues/1987))\n * Allow to 'unset' the `.editorconfig` property `ktlint_function_signature_rule_force_multiline_when_parameter_count_greater_or_equal_than` when using `ktlint_official` code style `function-signature` ([#1977](https://github.com/pinterest/ktlint/issues/1977))\n * Prevent nullpointer exception (NPE) if or operator at start of line is followed by dot qualified expression `indent` ([#1993](https://github.com/pinterest/ktlint/issues/1993))\n+* Restrict indentation of closing quotes to `ktlint_official` code style to keep formatting of other code styles consistent with `0.48.x` and before `indent` ([#1971](https://github.com/pinterest/ktlint/issues/1971))\n \n ### Changed\n * Separated Baseline functionality out of `ktlint-cli` into separate `ktlint-baseline` module for API consumers\ndiff --git a/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/IndentationRule.kt b/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/IndentationRule.kt\nindex c802acac00..65465d1e45 100644\n--- a/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/IndentationRule.kt\n+++ b/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/IndentationRule.kt\n@@ -89,6 +89,7 @@ import com.pinterest.ktlint.rule.engine.core.api.Rule.VisitorModifier.RunAfterRu\n import com.pinterest.ktlint.rule.engine.core.api.RuleId\n import com.pinterest.ktlint.rule.engine.core.api.children\n import com.pinterest.ktlint.rule.engine.core.api.editorconfig.CODE_STYLE_PROPERTY\n+import com.pinterest.ktlint.rule.engine.core.api.editorconfig.CodeStyleValue\n import com.pinterest.ktlint.rule.engine.core.api.editorconfig.CodeStyleValue.ktlint_official\n import com.pinterest.ktlint.rule.engine.core.api.editorconfig.EditorConfig\n import com.pinterest.ktlint.rule.engine.core.api.editorconfig.INDENT_SIZE_PROPERTY\n@@ -1083,7 +1084,7 @@ public class IndentationRule :\n emit: (offset: Int, errorMessage: String, canBeAutoCorrected: Boolean) -> Unit,\n ) {\n if (!this::stringTemplateIndenter.isInitialized) {\n- stringTemplateIndenter = StringTemplateIndenter(indentConfig)\n+ stringTemplateIndenter = StringTemplateIndenter(codeStyle, indentConfig)\n }\n stringTemplateIndenter.visitClosingQuotes(currentIndent(), node.treeParent, autoCorrect, emit)\n }\n@@ -1215,7 +1216,10 @@ private fun String.textWithEscapedTabAndNewline(): String {\n ).plus(suffix)\n }\n \n-private class StringTemplateIndenter(private val indentConfig: IndentConfig) {\n+private class StringTemplateIndenter(\n+ private val codeStyle: CodeStyleValue,\n+ private val indentConfig: IndentConfig,\n+) {\n fun visitClosingQuotes(\n expectedIndent: String,\n node: ASTNode,\n@@ -1243,7 +1247,7 @@ private class StringTemplateIndenter(private val indentConfig: IndentConfig) {\n val prefixLength = node.getCommonPrefixLength()\n val prevLeaf = node.prevLeaf()\n val correctedExpectedIndent =\n- if (node.isRawStringLiteralReturnInFunctionBodyBlock()) {\n+ if (codeStyle == ktlint_official && node.isRawStringLiteralReturnInFunctionBodyBlock()) {\n // Allow:\n // fun foo(): String {\n // return \"\"\"\n@@ -1253,7 +1257,7 @@ private class StringTemplateIndenter(private val indentConfig: IndentConfig) {\n node\n .indent(false)\n .plus(indentConfig.indent)\n- } else if (node.isRawStringLiteralFunctionBodyExpression()) {\n+ } else if (codeStyle == ktlint_official && node.isRawStringLiteralFunctionBodyExpression()) {\n // Allow:\n // fun foo(\n // bar: String\n", "test_patch": "diff --git a/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/IndentationRuleTest.kt b/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/IndentationRuleTest.kt\nindex 8ba35fc243..059e278f01 100644\n--- a/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/IndentationRuleTest.kt\n+++ b/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/IndentationRuleTest.kt\n@@ -1,6 +1,7 @@\n package com.pinterest.ktlint.ruleset.standard.rules\n \n import com.pinterest.ktlint.rule.engine.core.api.editorconfig.CODE_STYLE_PROPERTY\n+import com.pinterest.ktlint.rule.engine.core.api.editorconfig.CodeStyleValue\n import com.pinterest.ktlint.rule.engine.core.api.editorconfig.CodeStyleValue.intellij_idea\n import com.pinterest.ktlint.rule.engine.core.api.editorconfig.CodeStyleValue.ktlint_official\n import com.pinterest.ktlint.rule.engine.core.api.editorconfig.INDENT_SIZE_PROPERTY\n@@ -5055,32 +5056,6 @@ internal class IndentationRuleTest {\n \n @Nested\n inner class `Given a function with raw string literal as result` {\n- @Test\n- fun `As body expression on same line as equals and preceded by space`() {\n- val code =\n- \"\"\"\n- private fun foo(\n- bar: String,\n- ) = $MULTILINE_STRING_QUOTE\n- bar\n- $MULTILINE_STRING_QUOTE.trimIndent()\n- \"\"\".trimIndent()\n- indentationRuleAssertThat(code).hasNoLintViolations()\n- }\n-\n- @Test\n- fun `As body expression on same line as equals but not preceded by space`() {\n- val code =\n- \"\"\"\n- private fun foo(\n- bar: String,\n- ) =$MULTILINE_STRING_QUOTE\n- bar\n- $MULTILINE_STRING_QUOTE.trimIndent()\n- \"\"\".trimIndent()\n- indentationRuleAssertThat(code).hasNoLintViolations()\n- }\n-\n @Test\n fun `As body expression on next line`() {\n val code =\n@@ -5093,32 +5068,136 @@ internal class IndentationRuleTest {\n indentationRuleAssertThat(code).hasNoLintViolations()\n }\n \n- @Test\n- fun `As block body`() {\n- val code =\n- \"\"\"\n- private fun foo( bar: String): String {\n- return $MULTILINE_STRING_QUOTE\n+ @Nested\n+ inner class `Given non-ktlint_official code style` {\n+ private val nonKtlintOfficialCodeStyle = CodeStyleValue.android_studio\n+\n+ @Test\n+ fun `As body expression on same line as equals and preceded by space`() {\n+ val code =\n+ \"\"\"\n+ private fun foo(\n+ bar: String,\n+ ) = $MULTILINE_STRING_QUOTE\n+ bar\n+ $MULTILINE_STRING_QUOTE.trimIndent()\n+ \"\"\".trimIndent()\n+ indentationRuleAssertThat(code)\n+ .withEditorConfigOverride(CODE_STYLE_PROPERTY to nonKtlintOfficialCodeStyle)\n+ .hasNoLintViolations()\n+ }\n+\n+ @Test\n+ fun `As body expression on same line as equals but not preceded by space`() {\n+ val code =\n+ \"\"\"\n+ private fun foo(\n+ bar: String,\n+ ) =$MULTILINE_STRING_QUOTE\n bar\n+ $MULTILINE_STRING_QUOTE.trimIndent()\n+ \"\"\".trimIndent()\n+ indentationRuleAssertThat(code)\n+ .withEditorConfigOverride(CODE_STYLE_PROPERTY to nonKtlintOfficialCodeStyle)\n+ .hasNoLintViolations()\n+ }\n+\n+ @Test\n+ fun `As block body`() {\n+ val code =\n+ \"\"\"\n+ private fun foo( bar: String): String {\n+ return $MULTILINE_STRING_QUOTE\n+ bar\n $MULTILINE_STRING_QUOTE.trimIndent()\n- }\n- \"\"\".trimIndent()\n- indentationRuleAssertThat(code).hasNoLintViolations()\n+ }\n+ \"\"\".trimIndent()\n+ indentationRuleAssertThat(code)\n+ .withEditorConfigOverride(CODE_STYLE_PROPERTY to nonKtlintOfficialCodeStyle)\n+ .hasNoLintViolations()\n+ }\n+\n+ @Test\n+ fun `As body expression of function wrapped in class`() {\n+ val code =\n+ \"\"\"\n+ class Bar {\n+ private fun foo(\n+ bar: String,\n+ ) = $MULTILINE_STRING_QUOTE\n+ bar\n+ $MULTILINE_STRING_QUOTE.trimIndent()\n+ }\n+ \"\"\".trimIndent()\n+ indentationRuleAssertThat(code)\n+ .withEditorConfigOverride(CODE_STYLE_PROPERTY to nonKtlintOfficialCodeStyle)\n+ .hasNoLintViolations()\n+ }\n }\n \n- @Test\n- fun `As body expression of function wrapped in class`() {\n- val code =\n- \"\"\"\n- class Bar {\n+ @Nested\n+ inner class `Given ktlint_official code style` {\n+ @Test\n+ fun `As body expression on same line as equals and preceded by space`() {\n+ val code =\n+ \"\"\"\n private fun foo(\n bar: String,\n ) = $MULTILINE_STRING_QUOTE\n bar\n $MULTILINE_STRING_QUOTE.trimIndent()\n- }\n- \"\"\".trimIndent()\n- indentationRuleAssertThat(code).hasNoLintViolations()\n+ \"\"\".trimIndent()\n+ indentationRuleAssertThat(code)\n+ .withEditorConfigOverride(CODE_STYLE_PROPERTY to ktlint_official)\n+ .hasNoLintViolations()\n+ }\n+\n+ @Test\n+ fun `As body expression on same line as equals but not preceded by space`() {\n+ val code =\n+ \"\"\"\n+ private fun foo(\n+ bar: String,\n+ ) =$MULTILINE_STRING_QUOTE\n+ bar\n+ $MULTILINE_STRING_QUOTE.trimIndent()\n+ \"\"\".trimIndent()\n+ indentationRuleAssertThat(code)\n+ .withEditorConfigOverride(CODE_STYLE_PROPERTY to ktlint_official)\n+ .hasNoLintViolations()\n+ }\n+\n+ @Test\n+ fun `As block body`() {\n+ val code =\n+ \"\"\"\n+ private fun foo( bar: String): String {\n+ return $MULTILINE_STRING_QUOTE\n+ bar\n+ $MULTILINE_STRING_QUOTE.trimIndent()\n+ }\n+ \"\"\".trimIndent()\n+ indentationRuleAssertThat(code)\n+ .withEditorConfigOverride(CODE_STYLE_PROPERTY to ktlint_official)\n+ .hasNoLintViolations()\n+ }\n+\n+ @Test\n+ fun `As body expression of function wrapped in class`() {\n+ val code =\n+ \"\"\"\n+ class Bar {\n+ private fun foo(\n+ bar: String,\n+ ) = $MULTILINE_STRING_QUOTE\n+ bar\n+ $MULTILINE_STRING_QUOTE.trimIndent()\n+ }\n+ \"\"\".trimIndent()\n+ indentationRuleAssertThat(code)\n+ .withEditorConfigOverride(CODE_STYLE_PROPERTY to ktlint_official)\n+ .hasNoLintViolations()\n+ }\n }\n }\n \n", "problem_statement": "Indentation rule inconsistently identifies issues with multiline string closing quotes between functions and properties\n## Expected Behavior\r\nIndentation rule treats properties and functions similarly when identifying issues with multiline string closing quotes.\r\n\r\n## Observed Behavior\r\nThe rule is identifying issues with multiline string closing quotes inconsistently, when the only difference is whether the multiline string is returned from a function or is used as a property.\r\n\r\n## Steps to Reproduce\r\nThrows violation on last line, first char.\r\n```kotlin\r\nfun foo() = \"\"\"\r\n \r\n \r\n\"\"\".trimIndent()\r\n```\r\n\r\nThrows violation on second last line, first char.\r\n```kotlin\r\nfun foo2(): String {\r\n return \"\"\"\r\n \r\n \r\n \"\"\".trimIndent()\r\n}\r\n```\r\n\r\nDoes not throw. The only difference between this and the first case is the change from `fun foo()` to `val foo`.\r\n```kotlin\r\nval foo = \"\"\"\r\n \r\n \r\n\"\"\".trimIndent()\r\n```\r\n\r\n## Your Environment\r\n\r\n* Version of ktlint used: 0.49.0\r\n* Relevant parts of the `.editorconfig` settings: N/A, using detekt wrapper, but also verified by adding failing test cases to `IndentationRuleTest`\r\n* Name and version (or code for custom task) of integration used (Gradle plugin, Maven plugin, command line, custom Gradle task): Gradle\r\n* Version of Gradle used (if applicable): 8.1/8.1.1\r\n* Operating System and version: Windows 11 22H2\r\n\n", "hints_text": "> Throws violation on second last line, first char.\r\n\r\nI can can not reproduce this finding on `fun foo2`. Like with `fun foo` the error is reported at the beginning of the line containing the closing quotes.\r\n\r\n```\r\n$ cat << EOF | ktlint-0.49.0 --stdin\r\n> fun foo() = \"\"\"\r\n> \r\n> \r\n> \"\"\".trimIndent()\r\n> \r\n> fun foo2(): String {\r\n> return \"\"\"\r\n> \r\n> \r\n> \"\"\".trimIndent()\r\n> }\r\n> \r\n> val foo = \"\"\"\r\n> \r\n> \r\n> \"\"\".trimIndent()\r\n> EOF\r\n17:22:41.009 [main] INFO com.pinterest.ktlint.cli.internal.KtlintCommandLine - Enable default patterns [**/*.kt, **/*.kts]\r\n:4:1: Unexpected indent of multiline string closing quotes (standard:indent)\r\n:10:1: Unexpected indent of multiline string closing quotes (standard:indent)\r\n```\r\n\r\n> Does not throw. The only difference between this and the first case is the change from fun foo() to val foo.\r\n> ```\r\n> val foo = \"\"\"\r\n> \r\n> \r\n> \"\"\".trimIndent()\r\n> ```\r\n\r\nThis is indeed not consistent and needs to be fixed.\n@3flex Can you please respond on previous comment? It would be more convenient for me to know whether a problem is to be fixed with example of `fun foo2()`.", "created_at": "2023-05-06T15:17:44Z", "version": "0.49", "FAIL_TO_PASS": [ "gradle_test_execution" ], "PASS_TO_PASS": [], "ERROR_TO_PASS": [], "environment_setup_commit": "410d8849874f4d3600f9d4572e0850adccce4f2d" }, { "repo": "pinterest/ktlint", "pull_number": 1766, "instance_id": "pinterest__ktlint-1766", "issue_numbers": [ "1766" ], "base_commit": "2aedbd4d60e23973d8469c230c9ac25d2611a9e5", "patch": "diff --git a/CHANGELOG.md b/CHANGELOG.md\nindex ea4b034ebb..4ca0e743ab 100644\n--- a/CHANGELOG.md\n+++ b/CHANGELOG.md\n@@ -9,9 +9,9 @@ This project adheres to [Semantic Versioning](https://semver.org/).\n ### Removed\n \n ### Fixed\n+* Fix with array-syntax annotations on the same line as other annotations `annotation` ([#1765](https://github.com/pinterest/ktlint/issues/1765))\n * Do not enable the experimental rules by default when `.editorconfig` properties `disabled_rules` or `ktlint_disabled_rules` are set. ([#1771](https://github.com/pinterest/ktlint/issues/1771))\n * A function signature not having any parameters which exceeds the `max-line-length` should be ignored by rule `function-signature` ([#1773](https://github.com/pinterest/ktlint/issues/1773))\n-* \n \n ### Changed\n \ndiff --git a/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/AnnotationRule.kt b/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/AnnotationRule.kt\nindex 7fdfdd8891..0d942fde35 100644\n--- a/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/AnnotationRule.kt\n+++ b/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/AnnotationRule.kt\n@@ -20,6 +20,7 @@ import com.pinterest.ktlint.core.ast.lastChildLeafOrSelf\n import com.pinterest.ktlint.core.ast.nextCodeLeaf\n import com.pinterest.ktlint.core.ast.nextLeaf\n import com.pinterest.ktlint.core.ast.prevLeaf\n+import com.pinterest.ktlint.core.ast.upsertWhitespaceAfterMe\n import com.pinterest.ktlint.core.ast.upsertWhitespaceBeforeMe\n import org.jetbrains.kotlin.com.intellij.lang.ASTNode\n import org.jetbrains.kotlin.com.intellij.psi.PsiWhiteSpace\n@@ -49,6 +50,9 @@ public class AnnotationRule : Rule(\"annotation\") {\n FILE_ANNOTATION_LIST -> {\n visitFileAnnotationList(node, emit, autoCorrect)\n }\n+ ANNOTATION -> {\n+ visitAnnotation(node, emit, autoCorrect)\n+ }\n ANNOTATION_ENTRY ->\n visitAnnotationEntry(node, emit, autoCorrect)\n }\n@@ -259,6 +263,31 @@ public class AnnotationRule : Rule(\"annotation\") {\n }\n }\n \n+ private fun visitAnnotation(\n+ node: ASTNode,\n+ emit: (offset: Int, errorMessage: String, canBeAutoCorrected: Boolean) -> Unit,\n+ autoCorrect: Boolean,\n+ ) {\n+ require(node.elementType == ANNOTATION)\n+\n+ if ((node.isFollowedByOtherAnnotationEntry() && node.isOnSameLineAsNextAnnotationEntry()) ||\n+ (node.isPrecededByOtherAnnotationEntry() && node.isOnSameLineAsPreviousAnnotationEntry())\n+ ) {\n+ emit(\n+ node.startOffset,\n+ \"@[...] style annotations should be on a separate line from other annotations.\",\n+ true,\n+ )\n+ if (autoCorrect) {\n+ if (node.isFollowedByOtherAnnotationEntry()) {\n+ node.upsertWhitespaceAfterMe(getNewlineWithIndent(node.treeParent))\n+ } else if (node.isPrecededByOtherAnnotationEntry()) {\n+ node.upsertWhitespaceBeforeMe(getNewlineWithIndent(node.treeParent))\n+ }\n+ }\n+ }\n+ }\n+\n private fun getNewlineWithIndent(modifierListRoot: ASTNode): String {\n val nodeBeforeAnnotations = modifierListRoot.treeParent.treePrev as? PsiWhiteSpace\n // If there is no whitespace before the annotation, the annotation is the first\n", "test_patch": "diff --git a/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/AnnotationRuleTest.kt b/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/AnnotationRuleTest.kt\nindex e1f4dc9ae8..af14897739 100644\n--- a/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/AnnotationRuleTest.kt\n+++ b/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/AnnotationRuleTest.kt\n@@ -548,4 +548,46 @@ class AnnotationRuleTest {\n \"\"\".trimIndent()\n annotationRuleAssertThat(code).hasNoLintViolations()\n }\n+\n+ @Nested inner class `Array syntax annotations, Issue #1765` {\n+ @Test\n+ fun `annotation preceded by array syntax annotation`() {\n+ val code =\n+ \"\"\"\n+ class Main {\n+ @[Foo1 Foo2] @Foo3\n+ fun foo() {}\n+ }\n+ \"\"\".trimIndent()\n+ val formattedCode =\n+ \"\"\"\n+ class Main {\n+ @[Foo1 Foo2]\n+ @Foo3\n+ fun foo() {}\n+ }\n+ \"\"\".trimIndent()\n+ annotationRuleAssertThat(code)\n+ .hasLintViolation(2, 5, \"@[...] style annotations should be on a separate line from other annotations.\")\n+ .isFormattedAs(formattedCode)\n+ }\n+\n+ @Test\n+ fun `annotation followed by array syntax annotation`() {\n+ val code =\n+ \"\"\"\n+ @Foo3 @[Foo1 Foo2]\n+ fun foo() {}\n+ \"\"\".trimIndent()\n+ val formattedCode =\n+ \"\"\"\n+ @Foo3\n+ @[Foo1 Foo2]\n+ fun foo() {}\n+ \"\"\".trimIndent()\n+ annotationRuleAssertThat(code)\n+ .hasLintViolation(1, 7, \"@[...] style annotations should be on a separate line from other annotations.\")\n+ .isFormattedAs(formattedCode)\n+ }\n+ }\n }\n", "problem_statement": "Fixing issue #1765 with array syntax annotations\nIt seemed simplest to always force `@[...]` annotations onto separate lines.\r\n\r\nCloses #1765 \r\n\r\n## Description\r\n\r\nAdded separate check for `ANNOTATION` elements.\r\n\r\n## Checklist\r\n\r\n\r\n- [x] PR description added\r\n- [x] tests are added\r\n- [x] KtLint has been applied on source code itself and violations are fixed\r\n- [ ] [documentation](https://pinterest.github.io/ktlint/) is updated\r\n- [x] `CHANGELOG.md` is updated\r\n\n", "hints_text": "", "created_at": "2023-01-04T23:30:21Z", "version": "0.49", "FAIL_TO_PASS": [ "gradle_test_execution" ], "PASS_TO_PASS": [], "ERROR_TO_PASS": [], "environment_setup_commit": "410d8849874f4d3600f9d4572e0850adccce4f2d" }, { "repo": "pinterest/ktlint", "pull_number": 1997, "instance_id": "pinterest__ktlint-1997", "issue_numbers": [ "1976" ], "base_commit": "fc16aa0d4fe55956a4d6703067a72d3ae4c8a11a", "patch": "diff --git a/CHANGELOG.md b/CHANGELOG.md\nindex ab67c249ea..0657381500 100644\n--- a/CHANGELOG.md\n+++ b/CHANGELOG.md\n@@ -15,6 +15,7 @@ This project adheres to [Semantic Versioning](https://semver.org/).\n * Prevent nullpointer exception (NPE) if class without body is followed by multiple blank lines until end of file `no-consecutive-blank-lines` ([#1987](https://github.com/pinterest/ktlint/issues/1987))\n * Allow to 'unset' the `.editorconfig` property `ktlint_function_signature_rule_force_multiline_when_parameter_count_greater_or_equal_than` when using `ktlint_official` code style `function-signature` ([#1977](https://github.com/pinterest/ktlint/issues/1977))\n * Prevent nullpointer exception (NPE) if or operator at start of line is followed by dot qualified expression `indent` ([#1993](https://github.com/pinterest/ktlint/issues/1993))\n+* Fix indentation of multiline parameter list in function literal `indent` ([#1976](https://github.com/pinterest/ktlint/issues/1976))\n * Restrict indentation of closing quotes to `ktlint_official` code style to keep formatting of other code styles consistent with `0.48.x` and before `indent` ([#1971](https://github.com/pinterest/ktlint/issues/1971))\n \n ### Changed\ndiff --git a/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/IndentationRule.kt b/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/IndentationRule.kt\nindex 65465d1e45..39ae35af94 100644\n--- a/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/IndentationRule.kt\n+++ b/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/IndentationRule.kt\n@@ -53,7 +53,6 @@ import com.pinterest.ktlint.rule.engine.core.api.ElementType.PROPERTY\n import com.pinterest.ktlint.rule.engine.core.api.ElementType.PROPERTY_ACCESSOR\n import com.pinterest.ktlint.rule.engine.core.api.ElementType.RBRACE\n import com.pinterest.ktlint.rule.engine.core.api.ElementType.RBRACKET\n-import com.pinterest.ktlint.rule.engine.core.api.ElementType.REFERENCE_EXPRESSION\n import com.pinterest.ktlint.rule.engine.core.api.ElementType.REGULAR_STRING_PART\n import com.pinterest.ktlint.rule.engine.core.api.ElementType.RETURN_KEYWORD\n import com.pinterest.ktlint.rule.engine.core.api.ElementType.RPAR\n@@ -96,6 +95,7 @@ import com.pinterest.ktlint.rule.engine.core.api.editorconfig.INDENT_SIZE_PROPER\n import com.pinterest.ktlint.rule.engine.core.api.editorconfig.INDENT_STYLE_PROPERTY\n import com.pinterest.ktlint.rule.engine.core.api.firstChildLeafOrSelf\n import com.pinterest.ktlint.rule.engine.core.api.indent\n+import com.pinterest.ktlint.rule.engine.core.api.isPartOf\n import com.pinterest.ktlint.rule.engine.core.api.isPartOfComment\n import com.pinterest.ktlint.rule.engine.core.api.isRoot\n import com.pinterest.ktlint.rule.engine.core.api.isWhiteSpace\n@@ -452,7 +452,7 @@ public class IndentationRule :\n }\n \n private fun ASTNode.calculateIndentOfFunctionLiteralParameters() =\n- if (codeStyle == ktlint_official || isFirstParameterOfFunctionLiteralPrecededByNewLine()) {\n+ if (isFirstParameterOfFunctionLiteralPrecededByNewLine()) {\n // val fieldExample =\n // LongNameClass {\n // paramA,\n@@ -469,13 +469,23 @@ public class IndentationRule :\n // paramC ->\n // ClassB(paramA, paramB, paramC)\n // }\n- parent(CALL_EXPRESSION)\n- ?.let { callExpression ->\n- val textBeforeFirstParameter =\n- callExpression.findChildByType(REFERENCE_EXPRESSION)?.text +\n- \" { \"\n- \" \".repeat(textBeforeFirstParameter.length)\n- }\n+ // val fieldExample =\n+ // someFunction(\n+ // 1,\n+ // 2,\n+ // ) { paramA,\n+ // paramB,\n+ // paramC ->\n+ // ClassB(paramA, paramB, paramC)\n+ // }\n+ this\n+ .takeIf { it.isPartOf(CALL_EXPRESSION) }\n+ ?.treeParent\n+ ?.leaves(false)\n+ ?.takeWhile { !it.isWhiteSpaceWithNewline() }\n+ ?.sumOf { it.textLength }\n+ ?.plus(2) // need to add spaces to compensate for \"{ \"\n+ ?.let { length -> \" \".repeat(length) }\n ?: indentConfig.indent.repeat(2)\n }\n \ndiff --git a/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/ParameterListWrappingRule.kt b/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/ParameterListWrappingRule.kt\nindex 840d0c48c1..3f0926b3a1 100644\n--- a/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/ParameterListWrappingRule.kt\n+++ b/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/ParameterListWrappingRule.kt\n@@ -19,8 +19,11 @@ import com.pinterest.ktlint.rule.engine.core.api.editorconfig.EditorConfig\n import com.pinterest.ktlint.rule.engine.core.api.editorconfig.INDENT_SIZE_PROPERTY\n import com.pinterest.ktlint.rule.engine.core.api.editorconfig.INDENT_STYLE_PROPERTY\n import com.pinterest.ktlint.rule.engine.core.api.editorconfig.MAX_LINE_LENGTH_PROPERTY\n+import com.pinterest.ktlint.rule.engine.core.api.firstChildLeafOrSelf\n import com.pinterest.ktlint.rule.engine.core.api.indent\n import com.pinterest.ktlint.rule.engine.core.api.isWhiteSpaceWithNewline\n+import com.pinterest.ktlint.rule.engine.core.api.parent\n+import com.pinterest.ktlint.rule.engine.core.api.prevCodeLeaf\n import com.pinterest.ktlint.rule.engine.core.api.prevLeaf\n import com.pinterest.ktlint.rule.engine.core.api.prevSibling\n import com.pinterest.ktlint.rule.engine.core.api.upsertWhitespaceAfterMe\n@@ -33,6 +36,7 @@ import org.jetbrains.kotlin.com.intellij.psi.impl.source.tree.PsiWhiteSpaceImpl\n import org.jetbrains.kotlin.psi.KtTypeArgumentList\n import org.jetbrains.kotlin.psi.psiUtil.children\n import org.jetbrains.kotlin.psi.psiUtil.collectDescendantsOfType\n+import org.jetbrains.kotlin.psi.psiUtil.leaves\n \n public class ParameterListWrappingRule :\n StandardRule(\n@@ -120,7 +124,9 @@ public class ParameterListWrappingRule :\n private fun ASTNode.needToWrapParameterList() =\n when {\n hasNoParameters() -> false\n- isPartOfFunctionLiteralInNonKtlintOfficialCodeStyle() -> false\n+ codeStyle != ktlint_official && isPartOfFunctionLiteralInNonKtlintOfficialCodeStyle() -> false\n+ codeStyle == ktlint_official && isPartOfFunctionLiteralStartingOnSameLineAsClosingParenthesisOfPrecedingReferenceExpression() ->\n+ false\n isFunctionTypeWrappedInNullableType() -> false\n textContains('\\n') -> true\n codeStyle == ktlint_official && containsAnnotatedParameter() -> true\n@@ -135,7 +141,23 @@ public class ParameterListWrappingRule :\n \n private fun ASTNode.isPartOfFunctionLiteralInNonKtlintOfficialCodeStyle(): Boolean {\n require(elementType == VALUE_PARAMETER_LIST)\n- return codeStyle != ktlint_official && treeParent?.elementType == FUNCTION_LITERAL\n+ return treeParent?.elementType == FUNCTION_LITERAL\n+ }\n+\n+ private fun ASTNode.isPartOfFunctionLiteralStartingOnSameLineAsClosingParenthesisOfPrecedingReferenceExpression(): Boolean {\n+ require(elementType == VALUE_PARAMETER_LIST)\n+ return firstChildLeafOrSelf()\n+ .let { startOfFunctionLiteral ->\n+ treeParent\n+ ?.takeIf { it.elementType == FUNCTION_LITERAL }\n+ ?.prevCodeLeaf()\n+ ?.takeIf { it.treeParent.elementType == ElementType.VALUE_ARGUMENT_LIST }\n+ ?.takeIf { it.treeParent.treeParent.elementType == ElementType.CALL_EXPRESSION }\n+ ?.leaves()\n+ ?.takeWhile { it != startOfFunctionLiteral }\n+ ?.none { it.isWhiteSpaceWithNewline() }\n+ ?: false\n+ }\n }\n \n private fun ASTNode.isFunctionTypeWrappedInNullableType(): Boolean {\n", "test_patch": "diff --git a/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/IndentationRuleTest.kt b/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/IndentationRuleTest.kt\nindex 059e278f01..5e816c0b2f 100644\n--- a/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/IndentationRuleTest.kt\n+++ b/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/IndentationRuleTest.kt\n@@ -4819,10 +4819,11 @@ internal class IndentationRuleTest {\n .addAdditionalRuleProvider { ParameterListWrappingRule() }\n .withEditorConfigOverride(CODE_STYLE_PROPERTY to ktlint_official)\n .hasLintViolationForAdditionalRule(2, 20, \"Parameter should start on a newline\")\n- .hasLintViolations(\n- LintViolation(3, 1, \"Unexpected indentation (19) (should be 12)\"),\n- LintViolation(4, 1, \"Unexpected indentation (19) (should be 12)\"),\n- ).isFormattedAs(formattedCode)\n+// .hasLintViolations(\n+// LintViolation(3, 1, \"Unexpected indentation (19) (should be 12)\"),\n+// LintViolation(4, 1, \"Unexpected indentation (19) (should be 12)\"),\n+// )\n+ .isFormattedAs(formattedCode)\n }\n \n @Test\ndiff --git a/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/ParameterListWrappingRuleTest.kt b/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/ParameterListWrappingRuleTest.kt\nindex 5cc3aba446..d96a3ee426 100644\n--- a/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/ParameterListWrappingRuleTest.kt\n+++ b/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/ParameterListWrappingRuleTest.kt\n@@ -179,7 +179,7 @@ class ParameterListWrappingRuleTest {\n }\n \n @Nested\n- inner class `Given a function literal having a multiline parameter list` {\n+ inner class `Given a function literal having a multiline parameter list and the first parameter starts on same line as LBRACE` {\n private val code =\n \"\"\"\n val fieldExample =\n@@ -204,10 +204,9 @@ class ParameterListWrappingRuleTest {\n \"\"\".trimIndent()\n parameterListWrappingRuleAssertThat(code)\n .withEditorConfigOverride(CODE_STYLE_PROPERTY to ktlint_official)\n- .hasLintViolationsForAdditionalRule(\n- LintViolation(3, 1, \"Unexpected indentation (20) (should be 12)\"),\n- LintViolation(4, 1, \"Unexpected indentation (20) (should be 12)\"),\n- ).isFormattedAs(formattedCode)\n+ // Indent violations will not be reported until after the wrapping of the first parameter is completed and as of that will\n+ // not be found during linting\n+ .isFormattedAs(formattedCode)\n }\n \n @ParameterizedTest(name = \"Code style = {0}\")\n@@ -216,17 +215,35 @@ class ParameterListWrappingRuleTest {\n mode = EnumSource.Mode.EXCLUDE,\n names = [\"ktlint_official\"],\n )\n- fun `Given another than ktlint_official code style then do not reformat`(codeStyleValue: CodeStyleValue) {\n+ fun `Given another code style than ktlint_official then do not reformat`(codeStyleValue: CodeStyleValue) {\n parameterListWrappingRuleAssertThat(code)\n .withEditorConfigOverride(CODE_STYLE_PROPERTY to codeStyleValue)\n .hasNoLintViolations()\n-// .hasLintViolationsForAdditionalRule(\n-// LintViolation(3, 1, \"Unexpected indentation (20) (should be 12)\"),\n-// LintViolation(4, 1, \"Unexpected indentation (20) (should be 12)\"),\n-// )\n }\n }\n \n+ @ParameterizedTest(name = \"Code style = {0}\")\n+ @EnumSource(value = CodeStyleValue::class)\n+ fun `Given a multiline reference expression with trailing lambda having a multiline parameter list and the first parameter starts on same line as LBRACE`(\n+ codeStyleValue: CodeStyleValue,\n+ ) {\n+ val code =\n+ \"\"\"\n+ val foo =\n+ bar(\n+ Any(),\n+ Any()\n+ ) { a,\n+ b\n+ ->\n+ foobar()\n+ }\n+ \"\"\".trimIndent()\n+ parameterListWrappingRuleAssertThat(code)\n+ .withEditorConfigOverride(CODE_STYLE_PROPERTY to codeStyleValue)\n+ .hasNoLintViolations()\n+ }\n+\n @Test\n fun `Given a function with annotated parameters then start each parameter on a separate line but preserve spacing between annotation and parameter name`() {\n val code =\n", "problem_statement": "Format parameters in lambda\nAfter updating to 0.49.0 this is still not working as ktlint expects the formatting to look like this:\r\n\r\n```kotlin\r\nfun combine(a: Any, b: Any, c: (Any, Any) -> Unit) {\r\n c(a, b)\r\n}\r\n\r\nclass Foo {\r\n fun foo() {\r\n combine(\r\n Any(),\r\n Any()\r\n ) { a,\r\n b -> // Unexpected indentation (8) (should be 14) (standard:indent)\r\n TODO()\r\n }\r\n }\r\n}\r\n```\r\n\r\n_Originally posted by @eygraber in https://github.com/pinterest/ktlint/issues/1756#issuecomment-1520584883_\r\n \n", "hints_text": "In `0.49.0` it works correctly for code style `ktlint_official`. With the other code styles the formatting is indeed incorrect.", "created_at": "2023-05-06T19:12:56Z", "version": "0.49", "FAIL_TO_PASS": [ "gradle_test_execution" ], "PASS_TO_PASS": [], "ERROR_TO_PASS": [], "environment_setup_commit": "410d8849874f4d3600f9d4572e0850adccce4f2d" }, { "repo": "pinterest/ktlint", "pull_number": 2087, "instance_id": "pinterest__ktlint-2087", "issue_numbers": [ "2084" ], "base_commit": "cbee82230f47e043fbf9254344626f8a0665f45c", "patch": "diff --git a/CHANGELOG.md b/CHANGELOG.md\nindex 26e4a6c2ab..3d644b7648 100644\n--- a/CHANGELOG.md\n+++ b/CHANGELOG.md\n@@ -31,6 +31,8 @@ At this point in time, it is not yet decided what the next steps will be. Ktlint\n * Add new experimental rule `no-empty-file` for all code styles. A kotlin (script) file may not be empty ([#1074](https://github.com/pinterest/ktlint/issues/1074))\n * Add new experimental rule `statement-wrapping` which ensures function, class, or other blocks statement body doesn't start or end at starting or ending braces of the block ([#1938](https://github.com/pinterest/ktlint/issues/1938))\n * Add new experimental rule `blank-line-before-declaration`. This rule requires a blank line before class, function or property declarations ([#1939](https://github.com/pinterest/ktlint/issues/1939))\n+* Wrap multiple statements on same line `wrapping` ([#1078](https://github.com/pinterest/ktlint/issues/1078))\n+\n \n ### Removed\n \n@@ -50,6 +52,7 @@ At this point in time, it is not yet decided what the next steps will be. Ktlint\n * Update Kotlin development version to `1.8.22` and Kotlin version to `1.8.22`.\n * Update dependency io.github.detekt.sarif4k:sarif4k to v0.4.0\n * Update dependency org.jetbrains.dokka:dokka-gradle-plugin to v1.8.20\n+* Run format up to 3 times in case formatting introduces changes which also can be autocorrected ([#2084](https://github.com/pinterest/ktlint/issues/2084))\n \n ## [0.49.1] - 2023-05-12\n \ndiff --git a/RELEASE_TESTING.MD b/RELEASE_TESTING.MD\nindex b45adab737..c42b9cff4c 100644\n--- a/RELEASE_TESTING.MD\n+++ b/RELEASE_TESTING.MD\n@@ -40,7 +40,7 @@ Before releasing a new version of KtLint, the release candidate is tested on a s\n ```\n 4. Create an alias or script to run the latest released version of ktlint (note that this script will print the version as reference to which version is used):\n ```shell\n- alias ktlint-prev=\"ktlint-0.47.1 $@\" # Replace with the latest release version\n+ alias ktlint-prev=\"ktlint-0.49.1 $@\" # Replace with the latest release version\n ```\n Note that `~/git/ktlint` is the directory in which the ktlint project is checked out and that `~/git/ktlint/ktlint` refers to the `ktlint` CLI-module.\n 5. Create an alias or script to run the latest development-version of ktlint (note that this script will print the version and the datetime of compilation as reference to which version is used):\n@@ -80,27 +80,7 @@ Pre-requisites:\n \n Formatting projects in which ktlint is not used may result in a huge amount of fixes. The main focus of this test is to see what the effects are when upgrading ktlint in a project already formatted with latest released ktlint version.\n \n-1. Format the sample projects with the *latest released* ktlint version:\n- ```shell\n- ktlint-prev -F --relative # Do not call this command via the \"./exec-in-each-project.sh\" script.\n- ```\n- Note: Ignore all output as this is the old version!\n-2. Commit changes:\n- ```shell\n- ./exec-in-each-project.sh \"git add --all && git commit -m \\\"Format with ktlint (xx.yy.zz) -F\\\"\"\n- ```\n- Repeat step 1 and 2 until no files are changed anymore.\n-3. Create a new baseline file with the *latest released* ktlint version to ignore all lint violations that could not be autocorrected using the latest ktlint version:\n- ```shell\n- rm baseline.xml\n- ktlint-prev --baseline=baseline.xml --relative # Do not call this command via the \"./exec-in-each-project.sh\" script as we want one combined baseline.xml file for all projects.\n- ```\n-4. Check that besides the `baseline.xml` no files are changed (in step 1 and 2 all violations which could be autocorrected have already been committed). Remaining violations which could not be autocorrected are saved in the `baseline.xml` which is stored outside the project directories.\n- ```shell\n- ./exec-in-each-project.sh \"git status\"\n- ```\n- The `baseline.xml` file should only contain errors which can not be autocorrected.\n-5. Define `.editorconfig` in the integration test directory with content below. Also follow up the instructions mentioned:\n+1. Define `.editorconfig` in the integration test directory with content below. Also follow up the instructions mentioned:\n ```editorconfig\n root = true\n [*.{kt,kts}]\n@@ -112,6 +92,8 @@ Formatting projects in which ktlint is not used may result in a huge amount of f\n # graphql\n # ktlint_standard_import-ordering = disabled\n # ktlint_standard_package-name = disabled\n+ # 3) Replace removed property \"disabled_rules\" with \"ktlint_standard_xxxx = disabled\"\n+ ktlint_code_style = ktlint_official\n ktlint_experimental = enabled\n ktlint_standard = enabled\n ktlint_standard_filename = disabled\n@@ -119,14 +101,36 @@ Formatting projects in which ktlint is not used may result in a huge amount of f\n ktlint_standard_function-naming = disabled\n ktlint_standard_property-naming = disabled\n ```\n-6. Commit changes:\n+2. Commit changes:\n ```shell\n ./exec-in-each-project.sh \"git add --all && git commit -m \\\"Update .editorconfig to fallback to integration test settings\\\"\"\n ```\n+3. Format the sample projects with the *latest released* ktlint version:\n+ ```shell\n+ ktlint-prev -F --relative # Do not call this command via the \"./exec-in-each-project.sh\" script.\n+ ```\n+ Note: Ignore all output as this is the old version!\n+4. Commit changes:\n+ ```shell\n+ ./exec-in-each-project.sh \"git add --all && git commit -m \\\"Format with previous ktlint version -F\\\"\"\n+ ```\n+ Repeat step 1 and 2 until no files are changed anymore. Starting from 0.50, all changes should be resolved in one run as format internally reruns 3 times in case new violations are introduced which can be autocorrected as well.\n+5. Create a new baseline file with the *latest released* ktlint version to ignore all lint violations that could not be autocorrected using the latest ktlint version:\n+ ```shell\n+ rm baseline.xml\n+ ktlint-prev --baseline=baseline.xml --relative # Do not call this command via the \"./exec-in-each-project.sh\" script as we want one combined baseline.xml file for all projects.\n+ ```\n+6. Check that besides the `baseline.xml` no files are changed (in step 1 and 2 all violations which could be autocorrected have already been committed). Remaining violations which could not be autocorrected are saved in the `baseline.xml` which is stored outside the project directories.\n+ ```shell\n+ ./exec-in-each-project.sh \"git status\"\n+ ```\n+ The `baseline.xml` file should only contain errors which can not be autocorrected.\n 7. Lint with *latest development* version:\n ```shell\n ktlint-dev --baseline=baseline.xml --relative # Do not call this command via the \"./exec-in-each-project.sh\" script as we want to use the one combined baseline.xml file for all projects.\n- # or when lots are violations are reported\n+ ```\n+ or when lots are violations are reported:\n+ ```shell\n ktlint-dev --baseline=baseline.xml --relative --reporter=plain-summary # Do not call this command via the \"./exec-in-each-project.sh\" script as we want to use the one combined baseline.xml file for all projects.\n ```\n Inspect the output roughly (detailed inspection is done when formatting):\ndiff --git a/documentation/snapshot/docs/rules/experimental.md b/documentation/snapshot/docs/rules/experimental.md\nindex 98f65243ea..b7b92ac4f6 100644\n--- a/documentation/snapshot/docs/rules/experimental.md\n+++ b/documentation/snapshot/docs/rules/experimental.md\n@@ -88,7 +88,7 @@ Requires a blank line before any class or function declaration. No blank line is\n Rule id: `blank-line-before-declaration` (`standard` rule set)\n \n !!! Note\n-This rule is only run when `ktlint_code_style` is set to `ktlint_official` or when the rule is enabled explicitly.\n+ This rule is only run when `ktlint_code_style` is set to `ktlint_official` or when the rule is enabled explicitly.\n \n ## Discouraged comment location\n \ndiff --git a/ktlint-rule-engine-core/src/main/kotlin/com/pinterest/ktlint/rule/engine/core/api/ASTNodeExtension.kt b/ktlint-rule-engine-core/src/main/kotlin/com/pinterest/ktlint/rule/engine/core/api/ASTNodeExtension.kt\nindex 670841c697..65d4dccc3f 100644\n--- a/ktlint-rule-engine-core/src/main/kotlin/com/pinterest/ktlint/rule/engine/core/api/ASTNodeExtension.kt\n+++ b/ktlint-rule-engine-core/src/main/kotlin/com/pinterest/ktlint/rule/engine/core/api/ASTNodeExtension.kt\n@@ -429,3 +429,32 @@ public fun ASTNode.leavesIncludingSelf(forward: Boolean = true): Sequence {\n+ val lastLeafOnLineOrNull = getLastLeafOnLineOrNull()\n+ return getFirstLeafOnLineOrSelf()\n+ .leavesIncludingSelf()\n+ .takeWhile { lastLeafOnLineOrNull == null || it.prevLeaf() != lastLeafOnLineOrNull }\n+}\n+\n+internal fun ASTNode.getFirstLeafOnLineOrSelf() = prevLeaf { it.textContains('\\n') || it.prevLeaf() == null }!!\n+\n+internal fun ASTNode.getLastLeafOnLineOrNull() = nextLeaf { it.textContains('\\n') }?.prevLeaf()\n+\n+/**\n+ * Get the total length of all leaves on the same line as the given node including the whitespace indentation but excluding all leading\n+ * newline characters in the whitespace indentation.\n+ */\n+public fun ASTNode.lineLengthWithoutNewlinePrefix(): Int =\n+ leavesOnLine()\n+ .joinToString(separator = \"\") { it.text }\n+ // If a line is preceded by a blank line then the ident contains multiple newline chars\n+ .dropWhile { it == '\\n' }\n+ // In case the last element on the line would contain a newline then only include chars before that newline. Note that this should\n+ // not occur if the AST is parsed correctly\n+ .takeWhile { it != '\\n' }\n+ .length\ndiff --git a/ktlint-rule-engine/src/main/kotlin/com/pinterest/ktlint/rule/engine/api/Code.kt b/ktlint-rule-engine/src/main/kotlin/com/pinterest/ktlint/rule/engine/api/Code.kt\nindex 98f113c34a..c64d0e97f8 100644\n--- a/ktlint-rule-engine/src/main/kotlin/com/pinterest/ktlint/rule/engine/api/Code.kt\n+++ b/ktlint-rule-engine/src/main/kotlin/com/pinterest/ktlint/rule/engine/api/Code.kt\n@@ -23,6 +23,13 @@ public class Code private constructor(\n fileName.orEmpty()\n }\n \n+ public fun filePathOrStdin(): String =\n+ if (isStdIn) {\n+ STDIN_FILE\n+ } else {\n+ filePath?.pathString.orEmpty()\n+ }\n+\n public companion object {\n /**\n * Create [Code] from a [file] containing valid Kotlin code or script. The '.editorconfig' files on the path to [file] are taken\ndiff --git a/ktlint-rule-engine/src/main/kotlin/com/pinterest/ktlint/rule/engine/api/KtLintRuleEngine.kt b/ktlint-rule-engine/src/main/kotlin/com/pinterest/ktlint/rule/engine/api/KtLintRuleEngine.kt\nindex eec63c77b8..f8c897033e 100644\n--- a/ktlint-rule-engine/src/main/kotlin/com/pinterest/ktlint/rule/engine/api/KtLintRuleEngine.kt\n+++ b/ktlint-rule-engine/src/main/kotlin/com/pinterest/ktlint/rule/engine/api/KtLintRuleEngine.kt\n@@ -135,67 +135,56 @@ public class KtLintRuleEngine(\n val hasUTF8BOM = code.content.startsWith(UTF8_BOM)\n val ruleExecutionContext = createRuleExecutionContext(this, code)\n \n- var tripped = false\n- var mutated = false\n- val errors = mutableSetOf>()\n val visitorProvider = VisitorProvider(ruleExecutionContext.ruleProviders)\n- visitorProvider\n- .visitor()\n- .invoke { rule ->\n- ruleExecutionContext.executeRule(rule, true) { offset, errorMessage, canBeAutoCorrected ->\n- tripped = true\n- if (canBeAutoCorrected) {\n- mutated = true\n- /**\n- * Rebuild the suppression locator after each change in the AST as the offsets of the\n- * suppression hints might have changed.\n- */\n- ruleExecutionContext.rebuildSuppressionLocator()\n- }\n- val (line, col) = ruleExecutionContext.positionInTextLocator(offset)\n- errors.add(\n- Pair(\n- LintError(line, col, rule.ruleId, errorMessage, canBeAutoCorrected),\n- // It is assumed that a rule that emits that an error can be autocorrected, also\n- // does correct the error.\n- canBeAutoCorrected,\n- ),\n- )\n- // In trace mode report the violation immediately. The order in which violations are actually found might be different\n- // from the order in which they are reported. For debugging purposes it cn be helpful to know the exact order in which\n- // violations are being solved.\n- LOGGER.trace {\n- \"Format violation: ${code.fileNameOrStdin()}:$line:$col: $errorMessage (${rule.ruleId})\" +\n- canBeAutoCorrected.ifFalse { \" [cannot be autocorrected]\" }\n- }\n- }\n- }\n- if (tripped) {\n+ var formatRunCount = 0\n+ var mutated: Boolean\n+ val errors = mutableSetOf>()\n+ do {\n+ mutated = false\n+ formatRunCount++\n visitorProvider\n .visitor()\n .invoke { rule ->\n- ruleExecutionContext.executeRule(\n- rule,\n- false,\n- ) { offset, errorMessage, canBeAutoCorrected ->\n+ ruleExecutionContext.executeRule(rule, true) { offset, errorMessage, canBeAutoCorrected ->\n+ if (canBeAutoCorrected) {\n+ mutated = true\n+ /**\n+ * Rebuild the suppression locator after each change in the AST as the offsets of the\n+ * suppression hints might have changed.\n+ */\n+ ruleExecutionContext.rebuildSuppressionLocator()\n+ }\n val (line, col) = ruleExecutionContext.positionInTextLocator(offset)\n errors.add(\n Pair(\n LintError(line, col, rule.ruleId, errorMessage, canBeAutoCorrected),\n- // It is assumed that a rule only corrects an error after it has emitted an\n- // error and indicating that it actually can be autocorrected.\n- false,\n+ // It is assumed that a rule that emits that an error can be autocorrected, also\n+ // does correct the error.\n+ canBeAutoCorrected,\n ),\n )\n+ // In trace mode report the violation immediately. The order in which violations are actually found might be different\n+ // from the order in which they are reported. For debugging purposes it cn be helpful to know the exact order in which\n+ // violations are being solved.\n+ LOGGER.trace {\n+ \"Format violation: ${code.fileNameOrStdin()}:$line:$col: $errorMessage (${rule.ruleId})\" +\n+ canBeAutoCorrected.ifFalse { \" [cannot be autocorrected]\" }\n+ }\n }\n }\n+ } while (mutated && formatRunCount < MAX_FORMAT_RUNS_PER_FILE)\n+ if (formatRunCount == MAX_FORMAT_RUNS_PER_FILE && mutated) {\n+ LOGGER.warn {\n+ \"Format was not able to resolve all violations which (theoretically) can be autocorrected in file \" +\n+ \"${code.filePathOrStdin()} in $MAX_FORMAT_RUNS_PER_FILE consecutive runs of format.\"\n+ }\n }\n \n errors\n .sortedWith { (l), (r) -> if (l.line != r.line) l.line - r.line else l.col - r.col }\n .forEach { (e, corrected) -> callback(e, corrected) }\n \n- if (!mutated) {\n+ if (!mutated && formatRunCount == 1) {\n return code.content\n }\n \n@@ -285,5 +274,7 @@ public class KtLintRuleEngine(\n internal const val UTF8_BOM = \"\\uFEFF\"\n \n public const val STDIN_FILE: String = \"\"\n+\n+ private const val MAX_FORMAT_RUNS_PER_FILE = 3\n }\n }\ndiff --git a/ktlint-ruleset-standard/build.gradle.kts b/ktlint-ruleset-standard/build.gradle.kts\nindex e97bbf2a54..2ad0638382 100644\n--- a/ktlint-ruleset-standard/build.gradle.kts\n+++ b/ktlint-ruleset-standard/build.gradle.kts\n@@ -9,4 +9,5 @@ dependencies {\n api(projects.ktlintRuleEngineCore)\n \n testImplementation(projects.ktlintTest)\n+ testRuntimeOnly(libs.logback)\n }\ndiff --git a/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/ArgumentListWrappingRule.kt b/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/ArgumentListWrappingRule.kt\nindex 743d4fc660..ea8986ae42 100644\n--- a/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/ArgumentListWrappingRule.kt\n+++ b/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/ArgumentListWrappingRule.kt\n@@ -1,20 +1,22 @@\n package com.pinterest.ktlint.ruleset.standard.rules\n \n import com.pinterest.ktlint.rule.engine.core.api.ElementType\n+import com.pinterest.ktlint.rule.engine.core.api.ElementType.BINARY_EXPRESSION\n import com.pinterest.ktlint.rule.engine.core.api.ElementType.ELSE\n import com.pinterest.ktlint.rule.engine.core.api.ElementType.VALUE_ARGUMENT_LIST\n import com.pinterest.ktlint.rule.engine.core.api.IndentConfig\n import com.pinterest.ktlint.rule.engine.core.api.Rule.VisitorModifier.RunAfterRule.Mode.REGARDLESS_WHETHER_RUN_AFTER_RULE_IS_LOADED_OR_DISABLED\n import com.pinterest.ktlint.rule.engine.core.api.RuleId\n-import com.pinterest.ktlint.rule.engine.core.api.column\n import com.pinterest.ktlint.rule.engine.core.api.editorconfig.EditorConfig\n import com.pinterest.ktlint.rule.engine.core.api.editorconfig.INDENT_SIZE_PROPERTY\n import com.pinterest.ktlint.rule.engine.core.api.editorconfig.INDENT_STYLE_PROPERTY\n import com.pinterest.ktlint.rule.engine.core.api.editorconfig.MAX_LINE_LENGTH_PROPERTY\n import com.pinterest.ktlint.rule.engine.core.api.indent\n+import com.pinterest.ktlint.rule.engine.core.api.isPartOf\n import com.pinterest.ktlint.rule.engine.core.api.isPartOfComment\n import com.pinterest.ktlint.rule.engine.core.api.isWhiteSpace\n import com.pinterest.ktlint.rule.engine.core.api.isWhiteSpaceWithNewline\n+import com.pinterest.ktlint.rule.engine.core.api.lineLengthWithoutNewlinePrefix\n import com.pinterest.ktlint.rule.engine.core.api.prevLeaf\n import com.pinterest.ktlint.ruleset.standard.StandardRule\n import org.jetbrains.kotlin.com.intellij.lang.ASTNode\n@@ -47,10 +49,6 @@ public class ArgumentListWrappingRule :\n ruleId = WRAPPING_RULE_ID,\n mode = REGARDLESS_WHETHER_RUN_AFTER_RULE_IS_LOADED_OR_DISABLED,\n ),\n- VisitorModifier.RunAfterRule(\n- ruleId = BINARY_EXPRESSION_WRAPPING_RULE_ID,\n- mode = REGARDLESS_WHETHER_RUN_AFTER_RULE_IS_LOADED_OR_DISABLED,\n- ),\n ),\n usesEditorConfigProperties =\n setOf(\n@@ -96,7 +94,10 @@ public class ArgumentListWrappingRule :\n // skip lambda arguments\n node.treeParent?.elementType != ElementType.FUNCTION_LITERAL &&\n // skip if number of arguments is big (we assume it with a magic number of 8)\n- node.children().count { it.elementType == ElementType.VALUE_ARGUMENT } <= 8\n+ node.children().count { it.elementType == ElementType.VALUE_ARGUMENT } <= 8 &&\n+ // skip if part of a value argument list. It depends on the situation whether it is better to wrap the arguments in the list\n+ // or the operators in the binary expression\n+ !node.isPartOf(BINARY_EXPRESSION)\n ) {\n // each argument should be on a separate line if\n // - at least one of the arguments is\n@@ -107,7 +108,7 @@ public class ArgumentListWrappingRule :\n false\n }\n \n- private fun ASTNode.exceedsMaxLineLength() = (column - 1 + textLength) > maxLineLength && !textContains('\\n')\n+ private fun ASTNode.exceedsMaxLineLength() = lineLengthWithoutNewlinePrefix() > maxLineLength && !textContains('\\n')\n \n private fun intendedIndent(child: ASTNode): String =\n when {\ndiff --git a/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/BinaryExpressionWrappingRule.kt b/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/BinaryExpressionWrappingRule.kt\nindex d1b1db4a11..dbed17961a 100644\n--- a/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/BinaryExpressionWrappingRule.kt\n+++ b/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/BinaryExpressionWrappingRule.kt\n@@ -1,12 +1,18 @@\n package com.pinterest.ktlint.ruleset.standard.rules\n \n import com.pinterest.ktlint.rule.engine.core.api.ElementType.BINARY_EXPRESSION\n+import com.pinterest.ktlint.rule.engine.core.api.ElementType.CALL_EXPRESSION\n import com.pinterest.ktlint.rule.engine.core.api.ElementType.EQ\n import com.pinterest.ktlint.rule.engine.core.api.ElementType.FUN\n+import com.pinterest.ktlint.rule.engine.core.api.ElementType.LAMBDA_ARGUMENT\n+import com.pinterest.ktlint.rule.engine.core.api.ElementType.LONG_STRING_TEMPLATE_ENTRY\n import com.pinterest.ktlint.rule.engine.core.api.ElementType.OPERATION_REFERENCE\n import com.pinterest.ktlint.rule.engine.core.api.ElementType.PROPERTY\n+import com.pinterest.ktlint.rule.engine.core.api.ElementType.VALUE_ARGUMENT_LIST\n import com.pinterest.ktlint.rule.engine.core.api.IndentConfig\n import com.pinterest.ktlint.rule.engine.core.api.Rule\n+import com.pinterest.ktlint.rule.engine.core.api.Rule.VisitorModifier.RunAfterRule\n+import com.pinterest.ktlint.rule.engine.core.api.Rule.VisitorModifier.RunAfterRule.Mode.REGARDLESS_WHETHER_RUN_AFTER_RULE_IS_LOADED_OR_DISABLED\n import com.pinterest.ktlint.rule.engine.core.api.RuleId\n import com.pinterest.ktlint.rule.engine.core.api.editorconfig.EditorConfig\n import com.pinterest.ktlint.rule.engine.core.api.editorconfig.INDENT_SIZE_PROPERTY\n@@ -14,14 +20,11 @@ import com.pinterest.ktlint.rule.engine.core.api.editorconfig.INDENT_STYLE_PROPE\n import com.pinterest.ktlint.rule.engine.core.api.editorconfig.MAX_LINE_LENGTH_PROPERTY\n import com.pinterest.ktlint.rule.engine.core.api.firstChildLeafOrSelf\n import com.pinterest.ktlint.rule.engine.core.api.indent\n-import com.pinterest.ktlint.rule.engine.core.api.isWhiteSpaceWithNewline\n-import com.pinterest.ktlint.rule.engine.core.api.lastChildLeafOrSelf\n-import com.pinterest.ktlint.rule.engine.core.api.leavesIncludingSelf\n-import com.pinterest.ktlint.rule.engine.core.api.nextLeaf\n+import com.pinterest.ktlint.rule.engine.core.api.leavesOnLine\n+import com.pinterest.ktlint.rule.engine.core.api.nextCodeSibling\n import com.pinterest.ktlint.rule.engine.core.api.nextSibling\n import com.pinterest.ktlint.rule.engine.core.api.noNewLineInClosedRange\n-import com.pinterest.ktlint.rule.engine.core.api.prevCodeSibling\n-import com.pinterest.ktlint.rule.engine.core.api.prevLeaf\n+import com.pinterest.ktlint.rule.engine.core.api.parent\n import com.pinterest.ktlint.rule.engine.core.api.prevSibling\n import com.pinterest.ktlint.rule.engine.core.api.upsertWhitespaceBeforeMe\n import com.pinterest.ktlint.ruleset.standard.StandardRule\n@@ -41,6 +44,10 @@ public class BinaryExpressionWrappingRule :\n INDENT_STYLE_PROPERTY,\n MAX_LINE_LENGTH_PROPERTY,\n ),\n+ visitorModifiers =\n+ setOf(\n+ RunAfterRule(ARGUMENT_LIST_WRAPPING_RULE_ID, REGARDLESS_WHETHER_RUN_AFTER_RULE_IS_LOADED_OR_DISABLED),\n+ ),\n ),\n Rule.Experimental {\n private var indentConfig = IndentConfig.DEFAULT_INDENT_CONFIG\n@@ -80,7 +87,7 @@ public class BinaryExpressionWrappingRule :\n .prevSibling { it.elementType == EQ }\n ?.let { noNewLineInClosedRange(it, binaryExpression.firstChildLeafOrSelf()) }\n ?: false\n- }?.takeIf { textLengthWithoutNewlinePrefix(it.getFirstLeafOnLineOrSelf(), it.getLastLeafOnLineOrNull()) > maxLineLength }\n+ }?.takeIf { it.isOnLineExceedingMaxLineLength() }\n ?.let { expression ->\n emit(\n expression.startOffset,\n@@ -105,10 +112,15 @@ public class BinaryExpressionWrappingRule :\n node\n .takeIf { it.elementType == OPERATION_REFERENCE }\n ?.takeIf { it.treeParent.elementType == BINARY_EXPRESSION }\n- ?.takeIf { textLengthWithoutNewlinePrefix(it.getFirstLeafOnLineOrSelf(), it.getLastLeafOnLineOrNull()) > maxLineLength }\n+ ?.takeIf { binaryExpression ->\n+ // Ignore binary expression inside raw string literals. Raw string literals are allowed to exceed max-line-length. Wrapping\n+ // (each) binary expression inside such a literal seems to create more chaos than it resolves.\n+ binaryExpression.parent { it.elementType == LONG_STRING_TEMPLATE_ENTRY } == null\n+ }?.takeIf { it.isOnLineExceedingMaxLineLength() }\n ?.let { operationReference ->\n- if (cannotBeWrappedAtOperationReference(operationReference)) {\n- // Wrapping after operation reference won't work as the left hand side still does not fit on a single line\n+ if (node.isCallExpressionFollowedByLambdaArgument() || cannotBeWrappedAtOperationReference(operationReference)) {\n+ // Wrapping after operation reference might not be the best place in case of a call expression or just won't work as\n+ // the left hand side still does not fit on a single line\n emit(operationReference.startOffset, \"Line is exceeding max line length\", false)\n } else {\n operationReference\n@@ -116,7 +128,7 @@ public class BinaryExpressionWrappingRule :\n ?.let { nextSibling ->\n emit(\n nextSibling.startOffset,\n- \"Line is exceeding max line length. Break line after operator of binary expression\",\n+ \"Line is exceeding max line length. Break line after operator in binary expression\",\n true,\n )\n if (autoCorrect) {\n@@ -127,25 +139,31 @@ public class BinaryExpressionWrappingRule :\n }\n }\n \n+ private fun ASTNode.isCallExpressionFollowedByLambdaArgument() =\n+ parent { it.elementType == VALUE_ARGUMENT_LIST }\n+ ?.takeIf { it.treeParent.elementType == CALL_EXPRESSION }\n+ ?.nextCodeSibling()\n+ .let { it?.elementType == LAMBDA_ARGUMENT }\n+\n private fun cannotBeWrappedAtOperationReference(operationReference: ASTNode) =\n operationReference\n- .takeUnless { it.prevCodeSibling()?.elementType == BINARY_EXPRESSION }\n- ?.let { textLengthWithoutNewlinePrefix(it.getFirstLeafOnLineOrSelf(), it.lastChildLeafOrSelf()) > maxLineLength }\n+ .takeUnless { it.nextCodeSibling()?.elementType == BINARY_EXPRESSION }\n+ ?.let {\n+ val stopAtOperationReferenceLeaf = operationReference.firstChildLeafOrSelf()\n+ maxLineLength <=\n+ it\n+ .leavesOnLine()\n+ .takeWhile { leaf -> leaf != stopAtOperationReferenceLeaf }\n+ .lengthWithoutNewlinePrefix()\n+ }\n ?: false\n \n- private fun textLengthWithoutNewlinePrefix(\n- fromNode: ASTNode,\n- toNode: ASTNode?,\n- ) = fromNode\n- .leavesIncludingSelf()\n- .takeWhile { it.prevLeaf() != toNode }\n- .joinToString(separator = \"\") { it.text }\n- .removePrefix(\"\\n\")\n- .length\n-\n- private fun ASTNode.getLastLeafOnLineOrNull() = nextLeaf { it.isWhiteSpaceWithNewline() }?.prevLeaf()\n+ private fun ASTNode.isOnLineExceedingMaxLineLength() = leavesOnLine().lengthWithoutNewlinePrefix() > maxLineLength\n \n- private fun ASTNode.getFirstLeafOnLineOrSelf() = prevLeaf { it.isWhiteSpaceWithNewline() || it.prevLeaf() == null }!!\n+ private fun Sequence.lengthWithoutNewlinePrefix() =\n+ joinToString(separator = \"\") { it.text }\n+ .dropWhile { it == '\\n' }\n+ .length\n }\n \n private fun IElementType.anyOf(vararg elementType: IElementType): Boolean = elementType.contains(this)\ndiff --git a/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/BlankLineBeforeDeclarationRule.kt b/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/BlankLineBeforeDeclarationRule.kt\nindex aaa5e1979e..d55aebd499 100644\n--- a/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/BlankLineBeforeDeclarationRule.kt\n+++ b/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/BlankLineBeforeDeclarationRule.kt\n@@ -1,27 +1,34 @@\n package com.pinterest.ktlint.ruleset.standard.rules\n \n-import com.pinterest.ktlint.rule.engine.core.api.ElementType\n import com.pinterest.ktlint.rule.engine.core.api.ElementType.BLOCK\n import com.pinterest.ktlint.rule.engine.core.api.ElementType.CLASS\n+import com.pinterest.ktlint.rule.engine.core.api.ElementType.CLASS_BODY\n+import com.pinterest.ktlint.rule.engine.core.api.ElementType.CLASS_INITIALIZER\n import com.pinterest.ktlint.rule.engine.core.api.ElementType.FUN\n+import com.pinterest.ktlint.rule.engine.core.api.ElementType.FUNCTION_LITERAL\n import com.pinterest.ktlint.rule.engine.core.api.ElementType.LBRACE\n import com.pinterest.ktlint.rule.engine.core.api.ElementType.PROPERTY\n import com.pinterest.ktlint.rule.engine.core.api.ElementType.PROPERTY_ACCESSOR\n+import com.pinterest.ktlint.rule.engine.core.api.ElementType.WHEN\n import com.pinterest.ktlint.rule.engine.core.api.Rule\n import com.pinterest.ktlint.rule.engine.core.api.RuleId\n+import com.pinterest.ktlint.rule.engine.core.api.children\n import com.pinterest.ktlint.rule.engine.core.api.indent\n import com.pinterest.ktlint.rule.engine.core.api.isPartOfComment\n import com.pinterest.ktlint.rule.engine.core.api.isWhiteSpace\n import com.pinterest.ktlint.rule.engine.core.api.nextCodeSibling\n import com.pinterest.ktlint.rule.engine.core.api.prevCodeSibling\n+import com.pinterest.ktlint.rule.engine.core.api.prevLeaf\n import com.pinterest.ktlint.rule.engine.core.api.upsertWhitespaceBeforeMe\n+import com.pinterest.ktlint.rule.engine.core.util.safeAs\n import com.pinterest.ktlint.ruleset.standard.StandardRule\n import org.jetbrains.kotlin.com.intellij.lang.ASTNode\n-import org.jetbrains.kotlin.psi.psiUtil.siblings\n+import org.jetbrains.kotlin.psi.KtDeclaration\n+import org.jetbrains.kotlin.psi.KtFunctionLiteral\n \n /**\n- * Insert a blank line before declarations. No blank line is inserted before between the class signature and the first declaration in the\n- * class. Also, no blank lines are inserted between consecutive properties.\n+ * Insert a blank line before declarations. No blank line is inserted before between a class or method signature and the first declaration\n+ * in the class or method respectively. Also, no blank lines are inserted between consecutive properties.\n */\n public class BlankLineBeforeDeclarationRule :\n StandardRule(\"blank-line-before-declaration\"),\n@@ -34,6 +41,7 @@ public class BlankLineBeforeDeclarationRule :\n ) {\n when (node.elementType) {\n CLASS,\n+ CLASS_INITIALIZER,\n FUN,\n PROPERTY,\n PROPERTY_ACCESSOR,\n@@ -47,9 +55,34 @@ public class BlankLineBeforeDeclarationRule :\n autoCorrect: Boolean,\n emit: (offset: Int, errorMessage: String, canBeAutoCorrected: Boolean) -> Unit,\n ) {\n- if (node == node.firstCodeSiblingInClassBodyOrNull()) {\n- // Allow missing blank line between class signature and first code sibling in class body:\n- // Class Foo {\n+ if (node.isFirstCodeSiblingInClassBody()) {\n+ // No blank line between class signature and first declaration in class body:\n+ // class Foo {\n+ // fun bar() {}\n+ // }\n+ // class Foo {\n+ // class bar\n+ // }\n+ return\n+ }\n+\n+ if (node.isFirstCodeSiblingInBlock()) {\n+ // No blank line between opening brace of block and first code sibling in class body:\n+ // fun foo() {\n+ // class Bar\n+ // }\n+ // val foo = {\n+ // fun bar() {}\n+ // }\n+ return\n+ }\n+\n+ if (node.isFirstCodeSiblingInBodyOfFunctionLiteral()) {\n+ // No blank line between opening brace of function literal and declaration as first code sibling:\n+ // val foo = {\n+ // fun bar() {}\n+ // }\n+ // val foo = { _ ->\n // fun bar() {}\n // }\n return\n@@ -71,29 +104,54 @@ public class BlankLineBeforeDeclarationRule :\n return\n }\n \n+ if (node.elementType == PROPERTY && node.treeParent.elementType == WHEN) {\n+ // Allow:\n+ // when(val foo = foo()) {\n+ // ...\n+ // }\n+ return\n+ }\n+\n node\n- .siblings(false)\n- .takeWhile { it.isWhiteSpace() || it.isPartOfComment() }\n- .lastOrNull()\n- ?.let { previous ->\n- when {\n- !previous.isWhiteSpace() -> previous\n- !previous.text.startsWith(\"\\n\\n\") -> node\n- else -> null\n- }?.let { insertBeforeNode ->\n- emit(insertBeforeNode.startOffset, \"Expected a blank line for this declaration\", true)\n- if (autoCorrect) {\n- insertBeforeNode.upsertWhitespaceBeforeMe(\"\\n\".plus(node.indent()))\n- }\n+ .takeIf { it.psi is KtDeclaration }\n+// (node.psi as KtDeclaration)\n+// .node\n+ ?.takeIf {\n+ val prevLeaf = it.prevLeaf()\n+ prevLeaf != null && (!prevLeaf.isWhiteSpace() || !prevLeaf.text.startsWith(\"\\n\\n\"))\n+ }?.let { insertBeforeNode ->\n+ emit(insertBeforeNode.startOffset, \"Expected a blank line for this declaration\", true)\n+ if (autoCorrect) {\n+ insertBeforeNode.upsertWhitespaceBeforeMe(\"\\n\".plus(node.indent()))\n }\n }\n }\n \n- private fun ASTNode.firstCodeSiblingInClassBodyOrNull() =\n- treeParent\n- .takeIf { it.elementType == ElementType.CLASS_BODY }\n- ?.findChildByType(LBRACE)\n- ?.nextCodeSibling()\n+ private fun ASTNode.isFirstCodeSiblingInClassBody() =\n+ this ==\n+ treeParent\n+ .takeIf { it.elementType == CLASS_BODY }\n+ ?.findChildByType(LBRACE)\n+ ?.nextCodeSibling()\n+\n+ private fun ASTNode.isFirstCodeSiblingInBlock() =\n+ this ==\n+ treeParent\n+ .takeIf { it.elementType == BLOCK }\n+ ?.findChildByType(LBRACE)\n+ ?.nextCodeSibling()\n+\n+ private fun ASTNode.isFirstCodeSiblingInBodyOfFunctionLiteral() =\n+ this ==\n+ treeParent\n+ .takeIf { it.elementType == BLOCK && it.treeParent.elementType == FUNCTION_LITERAL }\n+ ?.treeParent\n+ ?.psi\n+ ?.safeAs()\n+ ?.bodyExpression\n+ ?.node\n+ ?.children()\n+ ?.firstOrNull { !it.isWhiteSpace() && !it.isPartOfComment() }\n \n private fun ASTNode.isConsecutiveProperty() =\n takeIf { it.propertyRelated() }\ndiff --git a/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/IfElseWrappingRule.kt b/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/IfElseWrappingRule.kt\nindex 05bd9d2593..ed08a29167 100644\n--- a/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/IfElseWrappingRule.kt\n+++ b/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/IfElseWrappingRule.kt\n@@ -6,6 +6,7 @@ import com.pinterest.ktlint.rule.engine.core.api.ElementType.ELSE_KEYWORD\n import com.pinterest.ktlint.rule.engine.core.api.ElementType.IF\n import com.pinterest.ktlint.rule.engine.core.api.ElementType.IF_KEYWORD\n import com.pinterest.ktlint.rule.engine.core.api.ElementType.LBRACE\n+import com.pinterest.ktlint.rule.engine.core.api.ElementType.RBRACE\n import com.pinterest.ktlint.rule.engine.core.api.ElementType.THEN\n import com.pinterest.ktlint.rule.engine.core.api.IndentConfig\n import com.pinterest.ktlint.rule.engine.core.api.Rule\n@@ -16,15 +17,20 @@ import com.pinterest.ktlint.rule.engine.core.api.children\n import com.pinterest.ktlint.rule.engine.core.api.editorconfig.EditorConfig\n import com.pinterest.ktlint.rule.engine.core.api.editorconfig.INDENT_SIZE_PROPERTY\n import com.pinterest.ktlint.rule.engine.core.api.editorconfig.INDENT_STYLE_PROPERTY\n+import com.pinterest.ktlint.rule.engine.core.api.indent\n import com.pinterest.ktlint.rule.engine.core.api.isPartOfComment\n+import com.pinterest.ktlint.rule.engine.core.api.isWhiteSpaceWithNewline\n import com.pinterest.ktlint.rule.engine.core.api.isWhiteSpaceWithoutNewline\n import com.pinterest.ktlint.rule.engine.core.api.nextCodeLeaf\n import com.pinterest.ktlint.rule.engine.core.api.nextLeaf\n+import com.pinterest.ktlint.rule.engine.core.api.nextSibling\n import com.pinterest.ktlint.rule.engine.core.api.prevCodeLeaf\n+import com.pinterest.ktlint.rule.engine.core.api.prevLeaf\n import com.pinterest.ktlint.rule.engine.core.api.upsertWhitespaceBeforeMe\n import com.pinterest.ktlint.ruleset.standard.StandardRule\n import org.jetbrains.kotlin.com.intellij.lang.ASTNode\n import org.jetbrains.kotlin.psi.psiUtil.parents\n+import org.jetbrains.kotlin.utils.addToStdlib.applyIf\n \n /**\n * Enforce that single line if statements are kept simple. A single line if statement is allowed only when it has at most one else branch.\n@@ -139,24 +145,44 @@ public class IfElseWrappingRule :\n }\n \n with(node.findFirstNodeInBlockToBeIndented() ?: node) {\n- val expectedIndent = indentConfig.siblingIndentOf(node)\n- if (text != expectedIndent) {\n- emit(startOffset, \"Expected a newline\", true)\n- if (autoCorrect) {\n- upsertWhitespaceBeforeMe(expectedIndent)\n+ val expectedIndent =\n+ if (nextSibling()?.elementType == RBRACE) {\n+ node.indent()\n+ } else {\n+ indentConfig.siblingIndentOf(node)\n+ }\n+\n+ applyIf(elementType == THEN || elementType == ELSE || elementType == ELSE_KEYWORD) { prevLeaf()!! }\n+ .takeUnless { it.isWhiteSpaceWithNewline() }\n+ ?.let {\n+ // Expected a newline with indent. Leave it up to the IndentationRule to determine exact indent\n+ emit(startOffset, \"Expected a newline\", true)\n+ if (autoCorrect) {\n+ upsertWhitespaceBeforeMe(expectedIndent)\n+ }\n }\n- }\n }\n }\n \n- private fun ASTNode.findFirstNodeInBlockToBeIndented() =\n- findChildByType(BLOCK)\n+// private fun ASTNode.findFirstNodeInBlockToBeIndented(): ASTNode? {\n+// val blockOrSelf = findChildByType(BLOCK) ?: this\n+// return blockOrSelf\n+// .children()\n+// .find {\n+// it.elementType != LBRACE &&\n+// !it.isWhitespaceBeforeComment() &&\n+// !it.isPartOfComment()\n+// }\n+// }\n+ private fun ASTNode.findFirstNodeInBlockToBeIndented(): ASTNode? {\n+ return findChildByType(BLOCK)\n ?.children()\n ?.first {\n it.elementType != LBRACE &&\n !it.isWhitespaceBeforeComment() &&\n !it.isPartOfComment()\n }\n+ }\n \n private fun ASTNode.isWhitespaceBeforeComment() = isWhiteSpaceWithoutNewline() && nextLeaf()?.isPartOfComment() == true\n \ndiff --git a/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/ParameterListWrappingRule.kt b/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/ParameterListWrappingRule.kt\nindex d9c4e10cb6..6976d5f5f3 100644\n--- a/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/ParameterListWrappingRule.kt\n+++ b/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/ParameterListWrappingRule.kt\n@@ -1,11 +1,11 @@\n package com.pinterest.ktlint.ruleset.standard.rules\n \n import com.pinterest.ktlint.rule.engine.core.api.ElementType\n+import com.pinterest.ktlint.rule.engine.core.api.ElementType.FUN\n import com.pinterest.ktlint.rule.engine.core.api.ElementType.FUNCTION_LITERAL\n import com.pinterest.ktlint.rule.engine.core.api.ElementType.FUNCTION_TYPE\n import com.pinterest.ktlint.rule.engine.core.api.ElementType.LPAR\n import com.pinterest.ktlint.rule.engine.core.api.ElementType.NULLABLE_TYPE\n-import com.pinterest.ktlint.rule.engine.core.api.ElementType.PRIMARY_CONSTRUCTOR\n import com.pinterest.ktlint.rule.engine.core.api.ElementType.RPAR\n import com.pinterest.ktlint.rule.engine.core.api.ElementType.TYPE_PARAMETER_LIST\n import com.pinterest.ktlint.rule.engine.core.api.ElementType.VALUE_PARAMETER\n@@ -26,7 +26,6 @@ import com.pinterest.ktlint.rule.engine.core.api.leavesIncludingSelf\n import com.pinterest.ktlint.rule.engine.core.api.nextLeaf\n import com.pinterest.ktlint.rule.engine.core.api.prevCodeLeaf\n import com.pinterest.ktlint.rule.engine.core.api.prevLeaf\n-import com.pinterest.ktlint.rule.engine.core.api.prevSibling\n import com.pinterest.ktlint.rule.engine.core.api.upsertWhitespaceAfterMe\n import com.pinterest.ktlint.rule.engine.core.api.upsertWhitespaceBeforeMe\n import com.pinterest.ktlint.ruleset.standard.StandardRule\n@@ -34,9 +33,7 @@ import org.jetbrains.kotlin.com.intellij.lang.ASTNode\n import org.jetbrains.kotlin.com.intellij.psi.PsiWhiteSpace\n import org.jetbrains.kotlin.com.intellij.psi.impl.source.tree.LeafPsiElement\n import org.jetbrains.kotlin.com.intellij.psi.impl.source.tree.PsiWhiteSpaceImpl\n-import org.jetbrains.kotlin.psi.KtTypeArgumentList\n import org.jetbrains.kotlin.psi.psiUtil.children\n-import org.jetbrains.kotlin.psi.psiUtil.collectDescendantsOfType\n import org.jetbrains.kotlin.psi.psiUtil.leaves\n \n public class ParameterListWrappingRule :\n@@ -207,7 +204,7 @@ public class ParameterListWrappingRule :\n // param1: T\n // param2: R\n // )\n- child.treeParent.hasTypeParameterListInFront() -> -1\n+ child.treeParent.isFunWithTypeParameterListInFront() -> -1\n \n else -> 0\n }.let {\n@@ -306,20 +303,13 @@ public class ParameterListWrappingRule :\n else -> throw UnsupportedOperationException()\n }\n \n- private fun ASTNode.hasTypeParameterListInFront(): Boolean {\n- val parent = this.treeParent\n- val typeParameterList =\n- if (parent.elementType == PRIMARY_CONSTRUCTOR) {\n- parent.prevSibling { it.elementType == TYPE_PARAMETER_LIST }\n- } else {\n- parent.children().firstOrNull { it.elementType == TYPE_PARAMETER_LIST }\n- }\n- val typeListNode =\n- typeParameterList\n- ?: parent.psi.collectDescendantsOfType().firstOrNull()?.node\n- ?: return false\n- return typeListNode.children().any { it.isWhiteSpaceWithNewline() }\n- }\n+ private fun ASTNode.isFunWithTypeParameterListInFront() =\n+ treeParent\n+ .takeIf { elementType == FUN }\n+ ?.findChildByType(TYPE_PARAMETER_LIST)\n+ ?.children()\n+ ?.any { it.isWhiteSpaceWithNewline() }\n+ ?: false\n }\n \n public val PARAMETER_LIST_WRAPPING_RULE_ID: RuleId = ParameterListWrappingRule().ruleId\ndiff --git a/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/StringTemplateIndentRule.kt b/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/StringTemplateIndentRule.kt\nindex 78ba388e0c..2e8592e213 100644\n--- a/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/StringTemplateIndentRule.kt\n+++ b/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/StringTemplateIndentRule.kt\n@@ -212,7 +212,7 @@ public class StringTemplateIndentRule :\n }\n if (currentIndent.contains(wrongIndentChar)) {\n checkAndFixWrongIndentationChar(\n- it = it,\n+ node = it,\n oldIndent = currentIndent,\n newIndent = newIndent,\n newContent = currentContent,\n@@ -249,15 +249,15 @@ public class StringTemplateIndentRule :\n true,\n )\n if (autoCorrect) {\n- (firstNodeAfterOpeningQuotes as LeafPsiElement).rawReplaceWithText(\n- \"\\n\" + indent + firstNodeAfterOpeningQuotes.text,\n+ (firstNodeAfterOpeningQuotes as LeafPsiElement).rawInsertBeforeMe(\n+ LeafPsiElement(REGULAR_STRING_PART, \"\\n\" + indent),\n )\n }\n }\n }\n \n private fun checkAndFixWrongIndentationChar(\n- it: ASTNode,\n+ node: ASTNode,\n oldIndent: String,\n newIndent: String,\n newContent: String,\n@@ -265,12 +265,12 @@ public class StringTemplateIndentRule :\n autoCorrect: Boolean,\n ) {\n emit(\n- it.startOffset + oldIndent.indexOf(wrongIndentChar),\n+ node.startOffset + oldIndent.indexOf(wrongIndentChar),\n \"Unexpected '$wrongIndentDescription' character(s) in margin of multiline string\",\n true,\n )\n if (autoCorrect) {\n- (it.firstChildNode as LeafPsiElement).rawReplaceWithText(\n+ (node.firstChildNode as LeafPsiElement).rawReplaceWithText(\n newIndent + newContent,\n )\n }\n@@ -316,8 +316,8 @@ public class StringTemplateIndentRule :\n true,\n )\n if (autoCorrect) {\n- (lastNodeBeforeClosingQuotes as LeafPsiElement).rawReplaceWithText(\n- lastNodeBeforeClosingQuotes.text + \"\\n\" + indent,\n+ (lastNodeBeforeClosingQuotes as LeafPsiElement).rawInsertAfterMe(\n+ LeafPsiElement(REGULAR_STRING_PART, \"\\n\" + indent),\n )\n }\n }\ndiff --git a/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/WrappingRule.kt b/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/WrappingRule.kt\nindex 244ea97667..784a18ed0b 100644\n--- a/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/WrappingRule.kt\n+++ b/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/WrappingRule.kt\n@@ -54,6 +54,7 @@ import com.pinterest.ktlint.rule.engine.core.api.editorconfig.INDENT_STYLE_PROPE\n import com.pinterest.ktlint.rule.engine.core.api.editorconfig.MAX_LINE_LENGTH_PROPERTY\n import com.pinterest.ktlint.rule.engine.core.api.editorconfig.MAX_LINE_LENGTH_PROPERTY_OFF\n import com.pinterest.ktlint.rule.engine.core.api.firstChildLeafOrSelf\n+import com.pinterest.ktlint.rule.engine.core.api.hasNewLineInClosedRange\n import com.pinterest.ktlint.rule.engine.core.api.indent\n import com.pinterest.ktlint.rule.engine.core.api.isPartOf\n import com.pinterest.ktlint.rule.engine.core.api.isPartOfComment\n@@ -151,53 +152,53 @@ public class WrappingRule :\n ) {\n require(node.elementType == BLOCK)\n \n- val startOfBlock = node.prevLeaf { !it.isPartOfComment() && !it.isWhiteSpace() }\n- if (startOfBlock?.elementType != LBRACE) {\n+ val lbrace =\n+ node\n+ .getStartOfBlock()\n+ ?.takeIf { it.elementType == LBRACE }\n+ ?: return\n+ if (lbrace.followedByNewline() ||\n+ lbrace.followedByEolComment() ||\n+ lbrace.isPartOf(LONG_STRING_TEMPLATE_ENTRY)\n+ ) {\n+ // String template inside raw string literal may exceed the maximum line length\n return\n }\n- val blockIsPrecededByWhitespaceContainingNewline = startOfBlock.nextLeaf().isWhiteSpaceWithNewline()\n- val endOfBlock = node.lastChildLeafOrSelf().nextLeaf { !it.isPartOfComment() && !it.isWhiteSpace() }\n- val blockIsFollowedByWhitespaceContainingNewline = endOfBlock?.prevLeaf().isWhiteSpaceWithNewline()\n- val wrapBlock =\n- when {\n- startOfBlock.isPartOf(LONG_STRING_TEMPLATE_ENTRY) -> {\n- // String template inside raw string literal may exceed the maximum line length\n- false\n- }\n- blockIsPrecededByWhitespaceContainingNewline -> false\n- node.textContains('\\n') || blockIsFollowedByWhitespaceContainingNewline -> {\n- // A multiline block should always be wrapped unless it starts with an EOL comment\n- node.firstChildLeafOrSelf().elementType != EOL_COMMENT\n- }\n- maxLineLength != MAX_LINE_LENGTH_PROPERTY_OFF -> {\n- val lengthUntilBeginOfLine =\n- node\n- .leaves(false)\n- .takeWhile { !it.isWhiteSpaceWithNewline() }\n- .sumOf { it.textLength }\n- val lengthUntilEndOfLine =\n- node\n- .firstChildLeafOrSelf()\n- .leavesIncludingSelf()\n- .takeWhile { !it.isWhiteSpaceWithNewline() }\n- .sumOf { it.textLength }\n- lengthUntilBeginOfLine + lengthUntilEndOfLine > maxLineLength\n+\n+ node\n+ .takeUnless { it.firstChildLeafOrSelf().elementType == EOL_COMMENT }\n+ ?.getEndOfBlock()\n+ ?.takeIf { it.elementType == RBRACE }\n+ ?.let { rbrace ->\n+ if (hasNewLineInClosedRange(lbrace, rbrace)) {\n+ requireNewlineAfterLeaf(lbrace, autoCorrect, emit)\n }\n- else -> false\n }\n- if (wrapBlock) {\n- startOfBlock\n- .takeIf { !it.nextLeaf().isWhiteSpaceWithNewline() }\n- ?.let { leafNodeBeforeBlock ->\n- requireNewlineAfterLeaf(\n- leafNodeBeforeBlock,\n- autoCorrect,\n- emit,\n- )\n- }\n+\n+ if (maxLineLength != MAX_LINE_LENGTH_PROPERTY_OFF) {\n+ val lengthUntilBeginOfLine =\n+ node\n+ .leaves(false)\n+ .takeWhile { !it.isWhiteSpaceWithNewline() }\n+ .sumOf { it.textLength }\n+ val lengthUntilEndOfLine =\n+ node\n+ .firstChildLeafOrSelf()\n+ .leavesIncludingSelf()\n+ .takeWhile { !it.isWhiteSpaceWithNewline() }\n+ .sumOf { it.textLength }\n+ if (lengthUntilBeginOfLine + lengthUntilEndOfLine > maxLineLength) {\n+ requireNewlineAfterLeaf(lbrace, autoCorrect, emit)\n+ }\n }\n }\n \n+ private fun ASTNode.followedByEolComment() =\n+ null !=\n+ leaves()\n+ .takeWhile { it.isWhiteSpaceWithoutNewline() || it.elementType == EOL_COMMENT }\n+ .firstOrNull { it.elementType == EOL_COMMENT }\n+\n private fun rearrangeBlock(\n node: ASTNode,\n autoCorrect: Boolean,\n@@ -546,7 +547,18 @@ public class WrappingRule :\n return\n }\n if (noNewLineInClosedRange(previousCodeLeaf, nextCodeLeaf)) {\n- requireNewlineAfterLeaf(node, autoCorrect, emit, indent = previousCodeLeaf.indent())\n+ requireNewlineAfterLeaf(node, autoCorrect, emit, previousCodeLeaf.indent())\n+ node\n+ .treeParent\n+ .takeIf { it.elementType == BLOCK }\n+ ?.let { block ->\n+ beforeVisitBlock(block, autoCorrect, emit)\n+ block\n+ .treeParent\n+ .takeIf { it.elementType == FUNCTION_LITERAL }\n+ ?.findChildByType(ARROW)\n+ ?.let { arrow -> rearrangeArrow(arrow, autoCorrect, emit) }\n+ }\n }\n }\n \n@@ -659,28 +671,55 @@ public class WrappingRule :\n emit: (offset: Int, errorMessage: String, canBeAutoCorrected: Boolean) -> Unit,\n ) {\n if (node.elementType == BLOCK) {\n- val startOfBlock = node.prevLeaf { !it.isPartOfComment() && !it.isWhiteSpace() }\n- if (startOfBlock?.elementType != LBRACE) {\n- return\n- }\n- val blockIsPrecededByWhitespaceContainingNewline = startOfBlock.nextLeaf().isWhiteSpaceWithNewline()\n- val endOfBlock = node.lastChildLeafOrSelf().nextLeaf { !it.isPartOfComment() && !it.isWhiteSpace() }\n- val blockIsFollowedByWhitespaceContainingNewline = endOfBlock?.prevLeaf().isWhiteSpaceWithNewline()\n- val wrapBlock =\n- !blockIsFollowedByWhitespaceContainingNewline && (\n- blockIsPrecededByWhitespaceContainingNewline || node.textContains('\\n')\n- )\n- if (wrapBlock && endOfBlock != null) {\n- requireNewlineBeforeLeaf(\n- endOfBlock,\n- autoCorrect,\n- emit,\n- indentConfig.parentIndentOf(node),\n- )\n- }\n+ val lbrace =\n+ node\n+ .getStartOfBlock()\n+ ?.takeIf { it.elementType == LBRACE }\n+ ?: return\n+ node\n+ .getEndOfBlock()\n+ ?.takeUnless { it.isPrecededByNewline() }\n+ ?.let { rbrace ->\n+ if (hasNewLineInClosedRange(lbrace, rbrace)) {\n+ requireNewlineBeforeLeaf(\n+ rbrace,\n+ autoCorrect,\n+ emit,\n+ indentConfig.parentIndentOf(node),\n+ )\n+ }\n+ }\n }\n }\n \n+ private fun ASTNode.followedByNewline() = nextLeaf().isWhiteSpaceWithNewline()\n+\n+ private fun ASTNode.isPrecededByNewline() = prevLeaf().isWhiteSpaceWithNewline()\n+\n+ private fun ASTNode.getStartOfBlock() =\n+ firstChildLeafOrSelf()\n+ .let { node ->\n+ if (node.elementType == LBRACE) {\n+ // WHEN-entry block have LBRACE and RBRACE as first and last elements\n+ node\n+ } else {\n+ // Other blocks have LBRACE and RBRACE as siblings of the block\n+ node.prevLeaf { !it.isPartOfComment() && !it.isWhiteSpace() }\n+ }\n+ }\n+\n+ private fun ASTNode.getEndOfBlock() =\n+ lastChildLeafOrSelf()\n+ .let { node ->\n+ if (node.elementType == RBRACE && treeParent.elementType != FUNCTION_LITERAL) {\n+ // WHEN-entry block have LBRACE and RBRACE as first and last elements\n+ node\n+ } else {\n+ // Other blocks have LBRACE and RBRACE as siblings of the block\n+ node.nextLeaf { !it.isPartOfComment() && !it.isWhiteSpace() }\n+ }\n+ }\n+\n private companion object {\n private val LTOKEN_SET = TokenSet.create(LPAR, LBRACE, LBRACKET, LT)\n private val RTOKEN_SET = TokenSet.create(RPAR, RBRACE, RBRACKET, GT)\n", "test_patch": "diff --git a/ktlint-rule-engine-core/src/test/kotlin/com/pinterest/ktlint/rule/engine/core/api/ASTNodeExtensionTest.kt b/ktlint-rule-engine-core/src/test/kotlin/com/pinterest/ktlint/rule/engine/core/api/ASTNodeExtensionTest.kt\nindex 2a37627b9b..c9c141d88f 100644\n--- a/ktlint-rule-engine-core/src/test/kotlin/com/pinterest/ktlint/rule/engine/core/api/ASTNodeExtensionTest.kt\n+++ b/ktlint-rule-engine-core/src/test/kotlin/com/pinterest/ktlint/rule/engine/core/api/ASTNodeExtensionTest.kt\n@@ -516,6 +516,68 @@ class ASTNodeExtensionTest {\n )\n }\n \n+ @Test\n+ fun `Given some line containing identifiers at different indentation levels then check that all leaves on those line are found`() {\n+ val code =\n+ \"\"\"\n+ class Foo1 {\n+ val foo2 = \"foo2\"\n+\n+ fun foo3() {\n+ val foo4 = \"foo4\"\n+ }\n+ }\n+ \"\"\".trimIndent()\n+\n+ val actual =\n+ transformCodeToAST(code)\n+ .firstChildLeafOrSelf()\n+ .leaves()\n+ .filter { it.elementType == IDENTIFIER }\n+ .map { identifier ->\n+ identifier\n+ .leavesOnLine()\n+ .joinToString(separator = \"\") { it.text }\n+ }.toList()\n+\n+ assertThat(actual).contains(\n+ \"class Foo1 {\",\n+ \"\\n val foo2 = \\\"foo2\\\"\",\n+ \"\\n\\n fun foo3() {\",\n+ \"\\n val foo4 = \\\"foo4\\\"\",\n+ )\n+ }\n+\n+ @Test\n+ fun `Given some line containing identifiers at different indentation levels then get line length exclusive the leading newline characters`() {\n+ val code =\n+ \"\"\"\n+ class Foo1 {\n+ val foo2 = \"foo2\"\n+\n+ fun foo3() {\n+ val foo4 = \"foo4\"\n+ }\n+ }\n+ \"\"\".trimIndent()\n+\n+ val actual =\n+ transformCodeToAST(code)\n+ .firstChildLeafOrSelf()\n+ .leaves()\n+ .filter { it.elementType == IDENTIFIER }\n+ .map { newLine ->\n+ newLine.lineLengthWithoutNewlinePrefix()\n+ }.toList()\n+\n+ assertThat(actual).contains(\n+ \"class Foo1 {\".length,\n+ \" val foo2 = \\\"foo2\\\"\".length,\n+ \" fun foo3() {\".length,\n+ \" val foo4 = \\\"foo4\\\"\".length,\n+ )\n+ }\n+\n private inline fun String.transformAst(block: FileASTNode.() -> Unit): FileASTNode =\n transformCodeToAST(this)\n .apply(block)\ndiff --git a/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/ArgumentListWrappingRuleTest.kt b/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/ArgumentListWrappingRuleTest.kt\nindex 0d852d657f..3309c6fdd4 100644\n--- a/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/ArgumentListWrappingRuleTest.kt\n+++ b/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/ArgumentListWrappingRuleTest.kt\n@@ -576,7 +576,7 @@ class ArgumentListWrappingRuleTest {\n \"\"\".trimIndent()\n argumentListWrappingRuleAssertThat(code)\n // TODO:to be fixed by https://github.com/pinterest/ktlint/issues/1861\n- .withEditorConfigOverride(MAX_LINE_LENGTH_PROPERTY to 44)\n+ .withEditorConfigOverride(MAX_LINE_LENGTH_PROPERTY to 45)\n .hasNoLintViolations()\n }\n \n@@ -839,4 +839,23 @@ class ArgumentListWrappingRuleTest {\n )\n .isFormattedAs(formattedCode)\n }\n+\n+ @Test\n+ fun `Given a property assignment with a binary expression for which the left hand side operator is a function call`() {\n+ val code =\n+ \"\"\"\n+ // $MAX_LINE_LENGTH_MARKER $EOL_CHAR\n+ val foo1 = foobar(foo * bar) + \"foo\"\n+ val foo2 = foobar(\"foo\", foo * bar) + \"foo\"\n+ val foo3 = foobar(\"fooo\", foo * bar) + \"foo\"\n+ \"\"\".trimIndent()\n+ argumentListWrappingRuleAssertThat(code)\n+ .setMaxLineLength()\n+ .addAdditionalRuleProvider { BinaryExpressionWrappingRule() }\n+ .addAdditionalRuleProvider { WrappingRule() }\n+ // Although the argument-list-wrapping runs before binary-expression-wrapping, it may not wrap the argument values of a\n+ // function call in case that call is part of a binary expression. It might be better to break the line at the operation\n+ // reference instead.\n+ .hasNoLintViolationsExceptInAdditionalRules()\n+ }\n }\ndiff --git a/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/BinaryExpressionWrappingRuleTest.kt b/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/BinaryExpressionWrappingRuleTest.kt\nindex 802f748daa..c8e3a9f774 100644\n--- a/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/BinaryExpressionWrappingRuleTest.kt\n+++ b/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/BinaryExpressionWrappingRuleTest.kt\n@@ -4,6 +4,7 @@ import com.pinterest.ktlint.test.KtLintAssertThat\n import com.pinterest.ktlint.test.KtLintAssertThat.Companion.EOL_CHAR\n import com.pinterest.ktlint.test.KtLintAssertThat.Companion.MAX_LINE_LENGTH_MARKER\n import com.pinterest.ktlint.test.LintViolation\n+import com.pinterest.ktlint.test.MULTILINE_STRING_QUOTE\n import org.junit.jupiter.api.Test\n \n class BinaryExpressionWrappingRuleTest {\n@@ -28,7 +29,7 @@ class BinaryExpressionWrappingRuleTest {\n LintViolation(2, 11, \"Line is exceeding max line length. Break line between assignment and expression\"),\n // Next violation only happens during linting. When formatting the violation does not occur because fix of previous\n // violation prevent that the remainder of the line exceeds the maximum\n- LintViolation(2, 36, \"Line is exceeding max line length. Break line after operator of binary expression\"),\n+ LintViolation(2, 36, \"Line is exceeding max line length. Break line after operator in binary expression\"),\n ).isFormattedAs(formattedCode)\n }\n \n@@ -49,7 +50,7 @@ class BinaryExpressionWrappingRuleTest {\n \"\"\".trimIndent()\n binaryExpressionWrappingRuleAssertThat(code)\n .setMaxLineLength()\n- .hasLintViolation(3, 30, \"Line is exceeding max line length. Break line after operator of binary expression\")\n+ .hasLintViolation(3, 30, \"Line is exceeding max line length. Break line after operator in binary expression\")\n .isFormattedAs(formattedCode)\n }\n \n@@ -72,7 +73,7 @@ class BinaryExpressionWrappingRuleTest {\n \"\"\".trimIndent()\n binaryExpressionWrappingRuleAssertThat(code)\n .setMaxLineLength()\n- .hasLintViolation(3, 37, \"Line is exceeding max line length. Break line after operator of binary expression\")\n+ .hasLintViolation(3, 37, \"Line is exceeding max line length. Break line after operator in binary expression\")\n .isFormattedAs(formattedCode)\n }\n \n@@ -95,7 +96,7 @@ class BinaryExpressionWrappingRuleTest {\n LintViolation(2, 13, \"Line is exceeding max line length. Break line between assignment and expression\"),\n // Next violation only happens during linting. When formatting the violation does not occur because fix of previous\n // violation prevent that the remainder of the line exceeds the maximum\n- LintViolation(2, 38, \"Line is exceeding max line length. Break line after operator of binary expression\"),\n+ LintViolation(2, 38, \"Line is exceeding max line length. Break line after operator in binary expression\"),\n ).isFormattedAs(formattedCode)\n }\n \n@@ -116,7 +117,7 @@ class BinaryExpressionWrappingRuleTest {\n \"\"\".trimIndent()\n binaryExpressionWrappingRuleAssertThat(code)\n .setMaxLineLength()\n- .hasLintViolation(3, 30, \"Line is exceeding max line length. Break line after operator of binary expression\")\n+ .hasLintViolation(3, 30, \"Line is exceeding max line length. Break line after operator in binary expression\")\n .isFormattedAs(formattedCode)\n }\n \n@@ -143,7 +144,7 @@ class BinaryExpressionWrappingRuleTest {\n \"\"\".trimIndent()\n binaryExpressionWrappingRuleAssertThat(code)\n .setMaxLineLength()\n- .hasLintViolation(3, 34, \"Line is exceeding max line length. Break line after operator of binary expression\")\n+ .hasLintViolation(3, 34, \"Line is exceeding max line length. Break line after operator in binary expression\")\n .isFormattedAs(formattedCode)\n }\n \n@@ -174,9 +175,9 @@ class BinaryExpressionWrappingRuleTest {\n .hasLintViolations(\n // When linting, a violation is reported for each operation reference. While when formatting, the nested binary expression\n // is evaluated (working from outside to inside). After wrapping an outer binary expression, the inner binary expressions\n- // are evaluated and only when needed wrapped again at the operation reference.\n- LintViolation(3, 35, \"Line is exceeding max line length. Break line after operator of binary expression\"),\n- LintViolation(3, 63, \"Line is exceeding max line length. Break line after operator of binary expression\"),\n+ // are evaluated and only wrapped again at the operation reference when needed.\n+ LintViolation(3, 35, \"Line is exceeding max line length. Break line after operator in binary expression\"),\n+ LintViolation(3, 63, \"Line is exceeding max line length. Break line after operator in binary expression\"),\n LintViolation(3, 92, \"Line is exceeding max line length\", canBeAutoCorrected = false),\n ).isFormattedAs(formattedCode)\n }\n@@ -195,4 +196,117 @@ class BinaryExpressionWrappingRuleTest {\n .setMaxLineLength()\n .hasLintViolationWithoutAutoCorrect(3, 36, \"Line is exceeding max line length\")\n }\n+\n+ @Test\n+ fun `Given a binary expression for which wrapping of the operator reference would still violates the max-line-length`() {\n+ val code =\n+ \"\"\"\n+ // $MAX_LINE_LENGTH_MARKER $EOL_CHAR\n+ val foo1 = foo() ?: \"fooooooooooo\" +\n+ \"bar\"\n+ // Do not remove blank line below, it is relevant as both the newline of the blank line and the indent before property foo2 have to be accounted for\n+\n+ val foo2 = foo() ?: \"foooooooooo\" +\n+ \"bar\"\n+ \"\"\".trimIndent()\n+ binaryExpressionWrappingRuleAssertThat(code)\n+ .setMaxLineLength()\n+ .hasLintViolationsWithoutAutoCorrect(\n+ LintViolation(2, 12, \"Line is exceeding max line length. Break line between assignment and expression\"),\n+ LintViolation(2, 20, \"Line is exceeding max line length. Break line after operator in binary expression\"),\n+ LintViolation(2, 36, \"Line is exceeding max line length\"),\n+ )\n+ }\n+\n+ @Test\n+ fun `Given a binary expression inside a raw string literal then do not wrap it`() {\n+ val code =\n+ \"\"\"\n+ // $MAX_LINE_LENGTH_MARKER $EOL_CHAR\n+ val foo =\n+ $MULTILINE_STRING_QUOTE\n+ foooooooooooooo ${'$'}{bar * bar - 123}\n+ $MULTILINE_STRING_QUOTE\n+ \"\"\".trimIndent()\n+ binaryExpressionWrappingRuleAssertThat(code)\n+ .setMaxLineLength()\n+ .hasNoLintViolations()\n+ }\n+\n+ @Test\n+ fun `Given a value argument containing a binary expression`() {\n+ val code =\n+ \"\"\"\n+ // $MAX_LINE_LENGTH_MARKER $EOL_CHAR\n+ val foobar = Foo(bar(1 * 2 * 3))\n+ \"\"\".trimIndent()\n+ val formattedCode =\n+ \"\"\"\n+ // $MAX_LINE_LENGTH_MARKER $EOL_CHAR\n+ val foobar = Foo(\n+ bar(1 * 2 * 3)\n+ )\n+ \"\"\".trimIndent()\n+ binaryExpressionWrappingRuleAssertThat(code)\n+ .addAdditionalRuleProvider { ArgumentListWrappingRule() }\n+ .addAdditionalRuleProvider { WrappingRule() }\n+ .setMaxLineLength()\n+ .hasLintViolations(\n+ // Although violations below are reported by the Linter, they will not be enforced by the formatter. After the\n+ // ArgumentListWrapping rule has wrapped the argument, there is no more need to wrap the expression as well.\n+ LintViolation(2, 25, \"Line is exceeding max line length. Break line after operator in binary expression\"),\n+ LintViolation(2, 29, \"Line is exceeding max line length. Break line after operator in binary expression\"),\n+ )\n+ .hasLintViolationsForAdditionalRules(\n+ LintViolation(2, 18, \"Argument should be on a separate line (unless all arguments can fit a single line)\"),\n+ LintViolation(2, 22, \"Argument should be on a separate line (unless all arguments can fit a single line)\"),\n+ LintViolation(2, 31, \"Missing newline before \\\")\\\"\"),\n+ LintViolation(2, 32, \"Missing newline before \\\")\\\"\"),\n+ ).isFormattedAs(formattedCode)\n+ }\n+\n+ @Test\n+ fun `Given a property assignment with a binary expression for which the left hand side operator is a function call`() {\n+ val code =\n+ \"\"\"\n+ // $MAX_LINE_LENGTH_MARKER $EOL_CHAR\n+ val foo1 = foobar(foo * bar) + \"foo\"\n+ val foo2 = foobar(\"foo\", foo * bar) + \"foo\"\n+ val foo3 = foobar(\"fooo\", foo * bar) + \"foo\"\n+ \"\"\".trimIndent()\n+ val formattedCode =\n+ \"\"\"\n+ // $MAX_LINE_LENGTH_MARKER $EOL_CHAR\n+ val foo1 = foobar(foo * bar) + \"foo\"\n+ val foo2 =\n+ foobar(\"foo\", foo * bar) + \"foo\"\n+ val foo3 =\n+ foobar(\"fooo\", foo * bar) +\n+ \"foo\"\n+ \"\"\".trimIndent()\n+ binaryExpressionWrappingRuleAssertThat(code)\n+ .setMaxLineLength()\n+ .addAdditionalRuleProvider { ArgumentListWrappingRule() }\n+ .addAdditionalRuleProvider { WrappingRule() }\n+ // Although the argument-list-wrapping runs before binary-expression-wrapping, it may not wrap the argument values of a\n+ // function call in case that call is part of a binary expression. It might be better to break the line at the operation\n+ // reference instead.\n+ .isFormattedAs(formattedCode)\n+ }\n+\n+ @Test\n+ fun `Given a call expression followed by lambda argument`() {\n+ val code =\n+ \"\"\"\n+ // $MAX_LINE_LENGTH_MARKER $EOL_CHAR\n+ fun foo() {\n+ require(bar != \"bar\") { \"some longgggggggggggggggggg message\" }\n+ }\n+ \"\"\".trimIndent()\n+ binaryExpressionWrappingRuleAssertThat(code)\n+ .setMaxLineLength()\n+ .addAdditionalRuleProvider { ArgumentListWrappingRule() }\n+ .addAdditionalRuleProvider { WrappingRule() }\n+ .hasLintViolationWithoutAutoCorrect(3, 17, \"Line is exceeding max line length\")\n+ }\n }\ndiff --git a/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/BlankLineBeforeDeclarationRuleTest.kt b/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/BlankLineBeforeDeclarationRuleTest.kt\nindex b9dbe531ea..77702f4986 100644\n--- a/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/BlankLineBeforeDeclarationRuleTest.kt\n+++ b/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/BlankLineBeforeDeclarationRuleTest.kt\n@@ -4,6 +4,7 @@ import com.pinterest.ktlint.rule.engine.core.api.editorconfig.CODE_STYLE_PROPERT\n import com.pinterest.ktlint.rule.engine.core.api.editorconfig.CodeStyleValue\n import com.pinterest.ktlint.test.KtLintAssertThat\n import com.pinterest.ktlint.test.LintViolation\n+import org.junit.jupiter.api.Nested\n import org.junit.jupiter.api.Test\n \n class BlankLineBeforeDeclarationRuleTest {\n@@ -244,15 +245,77 @@ class BlankLineBeforeDeclarationRuleTest {\n .hasNoLintViolations()\n }\n \n- @Test\n- fun `Given a function as first code sibling inside a class body then do not insert a blank line between the class signature and this function`() {\n- val code =\n- \"\"\"\n- class Foo {\n- fun Bar() {}\n- }\n- \"\"\".trimIndent()\n- blankLineBeforeDeclarationRuleAssertThat(code).hasNoLintViolations()\n+ @Nested\n+ inner class `Given some nested declaration` {\n+ @Test\n+ fun `Given a class as first code sibling inside a class body then do not insert a blank line between the class signature and this function`() {\n+ val code =\n+ \"\"\"\n+ class Foo {\n+ class Bar\n+ }\n+ \"\"\".trimIndent()\n+ blankLineBeforeDeclarationRuleAssertThat(code).hasNoLintViolations()\n+ }\n+\n+ @Test\n+ fun `Given a function as first code sibling inside a class body then do not insert a blank line between the class signature and this function`() {\n+ val code =\n+ \"\"\"\n+ class Foo {\n+ fun bar() {}\n+ }\n+ \"\"\".trimIndent()\n+ blankLineBeforeDeclarationRuleAssertThat(code).hasNoLintViolations()\n+ }\n+\n+ @Test\n+ fun `Given a class as first code sibling inside a function body then do not insert a blank line between the class signature and this function`() {\n+ val code =\n+ \"\"\"\n+ fun foo() {\n+ class Bar\n+ }\n+ \"\"\".trimIndent()\n+ blankLineBeforeDeclarationRuleAssertThat(code).hasNoLintViolations()\n+ }\n+\n+ @Test\n+ fun `Given a function as first code sibling inside a function body then do not insert a blank line between the class signature and this function`() {\n+ val code =\n+ \"\"\"\n+ fun foo() {\n+ fun bar() {}\n+ }\n+ \"\"\".trimIndent()\n+ blankLineBeforeDeclarationRuleAssertThat(code).hasNoLintViolations()\n+ }\n+\n+ @Test\n+ fun `Given a function as first code sibling inside a function literal without parameters then do not insert a blank line the declaration`() {\n+ val code =\n+ \"\"\"\n+ val foo = {\n+ fun bar() {}\n+\n+ bar()\n+ }\n+ \"\"\".trimIndent()\n+ blankLineBeforeDeclarationRuleAssertThat(code).hasNoLintViolations()\n+ }\n+\n+ @Test\n+ fun `Given a function as first code sibling inside a function literal with parameters then do not insert a blank line the declaration`() {\n+ val code =\n+ \"\"\"\n+ val foo = { _ ->\n+ fun bar() {}\n+\n+ bar()\n+ }\n+ \"\"\".trimIndent()\n+ blankLineBeforeDeclarationRuleAssertThat(code).hasNoLintViolations()\n+ }\n }\n \n @Test\n@@ -284,17 +347,6 @@ class BlankLineBeforeDeclarationRuleTest {\n blankLineBeforeDeclarationRuleAssertThat(code).hasNoLintViolations()\n }\n \n- @Test\n- fun `xx`() {\n- val code =\n- \"\"\"\n- fun foo(\n- emit: (offset: Int, errorMessage: String, canBeAutoCorrected: Boolean) -> Unit,\n- ) {}\n- \"\"\".trimIndent()\n- blankLineBeforeDeclarationRuleAssertThat(code).hasNoLintViolations()\n- }\n-\n @Test\n fun `Given some consecutive declarations`() {\n val code =\n@@ -343,4 +395,56 @@ class BlankLineBeforeDeclarationRuleTest {\n LintViolation(12, 5, \"Expected a blank line for this declaration\"),\n ).isFormattedAs(formattedCode)\n }\n+\n+ @Test\n+ fun `Given a class followed by EOL comment followed by a class`() {\n+ val code =\n+ \"\"\"\n+ class Foo\n+ // Some comment\n+\n+ class Bar\n+ \"\"\".trimIndent()\n+ blankLineBeforeDeclarationRuleAssertThat(code).hasNoLintViolations()\n+ }\n+\n+ @Test\n+ fun `Given a when statement with a property declaration`() {\n+ val code =\n+ \"\"\"\n+ val foo =\n+ when (val foobar = FooBar()) {\n+ is Bar -> foobar.bar()\n+ is Foo -> foobar.foo()\n+ else -> foobar\n+ }\n+ \"\"\".trimIndent()\n+ blankLineBeforeDeclarationRuleAssertThat(code).hasNoLintViolations()\n+ }\n+\n+ @Test\n+ fun `Given a class with a class initializer after another declaration`() {\n+ val code =\n+ \"\"\"\n+ class Foo {\n+ val foo = \"foo\"\n+ init {\n+ // do something\n+ }\n+ }\n+ \"\"\".trimIndent()\n+ val formattedCode =\n+ \"\"\"\n+ class Foo {\n+ val foo = \"foo\"\n+\n+ init {\n+ // do something\n+ }\n+ }\n+ \"\"\".trimIndent()\n+ blankLineBeforeDeclarationRuleAssertThat(code)\n+ .hasLintViolation(3, 5, \"Expected a blank line for this declaration\")\n+ .isFormattedAs(formattedCode)\n+ }\n }\ndiff --git a/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/IfElseWrappingRuleTest.kt b/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/IfElseWrappingRuleTest.kt\nindex 4c5c6e52dc..b1b46d65f9 100644\n--- a/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/IfElseWrappingRuleTest.kt\n+++ b/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/IfElseWrappingRuleTest.kt\n@@ -208,4 +208,34 @@ class IfElseWrappingRuleTest {\n .hasLintViolationWithoutAutoCorrect(2, 26, \"A single line if-statement should be kept simple. The 'ELSE' may not be wrapped in a block.\")\n }\n }\n+\n+ @Test\n+ fun `Given an if-else with empty branches`() {\n+ val code =\n+ \"\"\"\n+ val foo = if (true) {\n+ } else {\n+ }\n+ \"\"\".trimIndent()\n+ @Suppress(\"ktlint:argument-list-wrapping\", \"ktlint:max-line-length\")\n+ ifElseWrappingRuleAssertThat(code).hasNoLintViolations()\n+ }\n+\n+ @Test\n+ fun `Given an if-else statement inside a string template which is correctly indented then do not report a violation`() {\n+ val code =\n+ \"\"\"\n+ fun foo() {\n+ logger.log(\n+ \"<-- ${'$'}{if (true)\n+ \"\"\n+ else\n+ ' ' +\n+ \"bar\"}\",\n+ )\n+ }\n+ \"\"\".trimIndent()\n+ @Suppress(\"ktlint:argument-list-wrapping\", \"ktlint:max-line-length\")\n+ ifElseWrappingRuleAssertThat(code).hasNoLintViolations()\n+ }\n }\ndiff --git a/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/ParameterListWrappingRuleTest.kt b/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/ParameterListWrappingRuleTest.kt\nindex 911aeedb50..e8926d274e 100644\n--- a/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/ParameterListWrappingRuleTest.kt\n+++ b/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/ParameterListWrappingRuleTest.kt\n@@ -522,6 +522,20 @@ class ParameterListWrappingRuleTest {\n parameterListWrappingRuleAssertThat(code).hasNoLintViolations()\n }\n \n+ @Test\n+ fun `Given a multiline type argument list in a class property`() {\n+ val code =\n+ \"\"\"\n+ data class FooBar(\n+ public val fooBar: List<\n+ Foo,\n+ Bar\n+ >,\n+ )\n+ \"\"\".trimIndent()\n+ parameterListWrappingRuleAssertThat(code).hasNoLintViolations()\n+ }\n+\n @Nested\n inner class `Issue 1255 - Given a variable declaration for nullable function type` {\n @Test\ndiff --git a/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/WrappingRuleTest.kt b/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/WrappingRuleTest.kt\nindex b1915d06b7..0d047bed59 100644\n--- a/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/WrappingRuleTest.kt\n+++ b/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/WrappingRuleTest.kt\n@@ -2522,6 +2522,112 @@ internal class WrappingRuleTest {\n .hasNoLintViolations()\n }\n }\n+\n+ @Test\n+ fun `Given a single line block containing multiple statements then reformat block after wrapping the statement`() {\n+ val code =\n+ \"\"\"\n+ val fooBar =\n+ fooBar()\n+ .map { foo(); bar() }\n+ \"\"\".trimIndent()\n+ val formattedCode =\n+ \"\"\"\n+ val fooBar =\n+ fooBar()\n+ .map {\n+ foo()\n+ bar()\n+ }\n+ \"\"\".trimIndent()\n+ wrappingRuleAssertThat(code)\n+ .addAdditionalRuleProvider { NoSemicolonsRule() }\n+ .addAdditionalRuleProvider { IndentationRule() }\n+ .hasLintViolation(3, 22, \"Missing newline after \\\";\\\"\")\n+ .isFormattedAs(formattedCode)\n+ }\n+\n+ @Test\n+ fun `Given a single line lambda expression containing multiple statements then reformat block after wrapping the statement`() {\n+ val code =\n+ \"\"\"\n+ val fooBar =\n+ fooBar()\n+ .map { foo, bar -> print(foo); print(bar) }\n+ \"\"\".trimIndent()\n+ val formattedCode =\n+ \"\"\"\n+ val fooBar =\n+ fooBar()\n+ .map { foo, bar ->\n+ print(foo)\n+ print(bar)\n+ }\n+ \"\"\".trimIndent()\n+ wrappingRuleAssertThat(code)\n+ .addAdditionalRuleProvider { NoSemicolonsRule() }\n+ .addAdditionalRuleProvider { IndentationRule() }\n+ .hasLintViolation(3, 39, \"Missing newline after \\\";\\\"\")\n+ .isFormattedAs(formattedCode)\n+ }\n+\n+ @Test\n+ fun `Given a single line when entry block containing multiple statements then reformat block after wrapping the statement`() {\n+ val code =\n+ \"\"\"\n+ val foo =\n+ when (value) {\n+ 0 -> { foo(); true }\n+ else -> { bar(); false }\n+ }\n+ \"\"\".trimIndent()\n+ val formattedCode =\n+ \"\"\"\n+ val foo =\n+ when (value) {\n+ 0 -> {\n+ foo()\n+ true\n+ }\n+ else -> {\n+ bar()\n+ false\n+ }\n+ }\n+ \"\"\".trimIndent()\n+ wrappingRuleAssertThat(code)\n+ .addAdditionalRuleProvider { NoSemicolonsRule() }\n+ .addAdditionalRuleProvider { IndentationRule() }\n+ .hasLintViolations(\n+ LintViolation(3, 22, \"Missing newline after \\\";\\\"\"),\n+ LintViolation(4, 25, \"Missing newline after \\\";\\\"\"),\n+ ).isFormattedAs(formattedCode)\n+ }\n+ }\n+\n+ @Test\n+ fun `Given a lambda expression containing a function literal`() {\n+ val code =\n+ \"\"\"\n+ val foo = {\n+ Foo { \"foo\" }\n+ }\n+ \"\"\".trimIndent()\n+ wrappingRuleAssertThat(code).hasNoLintViolations()\n+ }\n+\n+ @Test\n+ fun `if else with comments after curly braces`() {\n+ val code =\n+ \"\"\"\n+ val foo =\n+ if (true) { // comment 1\n+ \"foo\"\n+ } else { // comment 2\n+ \"bar\"\n+ }\n+ \"\"\".trimIndent()\n+ wrappingRuleAssertThat(code).hasNoLintViolations()\n }\n }\n \n", "problem_statement": "Repeat format step until no more errors are found which can be auto-corrected\nThe order in which rules are executed can be influences with `Rule.VisitorModifier`. Now the network or rule execution dependencies get more complex, it becomes difficult to find that single order of rules which always resolves all format errors in a single trip. This is confusing for users of kltint.\r\n\r\nIf format finds any lint violations in a file that can be autocorrected, it should automatically rerun format on that file before returning the lint violations of the last format run. To prevent that a set of rules cause an infinite rerun of the format, no more than 3 reruns will be executed before returning the results.\n", "hints_text": "", "created_at": "2023-06-22T18:50:00Z", "version": "0.49", "FAIL_TO_PASS": [ "gradle_test_execution" ], "PASS_TO_PASS": [], "ERROR_TO_PASS": [], "environment_setup_commit": "410d8849874f4d3600f9d4572e0850adccce4f2d" }, { "repo": "pinterest/ktlint", "pull_number": 2132, "instance_id": "pinterest__ktlint-2132", "issue_numbers": [ "2130" ], "base_commit": "7d8a509fd477c8cb474258d0ae865ce4d707659f", "patch": "diff --git a/CHANGELOG.md b/CHANGELOG.md\nindex 5a4038fb86..ef900bb62c 100644\n--- a/CHANGELOG.md\n+++ b/CHANGELOG.md\n@@ -13,6 +13,8 @@ This project adheres to [Semantic Versioning](https://semver.org/).\n * Allow to disable ktlint in `.editorconfig` for a glob ([#2100](https://github.com/pinterest/ktlint/issues/2100))\n * Fix wrapping of nested function literals `wrapping` ([#2106](https://github.com/pinterest/ktlint/issues/2106))\n * Do not indent class body for classes having a long super type list in code style `ktlint_official` as it is inconsistent compared to other class bodies `indent` [#2115](https://github.com/pinterest/ktlint/issues/2115) \n+* Log message `Format was not able to resolve all violations which (theoretically) can be autocorrected in file ... in 3 consecutive runs of format` is now only displayed in case a new ktlint rule is actually needed. [#2129](https://github.com/pinterest/ktlint/issues/2129)\n+* Fix wrapping of function signature in case the opening brace of the function body block exceeds the maximum line length. Fix upsert of whitespace into composite nodes. `function-signature` [#2130](https://github.com/pinterest/ktlint/issues/2130)\n * Fix spacing around colon in annotations `spacing-around-colon` ([#2093](https://github.com/pinterest/ktlint/issues/2093))\n \n ### Changed\ndiff --git a/ktlint-rule-engine-core/src/main/kotlin/com/pinterest/ktlint/rule/engine/core/api/ASTNodeExtension.kt b/ktlint-rule-engine-core/src/main/kotlin/com/pinterest/ktlint/rule/engine/core/api/ASTNodeExtension.kt\nindex 201e7dac43..054d306400 100644\n--- a/ktlint-rule-engine-core/src/main/kotlin/com/pinterest/ktlint/rule/engine/core/api/ASTNodeExtension.kt\n+++ b/ktlint-rule-engine-core/src/main/kotlin/com/pinterest/ktlint/rule/engine/core/api/ASTNodeExtension.kt\n@@ -245,11 +245,23 @@ public fun ASTNode.upsertWhitespaceBeforeMe(text: String) {\n }\n }\n } else {\n- val prevLeaf =\n- requireNotNull(prevLeaf()) {\n- \"Can not upsert a whitespace if the first node is a non-leaf node\"\n+ when (val prevSibling = prevSibling()) {\n+ null -> {\n+ // Never insert a whitespace element as first child node in a composite node. Instead, upsert just before the composite node\n+ treeParent.upsertWhitespaceBeforeMe(text)\n }\n- prevLeaf.upsertWhitespaceAfterMe(text)\n+\n+ is LeafElement -> {\n+ prevSibling.upsertWhitespaceAfterMe(text)\n+ }\n+\n+ else -> {\n+ // Insert in between two composite nodes\n+ PsiWhiteSpaceImpl(text).also { psiWhiteSpace ->\n+ treeParent.addChild(psiWhiteSpace.node, this)\n+ }\n+ }\n+ }\n }\n }\n \n@@ -279,7 +291,23 @@ public fun ASTNode.upsertWhitespaceAfterMe(text: String) {\n }\n }\n } else {\n- lastChildLeafOrSelf().upsertWhitespaceAfterMe(text)\n+ when (val nextSibling = nextSibling()) {\n+ null -> {\n+ // Never insert a whitespace element as last child node in a composite node. Instead, upsert just after the composite node\n+ treeParent.upsertWhitespaceAfterMe(text)\n+ }\n+\n+ is LeafElement -> {\n+ nextSibling.upsertWhitespaceBeforeMe(text)\n+ }\n+\n+ else -> {\n+ // Insert in between two composite nodes\n+ PsiWhiteSpaceImpl(text).also { psiWhiteSpace ->\n+ treeParent.addChild(psiWhiteSpace.node, nextSibling)\n+ }\n+ }\n+ }\n }\n }\n \ndiff --git a/ktlint-rule-engine/src/main/kotlin/com/pinterest/ktlint/rule/engine/api/KtLintRuleEngine.kt b/ktlint-rule-engine/src/main/kotlin/com/pinterest/ktlint/rule/engine/api/KtLintRuleEngine.kt\nindex 3fdbdc1129..1c5ba36c7e 100644\n--- a/ktlint-rule-engine/src/main/kotlin/com/pinterest/ktlint/rule/engine/api/KtLintRuleEngine.kt\n+++ b/ktlint-rule-engine/src/main/kotlin/com/pinterest/ktlint/rule/engine/api/KtLintRuleEngine.kt\n@@ -179,9 +179,30 @@ public class KtLintRuleEngine(\n }\n } while (mutated && formatRunCount < MAX_FORMAT_RUNS_PER_FILE)\n if (formatRunCount == MAX_FORMAT_RUNS_PER_FILE && mutated) {\n- LOGGER.warn {\n- \"Format was not able to resolve all violations which (theoretically) can be autocorrected in file \" +\n- \"${code.filePathOrStdin()} in $MAX_FORMAT_RUNS_PER_FILE consecutive runs of format.\"\n+ // It is unknown if the last format run introduces new lint violations which can be autocorrected. So run lint once more so that\n+ // the user can be informed about this correctly.\n+ var hasErrorsWhichCanBeAutocorrected = false\n+ visitorProvider\n+ .visitor()\n+ .invoke { rule ->\n+ ruleExecutionContext.executeRule(rule, false) { offset, message, canBeAutoCorrected ->\n+ if (canBeAutoCorrected) {\n+ ruleExecutionContext.rebuildSuppressionLocator()\n+ val formattedCode =\n+ ruleExecutionContext\n+ .rootNode\n+ .text\n+ .replace(\"\\n\", ruleExecutionContext.determineLineSeparator(code.content))\n+ val (line, col) = ruleExecutionContext.positionInTextLocator(offset)\n+ hasErrorsWhichCanBeAutocorrected = true\n+ }\n+ }\n+ }\n+ if (hasErrorsWhichCanBeAutocorrected) {\n+ LOGGER.warn {\n+ \"Format was not able to resolve all violations which (theoretically) can be autocorrected in file \" +\n+ \"${code.filePathOrStdin()} in $MAX_FORMAT_RUNS_PER_FILE consecutive runs of format.\"\n+ }\n }\n }\n \ndiff --git a/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/FunctionSignatureRule.kt b/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/FunctionSignatureRule.kt\nindex 596533b3eb..3625054e2a 100644\n--- a/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/FunctionSignatureRule.kt\n+++ b/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/FunctionSignatureRule.kt\n@@ -9,6 +9,7 @@ import com.pinterest.ktlint.rule.engine.core.api.ElementType.EOL_COMMENT\n import com.pinterest.ktlint.rule.engine.core.api.ElementType.EQ\n import com.pinterest.ktlint.rule.engine.core.api.ElementType.FUN\n import com.pinterest.ktlint.rule.engine.core.api.ElementType.FUN_KEYWORD\n+import com.pinterest.ktlint.rule.engine.core.api.ElementType.LBRACE\n import com.pinterest.ktlint.rule.engine.core.api.ElementType.LPAR\n import com.pinterest.ktlint.rule.engine.core.api.ElementType.MODIFIER_LIST\n import com.pinterest.ktlint.rule.engine.core.api.ElementType.RPAR\n@@ -178,13 +179,21 @@ public class FunctionSignatureRule :\n val rewriteFunctionSignatureWithParameters = node.countParameters() > 0 && singleLineFunctionSignatureLength > maxLineLength\n if (forceMultilineSignature || rewriteFunctionSignatureWithParameters) {\n fixWhiteSpacesInValueParameterList(node, emit, autoCorrect, multiline = true, dryRun = false)\n- // Due to rewriting the function signature, the remaining length on the last line of the multiline\n- // signature needs to be recalculated\n- val lengthOfLastLine = recalculateRemainLengthForFirstLineOfBodyExpression(node)\n- fixFunctionBody(node, emit, autoCorrect, maxLineLength - lengthOfLastLine)\n+ if (node.findChildByType(EQ) == null) {\n+ fixWhitespaceBeforeFunctionBodyBlock(node, emit, autoCorrect, dryRun = false)\n+ } else {\n+ // Due to rewriting the function signature, the remaining length on the last line of the multiline signature needs to be\n+ // recalculated\n+ val lengthOfLastLine = recalculateRemainingLengthForFirstLineOfBodyExpression(node)\n+ fixFunctionBodyExpression(node, emit, autoCorrect, maxLineLength - lengthOfLastLine)\n+ }\n } else {\n fixWhiteSpacesInValueParameterList(node, emit, autoCorrect, multiline = false, dryRun = false)\n- fixFunctionBody(node, emit, autoCorrect, maxLineLength - singleLineFunctionSignatureLength)\n+ if (node.findChildByType(EQ) == null) {\n+ fixWhitespaceBeforeFunctionBodyBlock(node, emit, autoCorrect, dryRun = false)\n+ } else {\n+ fixFunctionBodyExpression(node, emit, autoCorrect, maxLineLength - singleLineFunctionSignatureLength)\n+ }\n }\n } else {\n // When max line length is not set then keep it as single line function signature only when the original\n@@ -202,7 +211,7 @@ public class FunctionSignatureRule :\n }\n }\n \n- private fun recalculateRemainLengthForFirstLineOfBodyExpression(node: ASTNode): Int {\n+ private fun recalculateRemainingLengthForFirstLineOfBodyExpression(node: ASTNode): Int {\n val closingParenthesis =\n node\n .findChildByType(VALUE_PARAMETER_LIST)\n@@ -250,7 +259,12 @@ public class FunctionSignatureRule :\n // maximum line length). The white space correction will be calculated via a dry run of the actual fix.\n return actualFunctionSignatureLength +\n // Calculate the white space correction in case the signature would be rewritten to a single line\n- fixWhiteSpacesInValueParameterList(node, emit, autoCorrect, multiline = false, dryRun = true)\n+ fixWhiteSpacesInValueParameterList(node, emit, autoCorrect, multiline = false, dryRun = true) +\n+ if (node.findChildByType(EQ) == null) {\n+ fixWhitespaceBeforeFunctionBodyBlock(node, emit, autoCorrect, dryRun = true)\n+ } else {\n+ 0\n+ }\n }\n \n private fun ASTNode.getFunctionSignatureLength() = indent(false).length + getFunctionSignatureNodesLength()\n@@ -505,19 +519,6 @@ public class FunctionSignatureRule :\n return whiteSpaceCorrection\n }\n \n- private fun fixFunctionBody(\n- node: ASTNode,\n- emit: (offset: Int, errorMessage: String, canBeAutoCorrected: Boolean) -> Unit,\n- autoCorrect: Boolean,\n- maxLengthRemainingForFirstLineOfBodyExpression: Int,\n- ) {\n- if (node.findChildByType(EQ) == null) {\n- fixFunctionBodyBlock(node, emit, autoCorrect)\n- } else {\n- fixFunctionBodyExpression(node, emit, autoCorrect, maxLengthRemainingForFirstLineOfBodyExpression)\n- }\n- }\n-\n private fun fixFunctionBodyExpression(\n node: ASTNode,\n emit: (offset: Int, errorMessage: String, canBeAutoCorrected: Boolean) -> Unit,\n@@ -618,36 +619,36 @@ public class FunctionSignatureRule :\n ?.matches(INDENT_WITH_CLOSING_PARENTHESIS)\n ?: false\n \n- private fun fixFunctionBodyBlock(\n+ private fun fixWhitespaceBeforeFunctionBodyBlock(\n node: ASTNode,\n emit: (offset: Int, errorMessage: String, canBeAutoCorrected: Boolean) -> Unit,\n autoCorrect: Boolean,\n- ) {\n- val lastNodeOfFunctionSignatureWithBlockBody =\n- node\n- .getLastNodeOfFunctionSignatureWithBlockBody()\n- ?.nextLeaf(includeEmpty = true)\n- ?: return\n-\n- val bodyNodes = node.getFunctionBody(lastNodeOfFunctionSignatureWithBlockBody)\n- val whiteSpaceBeforeFunctionBodyExpression = bodyNodes.getStartingWhitespaceOrNull()\n- val functionBodyBlock = bodyNodes.dropWhile { it.isWhiteSpace() }\n+ dryRun: Boolean,\n+ ): Int {\n+ var whiteSpaceCorrection = 0\n \n- functionBodyBlock\n- .joinTextToString()\n- .split(\"\\n\")\n- .firstOrNull()\n- ?.also {\n- if (whiteSpaceBeforeFunctionBodyExpression?.text != \" \") {\n- emit(functionBodyBlock.first().startOffset, \"Expected a single space before body block\", true)\n- if (autoCorrect) {\n- functionBodyBlock\n- .first()\n- .prevLeaf(true)\n- ?.upsertWhitespaceAfterMe(\" \")\n+ node\n+ .findChildByType(BLOCK)\n+ ?.takeIf { it.findChildByType(LBRACE) != null }\n+ ?.let { block ->\n+ block\n+ .prevLeaf()\n+ .takeIf { it.isWhiteSpace() }\n+ .let { whiteSpaceBeforeBlock ->\n+ if (whiteSpaceBeforeBlock == null || whiteSpaceBeforeBlock.text != \" \") {\n+ if (!dryRun) {\n+ emit(block.startOffset, \"Expected a single space before body block\", true)\n+ }\n+ if (autoCorrect && !dryRun) {\n+ block.upsertWhitespaceBeforeMe(\" \")\n+ } else {\n+ whiteSpaceCorrection += 1 - (whiteSpaceBeforeBlock?.textLength ?: 0)\n+ }\n+ }\n }\n- }\n }\n+\n+ return whiteSpaceCorrection\n }\n \n private fun ASTNode.getFunctionBody(splitNode: ASTNode?): List =\n", "test_patch": "diff --git a/ktlint-rule-engine-core/src/test/kotlin/com/pinterest/ktlint/rule/engine/core/api/ASTNodeExtensionTest.kt b/ktlint-rule-engine-core/src/test/kotlin/com/pinterest/ktlint/rule/engine/core/api/ASTNodeExtensionTest.kt\nindex 314059d452..d08d098c71 100644\n--- a/ktlint-rule-engine-core/src/test/kotlin/com/pinterest/ktlint/rule/engine/core/api/ASTNodeExtensionTest.kt\n+++ b/ktlint-rule-engine-core/src/test/kotlin/com/pinterest/ktlint/rule/engine/core/api/ASTNodeExtensionTest.kt\n@@ -2,13 +2,16 @@ package com.pinterest.ktlint.rule.engine.core.api\n \n import com.pinterest.ktlint.rule.engine.api.Code\n import com.pinterest.ktlint.rule.engine.api.KtLintRuleEngine\n+import com.pinterest.ktlint.rule.engine.core.api.ElementType.ANNOTATION_ENTRY\n import com.pinterest.ktlint.rule.engine.core.api.ElementType.CLASS\n import com.pinterest.ktlint.rule.engine.core.api.ElementType.CLASS_BODY\n import com.pinterest.ktlint.rule.engine.core.api.ElementType.ENUM_ENTRY\n import com.pinterest.ktlint.rule.engine.core.api.ElementType.FUN\n import com.pinterest.ktlint.rule.engine.core.api.ElementType.IDENTIFIER\n import com.pinterest.ktlint.rule.engine.core.api.ElementType.LPAR\n+import com.pinterest.ktlint.rule.engine.core.api.ElementType.MODIFIER_LIST\n import com.pinterest.ktlint.rule.engine.core.api.ElementType.RPAR\n+import com.pinterest.ktlint.rule.engine.core.api.ElementType.TYPE_REFERENCE\n import com.pinterest.ktlint.rule.engine.core.api.ElementType.VALUE_PARAMETER\n import com.pinterest.ktlint.rule.engine.core.api.ElementType.VALUE_PARAMETER_LIST\n import com.pinterest.ktlint.rule.engine.core.api.ElementType.WHITE_SPACE\n@@ -303,7 +306,7 @@ class ASTNodeExtensionTest {\n @Nested\n inner class UpsertWhitespaceBeforeMe {\n @Test\n- fun `Given a whitespace node and upsert a whitespace before the node (RPAR) then replace the current whitespace element`() {\n+ fun `Given an upsert of a whitespace based before another whitespace node then replace the existing whitespace element`() {\n val code =\n \"\"\"\n fun foo( ) = 42\n@@ -327,10 +330,10 @@ class ASTNodeExtensionTest {\n }\n \n @Test\n- fun `Given a node (RPAR) which is preceded by a non-whitespace leaf element (LPAR) and upsert a whitespace before the node (RPAR) then create a new whitespace element before the node (RPAR)`() {\n+ fun `Given an upsert of a whitespace before a non-whitespace node (RPAR) which is preceded by a whitespace leaf element (LPAR) then then replace the whitespace element`() {\n val code =\n \"\"\"\n- fun foo() = 42\n+ fun foo( ) = 42\n \"\"\".trimIndent()\n val formattedCode =\n \"\"\"\n@@ -350,10 +353,10 @@ class ASTNodeExtensionTest {\n }\n \n @Test\n- fun `Given a node (RPAR) which is preceded by a whitespace leaf element and upsert a whitespace before the node (RPAR) then replace the whitespace element before the node (RPAR)`() {\n+ fun `Given an upsert of a whitespace before a non-whitespace node (RPAR) which is preceded by another non-whitespace leaf element (LPAR) then create a new whitespace element`() {\n val code =\n \"\"\"\n- fun foo( ) = 42\n+ fun foo() = 42\n \"\"\".trimIndent()\n val formattedCode =\n \"\"\"\n@@ -373,7 +376,33 @@ class ASTNodeExtensionTest {\n }\n \n @Test\n- fun `Given a node (VALUE_PARAMETER) which is preceded by a non-whitespace leaf element (LPAR) and upsert a whitespace before the node (VALUE_PARAMETER) then create a new whitespace element before the node (VALUE_PARAMETER)`() {\n+ fun `Given an upsert of a whitespace before a composite node (ANNOTATION_ENTRY) which is the first child of another composite element then create a new whitespace before (VALUE_PARAMETER)`() {\n+ val code =\n+ \"\"\"\n+ fun foo(@Bar string: String) = 42\n+ \"\"\".trimIndent()\n+ val formattedCode =\n+ \"\"\"\n+ fun foo(\n+ @Bar string: String) = 42\n+ \"\"\".trimIndent()\n+\n+ val actual =\n+ code\n+ .transformAst {\n+ findChildByType(FUN)\n+ ?.findChildByType(VALUE_PARAMETER_LIST)\n+ ?.findChildByType(VALUE_PARAMETER)\n+ ?.findChildByType(MODIFIER_LIST)\n+ ?.findChildByType(ANNOTATION_ENTRY)\n+ ?.upsertWhitespaceBeforeMe(\"\\n \")\n+ }.text\n+\n+ assertThat(actual).isEqualTo(formattedCode)\n+ }\n+\n+ @Test\n+ fun `Given an upsert of a whitespace before a composite node (VALUE_PARAMETER) which is preceded by a non-whitespace leaf element (LPAR) then create a new whitespace element before the node (VALUE_PARAMETER)`() {\n val code =\n \"\"\"\n fun foo(string: String) = 42\n@@ -397,25 +426,26 @@ class ASTNodeExtensionTest {\n }\n \n @Test\n- fun `Given a node (FUN bar) which is preceded by a composite element (FUN foo) and upsert a whitespace before the node (FUN bar) then create a new whitespace element before the node (FUN bar)`() {\n+ fun `Given an upsert of a whitespace before a composite node (ANNOTATION_ENTRY) which is preceded by another composite node (ANNOTATION_ENTRY) then create a new whitespace between the ANNOTATION_ENTRIES`() {\n val code =\n \"\"\"\n- fun foo() = \"foo\"\n- fun bar() = \"bar\"\n+ fun foo(@Bar@Foo string: String) = 42\n \"\"\".trimIndent()\n val formattedCode =\n \"\"\"\n- fun foo() = \"foo\"\n-\n- fun bar() = \"bar\"\n+ fun foo(@Bar @Foo string: String) = 42\n \"\"\".trimIndent()\n \n val actual =\n code\n .transformAst {\n- children()\n- .last { it.elementType == FUN }\n- .upsertWhitespaceBeforeMe(\"\\n\\n\")\n+ findChildByType(FUN)\n+ ?.findChildByType(VALUE_PARAMETER_LIST)\n+ ?.findChildByType(VALUE_PARAMETER)\n+ ?.findChildByType(MODIFIER_LIST)\n+ ?.findChildByType(ANNOTATION_ENTRY)\n+ ?.nextSibling()\n+ ?.upsertWhitespaceBeforeMe(\" \")\n }.text\n \n assertThat(actual).isEqualTo(formattedCode)\n@@ -425,10 +455,34 @@ class ASTNodeExtensionTest {\n @Nested\n inner class UpsertWhitespaceAfterMe {\n @Test\n- fun `Given a node (LPAR) which is followed by a non-whitespace leaf element (RPAR) and upsert a whitespace after the node (LPAR) then create a new whitespace element after the node (LPAR)`() {\n+ fun `Given an upsert of a whitespace based after another whitespace node then replace the existing whitespace element`() {\n val code =\n \"\"\"\n- fun foo() = 42\n+ fun foo( ) = 42\n+ \"\"\".trimIndent()\n+ val formattedCode =\n+ \"\"\"\n+ fun foo(\n+ ) = 42\n+ \"\"\".trimIndent()\n+\n+ val actual =\n+ code\n+ .transformAst {\n+ findChildByType(FUN)\n+ ?.findChildByType(VALUE_PARAMETER_LIST)\n+ ?.findChildByType(WHITE_SPACE)\n+ ?.upsertWhitespaceAfterMe(\"\\n\")\n+ }.text\n+\n+ assertThat(actual).isEqualTo(formattedCode)\n+ }\n+\n+ @Test\n+ fun `Given an upsert of a whitespace after a non-whitespace node (LPAR) which is followed by a whitespace leaf element (RPAR) then then replace the whitespace element`() {\n+ val code =\n+ \"\"\"\n+ fun foo( ) = 42\n \"\"\".trimIndent()\n val formattedCode =\n \"\"\"\n@@ -448,10 +502,10 @@ class ASTNodeExtensionTest {\n }\n \n @Test\n- fun `Given a node (LPAR) which is followed by a whitespace leaf element and upsert a whitespace after the node (LPAR) then replace the whitespace element after the node (LPAR)`() {\n+ fun `Given an upsert of a whitespace after a non-whitespace node (LPAR) which is followed by another non-whitespace leaf element (RPAR) then create a new whitespace element`() {\n val code =\n \"\"\"\n- fun foo( ) = 42\n+ fun foo() = 42\n \"\"\".trimIndent()\n val formattedCode =\n \"\"\"\n@@ -471,7 +525,32 @@ class ASTNodeExtensionTest {\n }\n \n @Test\n- fun `Given a node (VALUE_PARAMETER) which is followed by a non-whitespace leaf element (RPAR) and upsert a whitespace after the node (VALUE_PARAMETER) then create a new whitespace element after the node (VALUE_PARAMETER)`() {\n+ fun `Given an upsert of a whitespace after a composite node (ANNOTATION_ENTRY) which is the last child of another composite element then create a new whitespace after (VALUE_PARAMETER)`() {\n+ val code =\n+ \"\"\"\n+ fun foo(@Bar string: String) = 42\n+ \"\"\".trimIndent()\n+ val formattedCode =\n+ \"\"\"\n+ fun foo(@Bar string: String\n+ ) = 42\n+ \"\"\".trimIndent()\n+\n+ val actual =\n+ code\n+ .transformAst {\n+ findChildByType(FUN)\n+ ?.findChildByType(VALUE_PARAMETER_LIST)\n+ ?.findChildByType(VALUE_PARAMETER)\n+ ?.findChildByType(TYPE_REFERENCE)\n+ ?.upsertWhitespaceAfterMe(\"\\n\")\n+ }.text\n+\n+ assertThat(actual).isEqualTo(formattedCode)\n+ }\n+\n+ @Test\n+ fun `Given an upsert of a whitespace after a composite node (VALUE_PARAMETER) which is followed by a non-whitespace leaf element (RPAR) then create a new whitespace element after the node (VALUE_PARAMETER)`() {\n val code =\n \"\"\"\n fun foo(string: String) = 42\n@@ -495,25 +574,25 @@ class ASTNodeExtensionTest {\n }\n \n @Test\n- fun `Given a node (FUN foo) which is followed by a composite element (FUN bar) and upsert a whitespace after the node (FUN foo) then create a new whitespace element after the node (FUN foo)`() {\n+ fun `Given an upsert of a whitespace after a composite node (ANNOTATION_ENTRY) which is followed by another composite node (ANNOTATION_ENTRY) then create a new whitespace between the ANNOTATION_ENTRIES`() {\n val code =\n \"\"\"\n- fun foo() = \"foo\"\n- fun bar() = \"bar\"\n+ fun foo(@Bar@Foo string: String) = 42\n \"\"\".trimIndent()\n val formattedCode =\n \"\"\"\n- fun foo() = \"foo\"\n-\n- fun bar() = \"bar\"\n+ fun foo(@Bar @Foo string: String) = 42\n \"\"\".trimIndent()\n \n val actual =\n code\n .transformAst {\n- children()\n- .first { it.elementType == FUN }\n- .upsertWhitespaceAfterMe(\"\\n\\n\")\n+ findChildByType(FUN)\n+ ?.findChildByType(VALUE_PARAMETER_LIST)\n+ ?.findChildByType(VALUE_PARAMETER)\n+ ?.findChildByType(MODIFIER_LIST)\n+ ?.findChildByType(ANNOTATION_ENTRY)\n+ ?.upsertWhitespaceAfterMe(\" \")\n }.text\n \n assertThat(actual).isEqualTo(formattedCode)\ndiff --git a/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/FunctionSignatureRuleTest.kt b/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/FunctionSignatureRuleTest.kt\nindex 138b8cd989..b965d01431 100644\n--- a/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/FunctionSignatureRuleTest.kt\n+++ b/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/FunctionSignatureRuleTest.kt\n@@ -63,8 +63,13 @@ class FunctionSignatureRuleTest {\n functionSignatureWrappingRuleAssertThat(code)\n .setMaxLineLength()\n .addAdditionalRuleProvider { FunctionStartOfBodySpacingRule() }\n- .hasLintViolation(2, 38, \"Expected a single space before body block\")\n- .isFormattedAs(formattedCode)\n+ .hasLintViolations(\n+ LintViolation(2, 7, \"Newline expected after opening parenthesis\"),\n+ LintViolation(2, 15, \"Parameter should start on a newline\"),\n+ LintViolation(2, 23, \"Parameter should start on a newline\"),\n+ LintViolation(2, 29, \"Newline expected before closing parenthesis\"),\n+ LintViolation(2, 38, \"Expected a single space before body block\"),\n+ ).isFormattedAs(formattedCode)\n }\n \n @Test\n", "problem_statement": "Missing whitespace before function body is inserted in wrong place in AST\nGiven code below:\r\n```\r\nclass UampNotificationManager(\r\n private val context: Context,\r\n sessionToken: MediaSessionCompat.Token,\r\n notificationListener: PlayerNotificationManager.NotificationListener,\r\n) {\r\n fun showNotificationForPlayer(player: Player){\r\n notificationManager.setPlayer(player)\r\n }\r\n}\r\n```\r\nand `.editorconfig`:\r\n```\r\nroot = true\r\n\r\n[**/*.{kt,kts}]\r\nktlint_code_style = ktlint_official\r\nktlint_experimental = enabled\r\nktlint_standard = enabled\r\n```\r\nthen ktlint `0.50.0` is not able to format the code correctly in 3 runs.\r\n\r\nWhen linting the original code, the following is reported:\r\n```\r\nsrc/main/kotlin/UampNotificationManager.kt:6:50: Missing spacing before \"{\" (standard:curly-spacing)\r\nsrc/main/kotlin/UampNotificationManager.kt:6:50: Expected a single white space before start of function body (standard:function-start-of-body-spacing)\r\nsrc/main/kotlin/UampNotificationManager.kt:6:50: Expected a single space before body block (standard:function-signature)\r\n12:11:35.739 [main] WARN com.pinterest.ktlint.cli.internal.KtlintCommandLine - Lint has found errors than can be autocorrected using 'ktlint --format'\r\n```\r\nSo three different rules are reporting the same error.\r\n\r\nWhen running format, the output is:\r\n```\r\n12:12:49.476 [pool-1-thread-1] WARN com.pinterest.ktlint.rule.engine.api.KtLintRuleEngine - Format was not able to resolve all violations which (theoretically) can be autocorrected in file .../src/main/kotlin/UampNotificationManager.kt in 3 consecutive runs of format.\r\n```\r\nAlso, the file is formatted correctly *and* no more errors remain despite that formatting reports that not all problems were solved.\r\n\r\nThe problem is caused by inserting the whitespace element in the wrong position in the AST. If ktlint is restarted, the file is parsed again and the whitespace is in the expected place in the AST and no more error is to be fixed.\n", "hints_text": "", "created_at": "2023-07-15T17:04:02Z", "version": "0.50", "FAIL_TO_PASS": [ "gradle_test_execution" ], "PASS_TO_PASS": [], "ERROR_TO_PASS": [], "environment_setup_commit": "0a2500665d514f27ad06828544c43a6f28924426" }, { "repo": "pinterest/ktlint", "pull_number": 2126, "instance_id": "pinterest__ktlint-2126", "issue_numbers": [ "2093" ], "base_commit": "ce93a6dbef5870951fea157acfbb57b8b8c352e2", "patch": "diff --git a/CHANGELOG.md b/CHANGELOG.md\nindex 7c49dcbfb5..5a4038fb86 100644\n--- a/CHANGELOG.md\n+++ b/CHANGELOG.md\n@@ -13,6 +13,7 @@ This project adheres to [Semantic Versioning](https://semver.org/).\n * Allow to disable ktlint in `.editorconfig` for a glob ([#2100](https://github.com/pinterest/ktlint/issues/2100))\n * Fix wrapping of nested function literals `wrapping` ([#2106](https://github.com/pinterest/ktlint/issues/2106))\n * Do not indent class body for classes having a long super type list in code style `ktlint_official` as it is inconsistent compared to other class bodies `indent` [#2115](https://github.com/pinterest/ktlint/issues/2115) \n+* Fix spacing around colon in annotations `spacing-around-colon` ([#2093](https://github.com/pinterest/ktlint/issues/2093))\n \n ### Changed\n \ndiff --git a/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/SpacingAroundColonRule.kt b/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/SpacingAroundColonRule.kt\nindex a3a8c61af3..4105a3c79e 100644\n--- a/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/SpacingAroundColonRule.kt\n+++ b/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/SpacingAroundColonRule.kt\n@@ -1,14 +1,12 @@\n package com.pinterest.ktlint.ruleset.standard.rules\n \n-import com.pinterest.ktlint.rule.engine.core.api.ElementType.ANNOTATION\n-import com.pinterest.ktlint.rule.engine.core.api.ElementType.ANNOTATION_ENTRY\n import com.pinterest.ktlint.rule.engine.core.api.ElementType.COLON\n import com.pinterest.ktlint.rule.engine.core.api.ElementType.EQ\n import com.pinterest.ktlint.rule.engine.core.api.RuleId\n-import com.pinterest.ktlint.rule.engine.core.api.isPartOf\n import com.pinterest.ktlint.rule.engine.core.api.isPartOfComment\n import com.pinterest.ktlint.rule.engine.core.api.isWhiteSpace\n import com.pinterest.ktlint.rule.engine.core.api.isWhiteSpaceWithNewline\n+import com.pinterest.ktlint.rule.engine.core.api.isWhiteSpaceWithoutNewline\n import com.pinterest.ktlint.rule.engine.core.api.nextLeaf\n import com.pinterest.ktlint.rule.engine.core.api.nextSibling\n import com.pinterest.ktlint.rule.engine.core.api.prevLeaf\n@@ -18,6 +16,8 @@ import com.pinterest.ktlint.rule.engine.core.api.upsertWhitespaceBeforeMe\n import com.pinterest.ktlint.ruleset.standard.StandardRule\n import org.jetbrains.kotlin.com.intellij.lang.ASTNode\n import org.jetbrains.kotlin.com.intellij.psi.impl.source.tree.LeafPsiElement\n+import org.jetbrains.kotlin.psi.KtAnnotation\n+import org.jetbrains.kotlin.psi.KtAnnotationEntry\n import org.jetbrains.kotlin.psi.KtBlockExpression\n import org.jetbrains.kotlin.psi.KtClassOrObject\n import org.jetbrains.kotlin.psi.KtConstructor\n@@ -35,138 +35,190 @@ public class SpacingAroundColonRule : StandardRule(\"colon-spacing\") {\n emit: (offset: Int, errorMessage: String, canBeAutoCorrected: Boolean) -> Unit,\n ) {\n if (node.elementType == COLON) {\n- val psiParent = node.psi.parent\n- if (node.isPartOf(ANNOTATION) || node.isPartOf(ANNOTATION_ENTRY)) {\n- // TODO: https://github.com/pinterest/ktlint/issues/2093 Enforce no spacing\n- return\n- }\n- val prevLeaf = node.prevLeaf()\n- if (prevLeaf != null && prevLeaf.isWhiteSpaceWithNewline()) {\n- emit(prevLeaf.startOffset, \"Unexpected newline before \\\":\\\"\", true)\n- if (autoCorrect) {\n- val prevNonCodeElements =\n- node\n- .siblings(forward = false)\n- .takeWhile { it.isWhiteSpace() || it.isPartOfComment() }\n- .toList()\n- .reversed()\n- when {\n- psiParent is KtProperty || psiParent is KtNamedFunction -> {\n- val equalsSignElement =\n- node\n- .siblings(forward = true)\n- .firstOrNull { it.elementType == EQ }\n- if (equalsSignElement != null) {\n- equalsSignElement\n- .treeNext\n- ?.let { treeNext ->\n- prevNonCodeElements.forEach {\n- node.treeParent.addChild(it, treeNext)\n- }\n- if (treeNext.isWhiteSpace()) {\n- equalsSignElement.treeParent.removeChild(treeNext)\n- }\n- Unit\n+ removeUnexpectedNewlineBefore(node, emit, autoCorrect)\n+ removeUnexpectedSpacingAround(node, emit, autoCorrect)\n+ addMissingSpacingAround(node, emit, autoCorrect)\n+ }\n+ }\n+\n+ private fun removeUnexpectedNewlineBefore(\n+ node: ASTNode,\n+ emit: (offset: Int, errorMessage: String, canBeAutoCorrected: Boolean) -> Unit,\n+ autoCorrect: Boolean,\n+ ) {\n+ val psiParent = node.psi.parent\n+ val prevLeaf = node.prevLeaf()\n+ if (prevLeaf != null && prevLeaf.isWhiteSpaceWithNewline()) {\n+ emit(prevLeaf.startOffset, \"Unexpected newline before \\\":\\\"\", true)\n+ if (autoCorrect) {\n+ val prevNonCodeElements =\n+ node\n+ .siblings(forward = false)\n+ .takeWhile { it.isWhiteSpace() || it.isPartOfComment() }\n+ .toList()\n+ .reversed()\n+ when {\n+ psiParent is KtProperty || psiParent is KtNamedFunction -> {\n+ val equalsSignElement =\n+ node\n+ .siblings(forward = true)\n+ .firstOrNull { it.elementType == EQ }\n+ if (equalsSignElement != null) {\n+ equalsSignElement\n+ .treeNext\n+ ?.let { treeNext ->\n+ prevNonCodeElements.forEach {\n+ node.treeParent.addChild(it, treeNext)\n+ }\n+ if (treeNext.isWhiteSpace()) {\n+ equalsSignElement.treeParent.removeChild(treeNext)\n+ }\n+ Unit\n+ }\n+ }\n+ val blockElement =\n+ node\n+ .siblings(forward = true)\n+ .firstIsInstanceOrNull()\n+ if (blockElement != null) {\n+ val before =\n+ blockElement\n+ .firstChildNode\n+ .nextSibling()\n+ prevNonCodeElements\n+ .let {\n+ if (it.first().isWhiteSpace()) {\n+ blockElement.treeParent.removeChild(it.first())\n+ it.drop(1)\n }\n- }\n- val blockElement =\n- node\n- .siblings(forward = true)\n- .firstIsInstanceOrNull()\n- if (blockElement != null) {\n- val before =\n- blockElement\n- .firstChildNode\n- .nextSibling()\n- prevNonCodeElements\n- .let {\n- if (it.first().isWhiteSpace()) {\n- blockElement.treeParent.removeChild(it.first())\n- it.drop(1)\n- }\n- if (it.last().isWhiteSpaceWithNewline()) {\n- blockElement.treeParent.removeChild(it.last())\n- it.dropLast(1)\n- } else {\n- it\n- }\n- }.forEach {\n- blockElement.addChild(it, before)\n+ if (it.last().isWhiteSpaceWithNewline()) {\n+ blockElement.treeParent.removeChild(it.last())\n+ it.dropLast(1)\n+ } else {\n+ it\n }\n- }\n+ }.forEach {\n+ blockElement.addChild(it, before)\n+ }\n }\n- prevLeaf.prevLeaf()?.isPartOfComment() == true -> {\n- val nextLeaf = node.nextLeaf()\n- prevNonCodeElements.forEach {\n- node.treeParent.addChild(it, nextLeaf)\n- }\n- if (nextLeaf != null && nextLeaf.isWhiteSpace()) {\n- node.treeParent.removeChild(nextLeaf)\n- }\n+ }\n+\n+ prevLeaf.prevLeaf()?.isPartOfComment() == true -> {\n+ val nextLeaf = node.nextLeaf()\n+ prevNonCodeElements.forEach {\n+ node.treeParent.addChild(it, nextLeaf)\n }\n- else -> {\n- val text = prevLeaf.text\n- if (node.removeSpacingBefore) {\n- prevLeaf.treeParent.removeChild(prevLeaf)\n- } else {\n- (prevLeaf as LeafPsiElement).rawReplaceWithText(\" \")\n- }\n- node.upsertWhitespaceAfterMe(text)\n+ if (nextLeaf != null && nextLeaf.isWhiteSpace()) {\n+ node.treeParent.removeChild(nextLeaf)\n }\n }\n- }\n- }\n- if (node.prevSibling().isWhiteSpace() && node.removeSpacingBefore && !prevLeaf.isWhiteSpaceWithNewline()) {\n- emit(node.startOffset, \"Unexpected spacing before \\\":\\\"\", true)\n- if (autoCorrect) {\n- node\n- .prevSibling()\n- ?.let { prevSibling ->\n- prevSibling.treeParent.removeChild(prevSibling)\n+\n+ else -> {\n+ val text = prevLeaf.text\n+ if (node.spacingBefore) {\n+ (prevLeaf as LeafPsiElement).rawReplaceWithText(\" \")\n+ } else {\n+ prevLeaf.treeParent.removeChild(prevLeaf)\n }\n+ node.upsertWhitespaceAfterMe(text)\n+ }\n }\n }\n- val missingSpacingBefore =\n- !node.prevSibling().isWhiteSpace() &&\n- (\n- psiParent is KtClassOrObject || psiParent is KtConstructor<*> ||\n- psiParent is KtTypeConstraint || psiParent.parent is KtTypeParameterList\n- )\n- val missingSpacingAfter = !node.nextSibling().isWhiteSpace()\n- when {\n- missingSpacingBefore && missingSpacingAfter -> {\n- emit(node.startOffset, \"Missing spacing around \\\":\\\"\", true)\n- if (autoCorrect) {\n- node.upsertWhitespaceBeforeMe(\" \")\n- node.upsertWhitespaceAfterMe(\" \")\n+ }\n+ }\n+\n+ private fun removeUnexpectedSpacingAround(\n+ node: ASTNode,\n+ emit: (offset: Int, errorMessage: String, canBeAutoCorrected: Boolean) -> Unit,\n+ autoCorrect: Boolean,\n+ ) {\n+ if (node.prevSibling().isWhiteSpaceWithoutNewline() && node.noSpacingBefore) {\n+ emit(node.startOffset, \"Unexpected spacing before \\\":\\\"\", true)\n+ if (autoCorrect) {\n+ node\n+ .prevSibling()\n+ ?.let { prevSibling ->\n+ prevSibling.treeParent.removeChild(prevSibling)\n }\n- }\n- missingSpacingBefore -> {\n- emit(node.startOffset, \"Missing spacing before \\\":\\\"\", true)\n- if (autoCorrect) {\n- node.upsertWhitespaceBeforeMe(\" \")\n+ }\n+ }\n+ if (node.nextSibling().isWhiteSpaceWithoutNewline() && node.spacingAfter) {\n+ emit(node.startOffset, \"Unexpected spacing after \\\":\\\"\", true)\n+ if (autoCorrect) {\n+ node\n+ .nextSibling()\n+ ?.let { nextSibling ->\n+ nextSibling.treeParent.removeChild(nextSibling)\n }\n+ }\n+ }\n+ }\n+\n+ private fun addMissingSpacingAround(\n+ node: ASTNode,\n+ emit: (offset: Int, errorMessage: String, canBeAutoCorrected: Boolean) -> Unit,\n+ autoCorrect: Boolean,\n+ ) {\n+ val missingSpacingBefore = !node.prevSibling().isWhiteSpace() && node.spacingBefore\n+ val missingSpacingAfter = !node.nextSibling().isWhiteSpace() && node.noSpacingAfter\n+ when {\n+ missingSpacingBefore && missingSpacingAfter -> {\n+ emit(node.startOffset, \"Missing spacing around \\\":\\\"\", true)\n+ if (autoCorrect) {\n+ node.upsertWhitespaceBeforeMe(\" \")\n+ node.upsertWhitespaceAfterMe(\" \")\n }\n- missingSpacingAfter -> {\n- emit(node.startOffset + 1, \"Missing spacing after \\\":\\\"\", true)\n- if (autoCorrect) {\n- node.upsertWhitespaceAfterMe(\" \")\n- }\n+ }\n+\n+ missingSpacingBefore -> {\n+ emit(node.startOffset, \"Missing spacing before \\\":\\\"\", true)\n+ if (autoCorrect) {\n+ node.upsertWhitespaceBeforeMe(\" \")\n+ }\n+ }\n+\n+ missingSpacingAfter -> {\n+ emit(node.startOffset + 1, \"Missing spacing after \\\":\\\"\", true)\n+ if (autoCorrect) {\n+ node.upsertWhitespaceAfterMe(\" \")\n }\n }\n }\n }\n \n- private inline val ASTNode.removeSpacingBefore: Boolean\n+ private inline val ASTNode.spacingBefore: Boolean\n get() =\n- psi\n- .parent\n- .let { psiParent ->\n- psiParent !is KtClassOrObject &&\n- psiParent !is KtConstructor<*> && // constructor : this/super\n- psiParent !is KtTypeConstraint && // where T : S\n- psiParent?.parent !is KtTypeParameterList\n+ when {\n+ psi.parent is KtClassOrObject -> true\n+\n+ psi.parent is KtConstructor<*> -> {\n+ // constructor : this/super\n+ true\n+ }\n+\n+ psi.parent is KtTypeConstraint -> {\n+ // where T : S\n+ true\n }\n+\n+ psi.parent.parent is KtTypeParameterList ->\n+ true\n+\n+ else -> false\n+ }\n+\n+ private inline val ASTNode.noSpacingBefore: Boolean\n+ get() = !spacingBefore\n+\n+ private inline val ASTNode.spacingAfter: Boolean\n+ get() =\n+ when (psi.parent) {\n+ is KtAnnotation, is KtAnnotationEntry -> true\n+ else -> false\n+ }\n+\n+ private inline val ASTNode.noSpacingAfter: Boolean\n+ get() = !spacingAfter\n }\n \n public val SPACING_AROUND_COLON_RULE_ID: RuleId = SpacingAroundColonRule().ruleId\n", "test_patch": "diff --git a/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/SpacingAroundColonRuleTest.kt b/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/SpacingAroundColonRuleTest.kt\nindex af7413fd58..7fde51e24f 100644\n--- a/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/SpacingAroundColonRuleTest.kt\n+++ b/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/SpacingAroundColonRuleTest.kt\n@@ -92,14 +92,46 @@ class SpacingAroundColonRuleTest {\n val code =\n \"\"\"\n @file:JvmName(\"Foo\")\n+ @file : JvmName(\"Foo\")\n class Example(@field:Ann val foo: String, @get:Ann val bar: String)\n+ class Example(@field : Ann val foo: String, @get : Ann val bar: String)\n class Example {\n @set:[Inject VisibleForTesting]\n public var collaborator: Collaborator\n+ @set : [Inject VisibleForTesting]\n+ public var collaborator: Collaborator\n }\n fun @receiver:Fancy String.myExtension() { }\n+ fun @receiver : Fancy String.myExtension() { }\n \"\"\".trimIndent()\n- spacingAroundColonRuleAssertThat(code).hasNoLintViolations()\n+ val formattedCode =\n+ \"\"\"\n+ @file:JvmName(\"Foo\")\n+ @file:JvmName(\"Foo\")\n+ class Example(@field:Ann val foo: String, @get:Ann val bar: String)\n+ class Example(@field:Ann val foo: String, @get:Ann val bar: String)\n+ class Example {\n+ @set:[Inject VisibleForTesting]\n+ public var collaborator: Collaborator\n+ @set:[Inject VisibleForTesting]\n+ public var collaborator: Collaborator\n+ }\n+ fun @receiver:Fancy String.myExtension() { }\n+ fun @receiver:Fancy String.myExtension() { }\n+ \"\"\".trimIndent()\n+ spacingAroundColonRuleAssertThat(code)\n+ .hasLintViolations(\n+ LintViolation(2, 7, \"Unexpected spacing before \\\":\\\"\"),\n+ LintViolation(2, 7, \"Unexpected spacing after \\\":\\\"\"),\n+ LintViolation(4, 22, \"Unexpected spacing before \\\":\\\"\"),\n+ LintViolation(4, 22, \"Unexpected spacing after \\\":\\\"\"),\n+ LintViolation(4, 50, \"Unexpected spacing before \\\":\\\"\"),\n+ LintViolation(4, 50, \"Unexpected spacing after \\\":\\\"\"),\n+ LintViolation(8, 10, \"Unexpected spacing before \\\":\\\"\"),\n+ LintViolation(8, 10, \"Unexpected spacing after \\\":\\\"\"),\n+ LintViolation(12, 15, \"Unexpected spacing before \\\":\\\"\"),\n+ LintViolation(12, 15, \"Unexpected spacing after \\\":\\\"\"),\n+ ).isFormattedAs(formattedCode)\n }\n \n @Test\n", "problem_statement": "No spacing around colon in annotation\nSpacing should not be allowed around the colon in annotation and annotation entries regardless of the annotation target\r\n\r\n```\r\n@file:JvmName(\"Foo\") // allowed\r\n@file :JvmName(\"Foo\") // disallowed\r\n@file: JvmName(\"Foo\") // disallowed\r\n@file : JvmName(\"Foo\") // disallowed\r\n\r\n@set:[Inject VisibleForTesting] // allowed\r\n@set :[Inject VisibleForTesting] // disallowed\r\n@set: [Inject VisibleForTesting] // disallowed\r\n@set : [Inject VisibleForTesting] // disallowed\r\n```\n", "hints_text": "", "created_at": "2023-07-13T15:50:29Z", "version": "0.50", "FAIL_TO_PASS": [ "gradle_test_execution" ], "PASS_TO_PASS": [], "ERROR_TO_PASS": [], "environment_setup_commit": "0a2500665d514f27ad06828544c43a6f28924426" }, { "repo": "pinterest/ktlint", "pull_number": 1994, "instance_id": "pinterest__ktlint-1994", "issue_numbers": [ "1993" ], "base_commit": "b30515d816c8ab3773406a38cdc2fcc8b4971fde", "patch": "diff --git a/CHANGELOG.md b/CHANGELOG.md\nindex cba7fb047b..d6fdb9ef9d 100644\n--- a/CHANGELOG.md\n+++ b/CHANGELOG.md\n@@ -13,6 +13,7 @@ This project adheres to [Semantic Versioning](https://semver.org/).\n * Print absolute path of file in lint violations when flag \"--relative\" is not specified in Ktlint CLI ([#1963](https://github.com/pinterest/ktlint/issues/1963)) \n * Handle parameter `--code-style=android_studio` in Ktlint CLI identical to deprecated parameter `--android` ([#1982](https://github.com/pinterest/ktlint/issues/1982))\n * Prevent nullpointer exception (NPE) if class without body is followed by multiple blank lines until end of file `no-consecutive-blank-lines` ([#1987](https://github.com/pinterest/ktlint/issues/1987))\n+* Prevent nullpointer exception (NPE) if or operator at start of line is followed by dot qualified expression `indent` ([#1993](https://github.com/pinterest/ktlint/issues/1993))\n \n ### Changed\n * Separated Baseline functionality out of `ktlint-cli` into separate `ktlint-baseline` module for API consumers\ndiff --git a/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/IndentationRule.kt b/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/IndentationRule.kt\nindex 81142c414f..c802acac00 100644\n--- a/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/IndentationRule.kt\n+++ b/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/IndentationRule.kt\n@@ -1091,7 +1091,7 @@ public class IndentationRule :\n private fun ASTNode?.isElvisOperator() =\n this != null &&\n elementType == OPERATION_REFERENCE &&\n- firstChildNode.elementType == ELVIS\n+ firstChildNode?.elementType == ELVIS\n \n private fun ASTNode.acceptableTrailingSpaces(): String {\n require(elementType == WHITE_SPACE)\n", "test_patch": "diff --git a/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/IndentationRuleTest.kt b/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/IndentationRuleTest.kt\nindex f1c49672ef..8ba35fc243 100644\n--- a/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/IndentationRuleTest.kt\n+++ b/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/IndentationRuleTest.kt\n@@ -5122,6 +5122,32 @@ internal class IndentationRuleTest {\n }\n }\n \n+ @Test\n+ fun `Issue 1993 - An or operator at start of line followed by a dot qualified expressions should not throw an exception`() {\n+ val code =\n+ \"\"\"\n+ val foo =\n+ if (false\n+ || foobar.bar()\n+ ) {\n+ // Do something\n+ }\n+ \"\"\".trimIndent()\n+ val formattedCode =\n+ \"\"\"\n+ val foo =\n+ if (false ||\n+ foobar.bar()\n+ ) {\n+ // Do something\n+ }\n+ \"\"\".trimIndent()\n+ indentationRuleAssertThat(code)\n+ .addAdditionalRuleProvider { ChainWrappingRule() }\n+ .hasLintViolationForAdditionalRule(3, 9, \"Line must not begin with \\\"||\\\"\")\n+ .isFormattedAs(formattedCode)\n+ }\n+\n private companion object {\n val INDENT_STYLE_TAB =\n INDENT_STYLE_PROPERTY to PropertyType.IndentStyleValue.tab\n", "problem_statement": "Starting a line with || causes internal error from ktlint --format\n\r\n\r\n## Expected Behavior\r\nLines that start with `||` should not crash `ktlint --format --log-level=debug`\r\n\r\n## Observed Behavior\r\nAn internal error is reported:\r\n\r\n\r\n```\r\n16:58:56.355 [main] DEBUG com.pinterest.ktlint.cli.internal.KtlintServiceLoader - Discovered RuleSetProviderV3 with id 'standard' in ktlint JAR\r\n16:58:56.535 [main] DEBUG com.pinterest.ktlint.cli.internal.KtlintServiceLoader - Discovered ReporterProviderV2 with id 'baseline' in ktlint JAR\r\n16:58:56.535 [main] DEBUG com.pinterest.ktlint.cli.internal.KtlintServiceLoader - Discovered ReporterProviderV2 with id 'plain' in ktlint JAR\r\n16:58:56.536 [main] DEBUG com.pinterest.ktlint.cli.internal.KtlintServiceLoader - Discovered ReporterProviderV2 with id 'checkstyle' in ktlint JAR\r\n16:58:56.536 [main] DEBUG com.pinterest.ktlint.cli.internal.KtlintServiceLoader - Discovered ReporterProviderV2 with id 'json' in ktlint JAR\r\n16:58:56.536 [main] DEBUG com.pinterest.ktlint.cli.internal.KtlintServiceLoader - Discovered ReporterProviderV2 with id 'format' in ktlint JAR\r\n16:58:56.536 [main] DEBUG com.pinterest.ktlint.cli.internal.KtlintServiceLoader - Discovered ReporterProviderV2 with id 'html' in ktlint JAR\r\n16:58:56.536 [main] DEBUG com.pinterest.ktlint.cli.internal.KtlintServiceLoader - Discovered ReporterProviderV2 with id 'plain-summary' in ktlint JAR\r\n16:58:56.536 [main] DEBUG com.pinterest.ktlint.cli.internal.KtlintServiceLoader - Discovered ReporterProviderV2 with id 'sarif' in ktlint JAR\r\n16:58:56.536 [main] DEBUG com.pinterest.ktlint.cli.internal.ReporterAggregator - Initializing \"plain\" reporter with {plain=true, color=false, color_name=DARK_GRAY, format=true}\r\n16:58:56.550 [pool-1-thread-1] DEBUG com.pinterest.ktlint.rule.engine.api.KtLintRuleEngine - Starting with formatting file 'BreakKtlintFormatRule.kt'\r\n16:58:56.928 [pool-1-thread-1] DEBUG com.pinterest.ktlint.rule.engine.internal.EditorConfigLoader - Effective editorconfig properties for file '/Users/me/myProject/src/main/kotlin/com/my/lint/rules/BreakKtlintFormatRule.kt':\r\n\tend_of_line: lf\r\n\tij_kotlin_allow_trailing_comma: false\r\n\tij_kotlin_allow_trailing_comma_on_call_site: false\r\n\tij_kotlin_imports_layout: *\r\n\tij_kotlin_packages_to_use_import_on_demand: java.util.*,kotlinx.android.synthetic.**\r\n\tindent_size: 4\r\n\tindent_style: space\r\n\tinsert_final_newline: true\r\n\tktlint_code_style: android_studio\r\n\tktlint_function_signature_body_expression_wrapping: default\r\n\tktlint_function_signature_rule_force_multiline_when_parameter_count_greater_or_equal_than: 2147483647\r\n\tktlint_ignore_back_ticked_identifier: false\r\n\tmax_line_length: 300\r\n\ttab_width: 4\r\n16:58:56.934 [pool-1-thread-1] DEBUG com.pinterest.ktlint.rule.engine.internal.rulefilter.RunAfterRuleFilter - Rule with id 'standard:annotation' should run after the rule with id 'standard:enum-wrapping'. However, the latter rule is not loaded and is allowed to be ignored. For best results, it is advised load the rule.\r\n16:58:56.935 [pool-1-thread-1] DEBUG com.pinterest.ktlint.rule.engine.internal.rulefilter.RunAfterRuleFilter - Rule with id 'standard:indent' should run after the rule with id 'standard:function-signature'. However, the latter rule is not loaded and is allowed to be ignored. For best results, it is advised load the rule.\r\n16:58:56.935 [pool-1-thread-1] DEBUG com.pinterest.ktlint.rule.engine.internal.rulefilter.RunAfterRuleFilter - Rule with id 'standard:indent' should run after the rule with id 'standard:function-signature'. However, the latter rule is not loaded and is allowed to be ignored. For best results, it is advised load the rule.\r\n16:58:56.935 [pool-1-thread-1] DEBUG com.pinterest.ktlint.rule.engine.internal.rulefilter.RunAfterRuleFilter - Rule with id 'standard:indent' should run after the rule with id 'standard:function-signature'. However, the latter rule is not loaded and is allowed to be ignored. For best results, it is advised load the rule.\r\n16:58:56.948 [pool-1-thread-1] DEBUG com.pinterest.ktlint.rule.engine.internal.RuleProviderSorter - Rules will be executed in order below:\r\n - standard:annotation-spacing, \r\n - standard:chain-wrapping, \r\n - standard:class-naming, \r\n - standard:colon-spacing, \r\n - standard:comma-spacing, \r\n - standard:comment-spacing, \r\n - standard:comment-wrapping, \r\n - standard:curly-spacing, \r\n - standard:dot-spacing, \r\n - standard:double-colon-spacing, \r\n - standard:enum-entry-name-case, \r\n - standard:filename, \r\n - standard:final-newline, \r\n - standard:fun-keyword-spacing, \r\n - standard:function-return-type-spacing, \r\n - standard:function-start-of-body-spacing, \r\n - standard:function-type-reference-spacing, \r\n - standard:import-ordering, \r\n - standard:kdoc-wrapping, \r\n - standard:keyword-spacing, \r\n - standard:modifier-list-spacing, \r\n - standard:modifier-order, \r\n - standard:multiline-if-else, \r\n - standard:no-blank-line-before-rbrace, \r\n - standard:no-blank-lines-in-chained-method-calls, \r\n - standard:no-consecutive-blank-lines, \r\n - standard:no-empty-class-body, \r\n - standard:no-empty-first-line-in-method-block, \r\n - standard:no-line-break-after-else, \r\n - standard:no-line-break-before-assignment, \r\n - standard:no-multi-spaces, \r\n - standard:no-semi, \r\n - standard:no-trailing-spaces, \r\n - standard:no-unit-return, \r\n - standard:no-unused-imports, \r\n - standard:no-wildcard-imports, \r\n - standard:nullable-type-spacing, \r\n - standard:op-spacing, \r\n - standard:package-name, \r\n - standard:parameter-list-wrapping, \r\n - standard:parameter-wrapping, \r\n - standard:paren-spacing, \r\n - standard:property-wrapping, \r\n - standard:range-spacing, \r\n - standard:spacing-around-angle-brackets, \r\n - standard:spacing-between-declarations-with-annotations, \r\n - standard:spacing-between-declarations-with-comments, \r\n - standard:spacing-between-function-name-and-opening-parenthesis, \r\n - standard:string-template, \r\n - standard:unary-op-spacing, \r\n - standard:annotation, \r\n - standard:wrapping, \r\n - standard:argument-list-wrapping, \r\n - standard:trailing-comma-on-call-site, \r\n - standard:trailing-comma-on-declaration-site, \r\n - standard:indent, \r\n - standard:block-comment-initial-star-alignment, \r\n - standard:max-line-length\r\n16:58:57.039 [pool-1-thread-1] DEBUG com.pinterest.ktlint.cli.internal.KtlintCommandLine - Internal Error (standard:indent) in BreakKtlintFormatRule.kt at position '0:0\r\ncom.pinterest.ktlint.rule.engine.api.KtLintRuleException: Rule 'standard:indent' throws exception in file 'BreakKtlintFormatRule.kt' at position (0:0)\r\n Rule maintainer: KtLint\r\n Issue tracker : https://github.com/pinterest/ktlint/issues\r\n Repository : https://github.com/pinterest/ktlint\r\n\tat com.pinterest.ktlint.rule.engine.internal.RuleExecutionContext.executeRule(RuleExecutionContext.kt:64)\r\n\tat com.pinterest.ktlint.rule.engine.api.KtLintRuleEngine$format$3.invoke(KtLintRuleEngine.kt:136)\r\n\tat com.pinterest.ktlint.rule.engine.api.KtLintRuleEngine$format$3.invoke(KtLintRuleEngine.kt:135)\r\n\tat com.pinterest.ktlint.rule.engine.internal.VisitorProvider$visitor$3.invoke(VisitorProvider.kt:46)\r\n\tat com.pinterest.ktlint.rule.engine.internal.VisitorProvider$visitor$3.invoke(VisitorProvider.kt:44)\r\n\tat com.pinterest.ktlint.rule.engine.api.KtLintRuleEngine.format(KtLintRuleEngine.kt:135)\r\n\tat com.pinterest.ktlint.cli.internal.KtlintCommandLine.format(KtlintCommandLine.kt:479)\r\n\tat com.pinterest.ktlint.cli.internal.KtlintCommandLine.process(KtlintCommandLine.kt:465)\r\n\tat com.pinterest.ktlint.cli.internal.KtlintCommandLine.access$process(KtlintCommandLine.kt:64)\r\n\tat com.pinterest.ktlint.cli.internal.KtlintCommandLine$lintFiles$3.invoke$lambda$0(KtlintCommandLine.kt:416)\r\n\tat java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264)\r\n\tat java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1136)\r\n\tat java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:635)\r\n\tat java.base/java.lang.Thread.run(Thread.java:833)\r\nCaused by: java.lang.NullPointerException: Cannot invoke \"org.jetbrains.kotlin.com.intellij.lang.ASTNode.getElementType()\" because the return value of \"org.jetbrains.kotlin.com.intellij.lang.ASTNode.getFirstChildNode()\" is null\r\n\tat com.pinterest.ktlint.ruleset.standard.rules.IndentationRule.isElvisOperator(IndentationRule.kt:1094)\r\n\tat com.pinterest.ktlint.ruleset.standard.rules.IndentationRule.beforeVisitChildNodes(IndentationRule.kt:287)\r\n\tat com.pinterest.ktlint.rule.engine.internal.RuleExecutionContext$executeRuleOnNodeRecursively$1.invoke(RuleExecutionContext.kt:93)\r\n\tat com.pinterest.ktlint.rule.engine.internal.RuleExecutionContext$executeRuleOnNodeRecursively$1.invoke(RuleExecutionContext.kt:92)\r\n\tat com.pinterest.ktlint.rule.engine.internal.SuppressHandler.handle-dhiVX_g(SuppressHandler.kt:28)\r\n\tat com.pinterest.ktlint.rule.engine.internal.RuleExecutionContext.executeRuleOnNodeRecursively(RuleExecutionContext.kt:92)\r\n\tat com.pinterest.ktlint.rule.engine.internal.RuleExecutionContext.access$executeRuleOnNodeRecursively(RuleExecutionContext.kt:29)\r\n\tat com.pinterest.ktlint.rule.engine.internal.RuleExecutionContext$executeRuleOnNodeRecursively$2$1.invoke(RuleExecutionContext.kt:100)\r\n\tat com.pinterest.ktlint.rule.engine.internal.RuleExecutionContext$executeRuleOnNodeRecursively$2$1.invoke(RuleExecutionContext.kt:99)\r\n\tat com.pinterest.ktlint.rule.engine.internal.SuppressHandler.handle-dhiVX_g(SuppressHandler.kt:28)\r\n\tat com.pinterest.ktlint.rule.engine.internal.RuleExecutionContext.executeRuleOnNodeRecursively(RuleExecutionContext.kt:99)\r\n\tat com.pinterest.ktlint.rule.engine.internal.RuleExecutionContext.access$executeRuleOnNodeRecursively(RuleExecutionContext.kt:29)\r\n\tat com.pinterest.ktlint.rule.engine.internal.RuleExecutionContext$executeRuleOnNodeRecursively$2$1.invoke(RuleExecutionContext.kt:100)\r\n\tat com.pinterest.ktlint.rule.engine.internal.RuleExecutionContext$executeRuleOnNodeRecursively$2$1.invoke(RuleExecutionContext.kt:99)\r\n\tat com.pinterest.ktlint.rule.engine.internal.SuppressHandler.handle-dhiVX_g(SuppressHandler.kt:28)\r\n\tat com.pinterest.ktlint.rule.engine.internal.RuleExecutionContext.executeRuleOnNodeRecursively(RuleExecutionContext.kt:99)\r\n\tat com.pinterest.ktlint.rule.engine.internal.RuleExecutionContext.access$executeRuleOnNodeRecursively(RuleExecutionContext.kt:29)\r\n\tat com.pinterest.ktlint.rule.engine.internal.RuleExecutionContext$executeRuleOnNodeRecursively$2$1.invoke(RuleExecutionContext.kt:100)\r\n\tat com.pinterest.ktlint.rule.engine.internal.RuleExecutionContext$executeRuleOnNodeRecursively$2$1.invoke(RuleExecutionContext.kt:99)\r\n\tat com.pinterest.ktlint.rule.engine.internal.SuppressHandler.handle-dhiVX_g(SuppressHandler.kt:28)\r\n\tat com.pinterest.ktlint.rule.engine.internal.RuleExecutionContext.executeRuleOnNodeRecursively(RuleExecutionContext.kt:99)\r\n\tat com.pinterest.ktlint.rule.engine.internal.RuleExecutionContext.access$executeRuleOnNodeRecursively(RuleExecutionContext.kt:29)\r\n\tat com.pinterest.ktlint.rule.engine.internal.RuleExecutionContext$executeRuleOnNodeRecursively$2$1.invoke(RuleExecutionContext.kt:100)\r\n\tat com.pinterest.ktlint.rule.engine.internal.RuleExecutionContext$executeRuleOnNodeRecursively$2$1.invoke(RuleExecutionContext.kt:99)\r\n\tat com.pinterest.ktlint.rule.engine.internal.SuppressHandler.handle-dhiVX_g(SuppressHandler.kt:28)\r\n\tat com.pinterest.ktlint.rule.engine.internal.RuleExecutionContext.executeRuleOnNodeRecursively(RuleExecutionContext.kt:99)\r\n\tat com.pinterest.ktlint.rule.engine.internal.RuleExecutionContext.access$executeRuleOnNodeRecursively(RuleExecutionContext.kt:29)\r\n\tat com.pinterest.ktlint.rule.engine.internal.RuleExecutionContext$executeRuleOnNodeRecursively$2$1.invoke(RuleExecutionContext.kt:100)\r\n\tat com.pinterest.ktlint.rule.engine.internal.RuleExecutionContext$executeRuleOnNodeRecursively$2$1.invoke(RuleExecutionContext.kt:99)\r\n\tat com.pinterest.ktlint.rule.engine.internal.SuppressHandler.handle-dhiVX_g(SuppressHandler.kt:28)\r\n\tat com.pinterest.ktlint.rule.engine.internal.RuleExecutionContext.executeRuleOnNodeRecursively(RuleExecutionContext.kt:99)\r\n\tat com.pinterest.ktlint.rule.engine.internal.RuleExecutionContext.access$executeRuleOnNodeRecursively(RuleExecutionContext.kt:29)\r\n\tat com.pinterest.ktlint.rule.engine.internal.RuleExecutionContext$executeRuleOnNodeRecursively$2$1.invoke(RuleExecutionContext.kt:100)\r\n\tat com.pinterest.ktlint.rule.engine.internal.RuleExecutionContext$executeRuleOnNodeRecursively$2$1.invoke(RuleExecutionContext.kt:99)\r\n\tat com.pinterest.ktlint.rule.engine.internal.SuppressHandler.handle-dhiVX_g(SuppressHandler.kt:28)\r\n\tat com.pinterest.ktlint.rule.engine.internal.RuleExecutionContext.executeRuleOnNodeRecursively(RuleExecutionContext.kt:99)\r\n\tat com.pinterest.ktlint.rule.engine.internal.RuleExecutionContext.access$executeRuleOnNodeRecursively(RuleExecutionContext.kt:29)\r\n\tat com.pinterest.ktlint.rule.engine.internal.RuleExecutionContext$executeRuleOnNodeRecursively$2$1.invoke(RuleExecutionContext.kt:100)\r\n\tat com.pinterest.ktlint.rule.engine.internal.RuleExecutionContext$executeRuleOnNodeRecursively$2$1.invoke(RuleExecutionContext.kt:99)\r\n\tat com.pinterest.ktlint.rule.engine.internal.SuppressHandler.handle-dhiVX_g(SuppressHandler.kt:28)\r\n\tat com.pinterest.ktlint.rule.engine.internal.RuleExecutionContext.executeRuleOnNodeRecursively(RuleExecutionContext.kt:99)\r\n\tat com.pinterest.ktlint.rule.engine.internal.RuleExecutionContext.access$executeRuleOnNodeRecursively(RuleExecutionContext.kt:29)\r\n\tat com.pinterest.ktlint.rule.engine.internal.RuleExecutionContext$executeRuleOnNodeRecursively$2$1.invoke(RuleExecutionContext.kt:100)\r\n\tat com.pinterest.ktlint.rule.engine.internal.RuleExecutionContext$executeRuleOnNodeRecursively$2$1.invoke(RuleExecutionContext.kt:99)\r\n\tat com.pinterest.ktlint.rule.engine.internal.SuppressHandler.handle-dhiVX_g(SuppressHandler.kt:28)\r\n\tat com.pinterest.ktlint.rule.engine.internal.RuleExecutionContext.executeRuleOnNodeRecursively(RuleExecutionContext.kt:99)\r\n\tat com.pinterest.ktlint.rule.engine.internal.RuleExecutionContext.executeRule(RuleExecutionContext.kt:61)\r\n\t... 13 common frames omitted\r\nmyProject/src/main/kotlin/com/my/lint/rules/BreakKtlintFormatRule.kt:0:0: Internal Error (rule 'standard:indent') in BreakKtlintFormatRule.kt at position '0:0. Please create a ticket at https://github.com/pinterest/ktlint/issues and provide the source code that triggered an error.\r\ncom.pinterest.ktlint.rule.engine.api.KtLintRuleException: Rule 'standard:indent' throws exception in file 'BreakKtlintFormatRule.kt' at position (0:0)\r\n Rule maintainer: KtLint\r\n Issue tracker : https://github.com/pinterest/ktlint/issues\r\n Repository : https://github.com/pinterest/ktlint\r\n\tat com.pinterest.ktlint.rule.engine.internal.RuleExecutionContext.executeRule(RuleExecutionContext.kt:64)\r\n\tat com.pinterest.ktlint.rule.engine.api.KtLintRuleEngine$format$3.invoke(KtLintRuleEngine.kt:136)\r\n\tat com.pinterest.ktlint.rule.engine.api.KtLintRuleEngine$format$3.invoke(KtLintRuleEngine.kt:135)\r\n\tat com.pinterest.ktlint.rule.engine.internal.VisitorProvider$visitor$3.invoke(VisitorProvider.kt:46)\r\n\tat com.pinterest.ktlint.rule.engine.internal.VisitorProvider$visitor$3.invoke(VisitorProvider.kt:44)\r\n\tat com.pinterest.ktlint.rule.engine.api.KtLintRuleEngine.format(KtLintRuleEngine.kt:135)\r\n\tat com.pinterest.ktlint.cli.internal.KtlintCommandLine.format(KtlintCommandLine.kt:479)\r\n\tat com.pinterest.ktlint.cli.internal.KtlintCommandLine.process(KtlintCommandLine.kt:465)\r\n\tat com.pinterest.ktlint.cli.internal.KtlintCommandLine.access$process(KtlintCommandLine.kt:64)\r\n\tat com.pinterest.ktlint.cli.internal.KtlintCommandLine$lintFiles$3.invoke$lambda$0(KtlintCommandLine.kt:416)\r\n\tat java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264)\r\n\tat java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1136)\r\n\tat java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:635)\r\n\tat java.base/java.lang.Thread.run(Thread.java:833)\r\nCaused by: java.lang.NullPointerException: Cannot invoke \"org.jetbrains.kotlin.com.intellij.lang.ASTNode.getElementType()\" because the return value of \"org.jetbrains.kotlin.com.intellij.lang.ASTNode.getFirstChildNode()\" is null\r\n\tat com.pinterest.ktlint.ruleset.standard.rules.IndentationRule.isElvisOperator(IndentationRule.kt:1094)\r\n\tat com.pinterest.ktlint.ruleset.standard.rules.IndentationRule.beforeVisitChildNodes(IndentationRule.kt:287)\r\n\tat com.pinterest.ktlint.rule.engine.internal.RuleExecutionContext$executeRuleOnNodeRecursively$1.invoke(RuleExecutionContext.kt:93)\r\n\tat com.pinterest.ktlint.rule.engine.internal.RuleExecutionContext$executeRuleOnNodeRecursively$1.invoke(RuleExecutionContext.kt:92)\r\n\tat com.pinterest.ktlint.rule.engine.internal.SuppressHandler.handle-dhiVX_g(SuppressHandler.kt:28)\r\n\tat com.pinterest.ktlint.rule.engine.internal.RuleExecutionContext.executeRuleOnNodeRecursively(RuleExecutionContext.kt:92)\r\n\tat com.pinterest.ktlint.rule.engine.internal.RuleExecutionContext.access$executeRuleOnNodeRecursively(RuleExecutionContext.kt:29)\r\n\tat com.pinterest.ktlint.rule.engine.internal.RuleExecutionContext$executeRuleOnNodeRecursively$2$1.invoke(RuleExecutionContext.kt:100)\r\n\tat com.pinterest.ktlint.rule.engine.internal.RuleExecutionContext$executeRuleOnNodeRecursively$2$1.invoke(RuleExecutionContext.kt:99)\r\n\tat com.pinterest.ktlint.rule.engine.internal.SuppressHandler.handle-dhiVX_g(SuppressHandler.kt:28)\r\n\tat com.pinterest.ktlint.rule.engine.internal.RuleExecutionContext.executeRuleOnNodeRecursively(RuleExecutionContext.kt:99)\r\n\tat com.pinterest.ktlint.rule.engine.internal.RuleExecutionContext.access$executeRuleOnNodeRecursively(RuleExecutionContext.kt:29)\r\n\tat com.pinterest.ktlint.rule.engine.internal.RuleExecutionContext$executeRuleOnNodeRecursively$2$1.invoke(RuleExecutionContext.kt:100)\r\n\tat com.pinterest.ktlint.rule.engine.internal.RuleExecutionContext$executeRuleOnNodeRecursively$2$1.invoke(RuleExecutionContext.kt:99)\r\n\tat com.pinterest.ktlint.rule.engine.internal.SuppressHandler.handle-dhiVX_g(SuppressHandler.kt:28)\r\n\tat com.pinterest.ktlint.rule.engine.internal.RuleExecutionContext.executeRuleOnNodeRecursively(RuleExecutionContext.kt:99)\r\n\tat com.pinterest.ktlint.rule.engine.internal.RuleExecutionContext.access$executeRuleOnNodeRecursively(RuleExecutionContext.kt:29)\r\n\tat com.pinterest.ktlint.rule.engine.internal.RuleExecutionContext$executeRuleOnNodeRecursively$2$1.invoke(RuleExecutionContext.kt:100)\r\n\tat com.pinterest.ktlint.rule.engine.internal.RuleExecutionContext$executeRuleOnNodeRecursively$2$1.invoke(RuleExecutionContext.kt:99)\r\n\tat com.pinterest.ktlint.rule.engine.internal.SuppressHandler.handle-dhiVX_g(SuppressHandler.kt:28)\r\n\tat com.pinterest.ktlint.rule.engine.internal.RuleExecutionContext.executeRuleOnNodeRecursively(RuleExecutionContext.kt:99)\r\n\tat com.pinterest.ktlint.rule.engine.internal.RuleExecutionContext.access$executeRuleOnNodeRecursively(RuleExecutionContext.kt:29)\r\n\tat com.pinterest.ktlint.rule.engine.internal.RuleExecutionContext$executeRuleOnNodeRecursively$2$1.invoke(RuleExecutionContext.kt:100)\r\n\tat com.pinterest.ktlint.rule.engine.internal.RuleExecutionContext$executeRuleOnNodeRecursively$2$1.invoke(RuleExecutionContext.kt:99)\r\n\tat com.pinterest.ktlint.rule.engine.internal.SuppressHandler.handle-dhiVX_g(SuppressHandler.kt:28)\r\n\tat com.pinterest.ktlint.rule.engine.internal.RuleExecutionContext.executeRuleOnNodeRecursively(RuleExecutionContext.kt:99)\r\n\tat com.pinterest.ktlint.rule.engine.internal.RuleExecutionContext.access$executeRuleOnNodeRecursively(RuleExecutionContext.kt:29)\r\n\tat com.pinterest.ktlint.rule.engine.internal.RuleExecutionContext$executeRuleOnNodeRecursively$2$1.invoke(RuleExecutionContext.kt:100)\r\n\tat com.pinterest.ktlint.rule.engine.internal.RuleExecutionContext$executeRuleOnNodeRecursively$2$1.invoke(RuleExecutionContext.kt:99)\r\n\tat com.pinterest.ktlint.rule.engine.internal.SuppressHandler.handle-dhiVX_g(SuppressHandler.kt:28)\r\n\tat com.pinterest.ktlint.rule.engine.internal.RuleExecutionContext.executeRuleOnNodeRecursively(RuleExecutionContext.kt:99)\r\n\tat com.pinterest.ktlint.rule.engine.internal.RuleExecutionContext.access$executeRuleOnNodeRecursively(RuleExecutionContext.kt:29)\r\n\tat com.pinterest.ktlint.rule.engine.internal.RuleExecutionContext$executeRuleOnNodeRecursively$2$1.invoke(RuleExecutionContext.kt:100)\r\n\tat com.pinterest.ktlint.rule.engine.internal.RuleExecutionContext$executeRuleOnNodeRecursively$2$1.invoke(RuleExecutionContext.kt:99)\r\n\tat com.pinterest.ktlint.rule.engine.internal.SuppressHandler.handle-dhiVX_g(SuppressHandler.kt:28)\r\n\tat com.pinterest.ktlint.rule.engine.internal.RuleExecutionContext.executeRuleOnNodeRecursively(RuleExecutionContext.kt:99)\r\n\tat com.pinterest.ktlint.rule.engine.internal.RuleExecutionContext.access$executeRuleOnNodeRecursively(RuleExecutionContext.kt:29)\r\n\tat com.pinterest.ktlint.rule.engine.internal.RuleExecutionContext$executeRuleOnNodeRecursively$2$1.invoke(RuleExecutionContext.kt:100)\r\n\tat com.pinterest.ktlint.rule.engine.internal.RuleExecutionContext$executeRuleOnNodeRecursively$2$1.invoke(RuleExecutionContext.kt:99)\r\n\tat com.pinterest.ktlint.rule.engine.internal.SuppressHandler.handle-dhiVX_g(SuppressHandler.kt:28)\r\n\tat com.pinterest.ktlint.rule.engine.internal.RuleExecutionContext.executeRuleOnNodeRecursively(RuleExecutionContext.kt:99)\r\n\tat com.pinterest.ktlint.rule.engine.internal.RuleExecutionContext.access$executeRuleOnNodeRecursively(RuleExecutionContext.kt:29)\r\n\tat com.pinterest.ktlint.rule.engine.internal.RuleExecutionContext$executeRuleOnNodeRecursively$2$1.invoke(RuleExecutionContext.kt:100)\r\n\tat com.pinterest.ktlint.rule.engine.internal.RuleExecutionContext$executeRuleOnNodeRecursively$2$1.invoke(RuleExecutionContext.kt:99)\r\n\tat com.pinterest.ktlint.rule.engine.internal.SuppressHandler.handle-dhiVX_g(SuppressHandler.kt:28)\r\n\tat com.pinterest.ktlint.rule.engine.internal.RuleExecutionContext.executeRuleOnNodeRecursively(RuleExecutionContext.kt:99)\r\n\tat com.pinterest.ktlint.rule.engine.internal.RuleExecutionContext.executeRule(RuleExecutionContext.kt:61)\r\n\t... 13 more\r\n ()\r\n\r\nSummary error count (descending) by rule:\r\n An internal error occurred in the Ktlint Rule Engine: 1\r\n16:58:57.046 [main] DEBUG com.pinterest.ktlint.cli.internal.KtlintCommandLine - Finished processing in 702ms / 1 file(s) scanned / 1 error(s) found\r\n16:58:57.046 [main] DEBUG com.pinterest.ktlint.cli.internal.KtlintCommandLine - Exit ktlint with exit code: 1\r\n\r\n```\r\n\r\n## Steps to Reproduce\r\nProccess this code with `ktlint --format`:\r\n\r\n```\r\npackage com.my.lint.rules\r\n\r\nimport com.pinterest.ktlint.rule.engine.core.api.Rule\r\nimport com.pinterest.ktlint.rule.engine.core.api.RuleId\r\nimport org.jetbrains.kotlin.com.intellij.lang.ASTNode\r\n\r\nclass BreakKtlintFormatRule : Rule(\r\n RuleId(\"my-ruleset:my-rule-id\"),\r\n Rule.About(maintainer = \"Me\", repositoryUrl = \"repositoryUrl\", issueTrackerUrl = \"issueTrackerUrl\")\r\n) {\r\n\r\n override fun beforeVisitChildNodes(\r\n node: ASTNode,\r\n autoCorrect: Boolean,\r\n emit: (offset: Int, errorMessage: String, canBeAutoCorrected: Boolean) -> Unit\r\n ) {\r\n\r\n if (node.text.contains(\"this\")\r\n || node.text.contains(\"that\")\r\n ) {\r\n emit(node.startOffset, \"My violation detail\", false)\r\n }\r\n }\r\n}\r\n```\r\n\r\n\r\n## Your Environment\r\n* Version of ktlint used: 0.49.0\r\n* Relevant parts of the `.editorconfig` settings: None, but am using config generated by `ktlint generateEditorConfig --code-style=android_studio`\r\n* Name and version (or code for custom task) of integration used (Gradle plugin, Maven plugin, command line, custom Gradle task): Command line\r\n* Version of Gradle used (if applicable): N/A\r\n* Operating System and version: macOS 13.2\r\n\n", "hints_text": "", "created_at": "2023-05-05T18:38:16Z", "version": "0.49", "FAIL_TO_PASS": [ "gradle_test_execution" ], "PASS_TO_PASS": [], "ERROR_TO_PASS": [], "environment_setup_commit": "410d8849874f4d3600f9d4572e0850adccce4f2d" }, { "repo": "pinterest/ktlint", "pull_number": 2127, "instance_id": "pinterest__ktlint-2127", "issue_numbers": [ "920", "920" ], "base_commit": "76016af2de149fc61b125ced2451e9d3b4659853", "patch": "diff --git a/CHANGELOG.md b/CHANGELOG.md\nindex ef900bb62c..509cd20084 100644\n--- a/CHANGELOG.md\n+++ b/CHANGELOG.md\n@@ -12,7 +12,8 @@ This project adheres to [Semantic Versioning](https://semver.org/).\n \n * Allow to disable ktlint in `.editorconfig` for a glob ([#2100](https://github.com/pinterest/ktlint/issues/2100))\n * Fix wrapping of nested function literals `wrapping` ([#2106](https://github.com/pinterest/ktlint/issues/2106))\n-* Do not indent class body for classes having a long super type list in code style `ktlint_official` as it is inconsistent compared to other class bodies `indent` [#2115](https://github.com/pinterest/ktlint/issues/2115) \n+* Do not indent class body for classes having a long super type list in code style `ktlint_official` as it is inconsistent compared to other class bodies `indent` [#2115](https://github.com/pinterest/ktlint/issues/2115)\n+* In code style `ktlint_official` do not indent the closing parenthesis of a PARENTHESIZED expression `indent` [#920](https://github.com/pinterest/ktlint/issues/920) \n * Log message `Format was not able to resolve all violations which (theoretically) can be autocorrected in file ... in 3 consecutive runs of format` is now only displayed in case a new ktlint rule is actually needed. [#2129](https://github.com/pinterest/ktlint/issues/2129)\n * Fix wrapping of function signature in case the opening brace of the function body block exceeds the maximum line length. Fix upsert of whitespace into composite nodes. `function-signature` [#2130](https://github.com/pinterest/ktlint/issues/2130)\n * Fix spacing around colon in annotations `spacing-around-colon` ([#2093](https://github.com/pinterest/ktlint/issues/2093))\ndiff --git a/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/IndentationRule.kt b/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/IndentationRule.kt\nindex 2949883301..3c08326204 100644\n--- a/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/IndentationRule.kt\n+++ b/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/IndentationRule.kt\n@@ -245,9 +245,16 @@ public class IndentationRule :\n node.elementType == SECONDARY_CONSTRUCTOR ->\n visitSecondaryConstructor(node)\n \n- node.elementType == PARENTHESIZED &&\n- node.treeParent.treeParent.elementType != IF ->\n- startIndentContext(node)\n+ node.elementType == PARENTHESIZED ->\n+ if (codeStyle == ktlint_official) {\n+ // Contrary to the IntelliJ IDEA default formatter, do not indent the closing RPAR\n+ startIndentContext(\n+ fromAstNode = node,\n+ lastChildIndent = \"\",\n+ )\n+ } else if (node.treeParent.treeParent.elementType != IF) {\n+ startIndentContext(node)\n+ }\n \n node.elementType == BINARY_WITH_TYPE ||\n node.elementType == SUPER_TYPE_ENTRY ||\n@@ -1366,7 +1373,7 @@ private class StringTemplateIndenter(\n it.isLiteralStringTemplateEntry() ||\n it.isVariableStringTemplateEntry() ||\n it.isClosingQuote()\n- )\n+ )\n ) {\n val (actualIndent, actualContent) =\n if (it.isIndentBeforeClosingQuote()) {\ndiff --git a/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/NoSemicolonsRule.kt b/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/NoSemicolonsRule.kt\nindex 8c399150ae..b651dee99f 100644\n--- a/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/NoSemicolonsRule.kt\n+++ b/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/NoSemicolonsRule.kt\n@@ -67,26 +67,25 @@ public class NoSemicolonsRule :\n }\n }\n \n- private fun ASTNode?.doesNotRequirePreSemi(): Boolean {\n- if (this == null) {\n- return true\n- }\n- if (this is PsiWhiteSpace) {\n- val nextLeaf =\n+ private fun ASTNode?.doesNotRequirePreSemi() =\n+ when {\n+ this == null -> true\n+\n+ this is PsiWhiteSpace -> {\n nextLeaf {\n val psi = it.psi\n it !is PsiWhiteSpace &&\n it !is PsiComment &&\n psi.getStrictParentOfType() == null &&\n psi.getStrictParentOfType() == null\n+ }.let { nextLeaf ->\n+ nextLeaf == null || // \\s+ and then eof\n+ (textContains('\\n') && nextLeaf.elementType != KtTokens.LBRACE)\n }\n- return (\n- nextLeaf == null || // \\s+ and then eof\n- textContains('\\n') && nextLeaf.elementType != KtTokens.LBRACE\n- )\n+ }\n+\n+ else -> false\n }\n- return false\n- }\n \n private fun isNoSemicolonRequiredAfter(node: ASTNode): Boolean {\n val prevCodeLeaf =\ndiff --git a/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/SpacingAroundCurlyRule.kt b/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/SpacingAroundCurlyRule.kt\nindex 45259e5ed2..fa68f7a06f 100644\n--- a/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/SpacingAroundCurlyRule.kt\n+++ b/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/SpacingAroundCurlyRule.kt\n@@ -51,7 +51,7 @@ public class SpacingAroundCurlyRule : StandardRule(\"curly-spacing\") {\n (\n prevLeaf?.elementType == LPAR &&\n ((node as LeafPsiElement).parent is KtLambdaExpression || node.parent.parent is KtLambdaExpression)\n- )\n+ )\n spacingAfter = nextLeaf is PsiWhiteSpace || nextLeaf?.elementType == RBRACE\n if (prevLeaf is PsiWhiteSpace &&\n !prevLeaf.textContains('\\n') &&\n@@ -69,7 +69,7 @@ public class SpacingAroundCurlyRule : StandardRule(\"curly-spacing\") {\n prevLeaf.prevLeaf()?.let { it.elementType == RPAR || KtTokens.KEYWORDS.contains(it.elementType) } == true ||\n node.treeParent.elementType == CLASS_BODY ||\n (prevLeaf.treeParent.elementType == FUN && prevLeaf.treeNext.elementType != LAMBDA_EXPRESSION)\n- ) // allow newline for lambda return type\n+ ) // allow newline for lambda return type\n ) {\n emit(node.startOffset, \"Unexpected newline before \\\"${node.text}\\\"\", true)\n if (autoCorrect) {\n@@ -141,7 +141,7 @@ public class SpacingAroundCurlyRule : StandardRule(\"curly-spacing\") {\n nextElementType == LBRACKET ||\n nextElementType == LPAR ||\n nextElementType == COLONCOLON\n- )\n+ )\n }\n }\n \ndiff --git a/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/SpacingAroundParensRule.kt b/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/SpacingAroundParensRule.kt\nindex bdfa0fa3fb..10158fcd15 100644\n--- a/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/SpacingAroundParensRule.kt\n+++ b/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/SpacingAroundParensRule.kt\n@@ -42,11 +42,11 @@ public class SpacingAroundParensRule : StandardRule(\"paren-spacing\") {\n // Super keyword needs special-casing\n prevLeaf.prevLeaf()?.elementType == SUPER_KEYWORD ||\n prevLeaf.prevLeaf()?.treeParent?.elementType == PRIMARY_CONSTRUCTOR\n- ) &&\n+ ) &&\n (\n node.treeParent?.elementType == VALUE_PARAMETER_LIST ||\n node.treeParent?.elementType == VALUE_ARGUMENT_LIST\n- )\n+ )\n } else {\n prevLeaf is PsiWhiteSpace && !prevLeaf.textContains('\\n') &&\n prevLeaf.prevLeaf()?.elementType != LPAR\ndiff --git a/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/StringTemplateRule.kt b/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/StringTemplateRule.kt\nindex 52335cd8de..14b0c5a371 100644\n--- a/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/StringTemplateRule.kt\n+++ b/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/StringTemplateRule.kt\n@@ -63,7 +63,7 @@ public class StringTemplateRule : StandardRule(\"string-template\") {\n (\n nextSibling.elementType == LITERAL_STRING_TEMPLATE_ENTRY &&\n !nextSibling.text.substring(0, 1).isPartOfIdentifier()\n- )\n+ )\n }\n ) {\n emit(node.treePrev.startOffset + 2, \"Redundant curly braces\", true)\ndiff --git a/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/WrappingRule.kt b/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/WrappingRule.kt\nindex 706001a6ea..2a72cfee9b 100644\n--- a/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/WrappingRule.kt\n+++ b/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/WrappingRule.kt\n@@ -239,7 +239,7 @@ public class WrappingRule :\n numberOfArgs == 1 &&\n firstArg?.firstChildNode?.elementType\n ?.let { it == OBJECT_LITERAL || it == LAMBDA_EXPRESSION } == true\n- )\n+ )\n ) {\n return\n }\n@@ -308,7 +308,7 @@ public class WrappingRule :\n !(\n entries.dropLast(1).all { it.elementType == SUPER_TYPE_ENTRY } &&\n entries.last().elementType == SUPER_TYPE_CALL_ENTRY\n- )\n+ )\n ) {\n // put space after :\n if (!node.prevLeaf().isWhiteSpaceWithNewline()) {\n", "test_patch": "diff --git a/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/IndentationRuleTest.kt b/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/IndentationRuleTest.kt\nindex 95cbce439b..e35cdb2afc 100644\n--- a/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/IndentationRuleTest.kt\n+++ b/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/IndentationRuleTest.kt\n@@ -5322,6 +5322,24 @@ internal class IndentationRuleTest {\n .isFormattedAs(formattedCode)\n }\n \n+ @Test\n+ fun `Issue 920 - Given ktlint_official codestyle and a PARENTHESIZED expression`() {\n+ val code =\n+ \"\"\"\n+ val foobar =\n+ if (true) {\n+ (\n+ foo()\n+ )\n+ } else {\n+ bar()\n+ }\n+ \"\"\".trimIndent()\n+ indentationRuleAssertThat(code)\n+ .withEditorConfigOverride(CODE_STYLE_PROPERTY to ktlint_official)\n+ .hasNoLintViolations()\n+ }\n+\n private companion object {\n val INDENT_STYLE_TAB =\n INDENT_STYLE_PROPERTY to PropertyType.IndentStyleValue.tab\n", "problem_statement": "\")\" unexpectedly indented in expression but not in `if`\nGiven ktlint 0.39.0 and some code that looks like this:\r\n\r\n```\r\nval pass = if (condition1) { \r\n (\r\n condition2\r\n )\r\n } else {\r\n condition3\r\n }\r\n```\r\n\r\n## Expected Behavior:\r\nthis code seems to be formatted reasonably to us; we think ktlint should report no problems.\r\n\r\n## Observed Behavior:\r\nInstead we're observing it to request indenting \"condition2\" and \")\" to get this:\r\n\r\n```\r\nval pass = if (condition1) { \r\n (\r\n condition2\r\n )\r\n } else {\r\n condition3\r\n }\r\n```\r\n\r\nAt first I thought this seemed reasonable to me because it was presumably being treated as a line continuation, but then I checked what would happen if condition1 were multiple lines, and found in that case that ktlint requested that the parentheses of the `if` statement should be lined up:\r\n\r\n```\r\nif (\r\n condition1\r\n) { // indendation matching the corresponding \"(\"\r\n (\r\n condition2\r\n ) // indentation not matching the corresponding \"(\"\r\n} else {\r\n condition3\r\n}\r\n```\r\n\r\n## Your Environment\r\nWe encounter this when upgrading from ktlint 0.36.0 to 0.39.0\r\n\r\nThe full code in question: https://android-review.googlesource.com/c/platform/frameworks/support/+/1432017/2/compose/animation/animation-core/src/test/java/androidx/compose/animation/core/SpringEstimationTest.kt#139\n\")\" unexpectedly indented in expression but not in `if`\nGiven ktlint 0.39.0 and some code that looks like this:\r\n\r\n```\r\nval pass = if (condition1) { \r\n (\r\n condition2\r\n )\r\n } else {\r\n condition3\r\n }\r\n```\r\n\r\n## Expected Behavior:\r\nthis code seems to be formatted reasonably to us; we think ktlint should report no problems.\r\n\r\n## Observed Behavior:\r\nInstead we're observing it to request indenting \"condition2\" and \")\" to get this:\r\n\r\n```\r\nval pass = if (condition1) { \r\n (\r\n condition2\r\n )\r\n } else {\r\n condition3\r\n }\r\n```\r\n\r\nAt first I thought this seemed reasonable to me because it was presumably being treated as a line continuation, but then I checked what would happen if condition1 were multiple lines, and found in that case that ktlint requested that the parentheses of the `if` statement should be lined up:\r\n\r\n```\r\nif (\r\n condition1\r\n) { // indendation matching the corresponding \"(\"\r\n (\r\n condition2\r\n ) // indentation not matching the corresponding \"(\"\r\n} else {\r\n condition3\r\n}\r\n```\r\n\r\n## Your Environment\r\nWe encounter this when upgrading from ktlint 0.36.0 to 0.39.0\r\n\r\nThe full code in question: https://android-review.googlesource.com/c/platform/frameworks/support/+/1432017/2/compose/animation/animation-core/src/test/java/androidx/compose/animation/core/SpringEstimationTest.kt#139\n", "hints_text": "That is a known quirk of the Kotlin ide plugin formatter (whose behavior we are trying to match), please check #810 for details. I've also filed an issue on [youtrack](https://youtrack.jetbrains.com/issue/KT-41316) and have to close this until further notice from JB, as it seems to be expected behavior.\nI gave that YouTrack issue a thumbs up, which brought the total number of thumbs up to two. It's been two years, perhaps it's worth considering whether it could be okay to allow deviating from the IDE formatter in cases such as this? This looks super weird \ud83e\udd2a\nI also gave it a thumbs up. Any chance we could at least add a flag to allow deviation?\nReopened issue for investigation. If it gets solved, it will only be solved for the new code style `ktlint_official`.\nThat is a known quirk of the Kotlin ide plugin formatter (whose behavior we are trying to match), please check #810 for details. I've also filed an issue on [youtrack](https://youtrack.jetbrains.com/issue/KT-41316) and have to close this until further notice from JB, as it seems to be expected behavior.\nI gave that YouTrack issue a thumbs up, which brought the total number of thumbs up to two. It's been two years, perhaps it's worth considering whether it could be okay to allow deviating from the IDE formatter in cases such as this? This looks super weird \ud83e\udd2a\nI also gave it a thumbs up. Any chance we could at least add a flag to allow deviation?\nReopened issue for investigation. If it gets solved, it will only be solved for the new code style `ktlint_official`.", "created_at": "2023-07-13T16:41:46Z", "version": "0.50", "FAIL_TO_PASS": [ "gradle_test_execution" ], "PASS_TO_PASS": [], "ERROR_TO_PASS": [], "environment_setup_commit": "0a2500665d514f27ad06828544c43a6f28924426" }, { "repo": "pinterest/ktlint", "pull_number": 1991, "instance_id": "pinterest__ktlint-1991", "issue_numbers": [ "1987" ], "base_commit": "f408c888acbf2aa1a2bb11d7a7f32f68be9db413", "patch": "diff --git a/CHANGELOG.md b/CHANGELOG.md\nindex 6a6a2fb78a..8e7a7f981f 100644\n--- a/CHANGELOG.md\n+++ b/CHANGELOG.md\n@@ -11,6 +11,7 @@ This project adheres to [Semantic Versioning](https://semver.org/).\n ### Fixed\n * Store path of file containing a lint violation relative to the location of the baseline file itself ([#1962](https://github.com/pinterest/ktlint/issues/1962))\n * Handle parameter `--code-style=android_studio` in Ktlint CLI identical to deprecated parameter `--android` ([#1982](https://github.com/pinterest/ktlint/issues/1982))\n+* Prevent nullpointer exception (NPE) if class without body is followed by multiple blank lines until end of file `no-consecutive-blank-lines` ([#1987](https://github.com/pinterest/ktlint/issues/1987))\n \n ### Changed\n * Separated Baseline functionality out of `ktlint-cli` into separate `ktlint-baseline` module for API consumers\ndiff --git a/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/NoConsecutiveBlankLinesRule.kt b/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/NoConsecutiveBlankLinesRule.kt\nindex e215349c93..fc871a22c2 100644\n--- a/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/NoConsecutiveBlankLinesRule.kt\n+++ b/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/NoConsecutiveBlankLinesRule.kt\n@@ -62,7 +62,7 @@ public class NoConsecutiveBlankLinesRule : StandardRule(\"no-consecutive-blank-li\n ?.let { prevNode ->\n prevNode.elementType == IDENTIFIER &&\n prevNode.treeParent.elementType == CLASS &&\n- this.treeNext.elementType == PRIMARY_CONSTRUCTOR\n+ this.treeNext?.elementType == PRIMARY_CONSTRUCTOR\n }\n ?: false\n }\n", "test_patch": "diff --git a/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/NoConsecutiveBlankLinesRuleTest.kt b/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/NoConsecutiveBlankLinesRuleTest.kt\nindex db28d360e5..f93ee0b63a 100644\n--- a/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/NoConsecutiveBlankLinesRuleTest.kt\n+++ b/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/NoConsecutiveBlankLinesRuleTest.kt\n@@ -212,4 +212,13 @@ class NoConsecutiveBlankLinesRuleTest {\n \"\"\".trimIndent(),\n )\n }\n+\n+ @Test\n+ fun `Issue 1987 - Class without body but followed by multiple blank lines until end of file should not throw exception`() {\n+ val code = \"class Foo\\n\\n\\n\"\n+ val formattedCode = \"class Foo\\n\"\n+ noConsecutiveBlankLinesRuleAssertThat(code)\n+ .hasLintViolations(LintViolation(3, 1, \"Needless blank line(s)\"))\n+ .isFormattedAs(formattedCode)\n+ }\n }\n", "problem_statement": "NPE on consecutive blank lines in end of file with class without body\n\r\n\r\n## Expected Behavior\r\nKtlint should report an error of `no-consecutive-blank-lines` violation\r\n\r\n## Observed Behavior\r\nNPE\r\n\r\n```\r\n~/workspace > vim dummy.kt 48s 16:32:07\r\n~/workspace > ktlint dummy.kt 5s 16:32:18\r\ndummy.kt:1:23: Internal Error (rule 'standard:no-consecutive-blank-lines') in dummy.kt at position '1:23. Please create a ticket at https://github.com/pinterest/ktlint/issues and provide the source code that triggered an error.\r\ncom.pinterest.ktlint.rule.engine.api.KtLintRuleException: Rule 'standard:no-consecutive-blank-lines' throws exception in file 'dummy.kt' at position (1:23)\r\n Rule maintainer: KtLint\r\n Issue tracker : https://github.com/pinterest/ktlint/issues\r\n Repository : https://github.com/pinterest/ktlint\r\n\tat com.pinterest.ktlint.rule.engine.internal.RuleExecutionContext.executeRule(RuleExecutionContext.kt:64)\r\n\tat com.pinterest.ktlint.rule.engine.api.KtLintRuleEngine$lint$3.invoke(KtLintRuleEngine.kt:100)\r\n\tat com.pinterest.ktlint.rule.engine.api.KtLintRuleEngine$lint$3.invoke(KtLintRuleEngine.kt:99)\r\n\tat com.pinterest.ktlint.rule.engine.internal.VisitorProvider$visitor$3.invoke(VisitorProvider.kt:46)\r\n\tat com.pinterest.ktlint.rule.engine.internal.VisitorProvider$visitor$3.invoke(VisitorProvider.kt:44)\r\n\tat com.pinterest.ktlint.rule.engine.api.KtLintRuleEngine.lint(KtLintRuleEngine.kt:99)\r\n\tat com.pinterest.ktlint.cli.internal.KtlintCommandLine.lint(KtlintCommandLine.kt:542)\r\n\tat com.pinterest.ktlint.cli.internal.KtlintCommandLine.process(KtlintCommandLine.kt:467)\r\n\tat com.pinterest.ktlint.cli.internal.KtlintCommandLine.access$process(KtlintCommandLine.kt:64)\r\n\tat com.pinterest.ktlint.cli.internal.KtlintCommandLine$lintFiles$3.invoke$lambda$0(KtlintCommandLine.kt:416)\r\n\tat java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264)\r\n\tat java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1136)\r\n\tat java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:635)\r\n\tat java.base/java.lang.Thread.run(Thread.java:833)\r\nCaused by: java.lang.NullPointerException: Cannot invoke \"org.jetbrains.kotlin.com.intellij.lang.ASTNode.getElementType()\" because the return value of \"org.jetbrains.kotlin.com.intellij.lang.ASTNode.getTreeNext()\" is null\r\n\tat com.pinterest.ktlint.ruleset.standard.rules.NoConsecutiveBlankLinesRule.isBetweenClassAndPrimaryConstructor(NoConsecutiveBlankLinesRule.kt:65)\r\n\tat com.pinterest.ktlint.ruleset.standard.rules.NoConsecutiveBlankLinesRule.beforeVisitChildNodes(NoConsecutiveBlankLinesRule.kt:30)\r\n\tat com.pinterest.ktlint.rule.engine.internal.RuleExecutionContext$executeRuleOnNodeRecursively$1.invoke(RuleExecutionContext.kt:93)\r\n\tat com.pinterest.ktlint.rule.engine.internal.RuleExecutionContext$executeRuleOnNodeRecursively$1.invoke(RuleExecutionContext.kt:92)\r\n\tat com.pinterest.ktlint.rule.engine.internal.SuppressHandler.handle-dhiVX_g(SuppressHandler.kt:28)\r\n\tat com.pinterest.ktlint.rule.engine.internal.RuleExecutionContext.executeRuleOnNodeRecursively(RuleExecutionContext.kt:92)\r\n\tat com.pinterest.ktlint.rule.engine.internal.RuleExecutionContext.access$executeRuleOnNodeRecursively(RuleExecutionContext.kt:29)\r\n\tat com.pinterest.ktlint.rule.engine.internal.RuleExecutionContext$executeRuleOnNodeRecursively$2$1.invoke(RuleExecutionContext.kt:100)\r\n\tat com.pinterest.ktlint.rule.engine.internal.RuleExecutionContext$executeRuleOnNodeRecursively$2$1.invoke(RuleExecutionContext.kt:99)\r\n\tat com.pinterest.ktlint.rule.engine.internal.SuppressHandler.handle-dhiVX_g(SuppressHandler.kt:28)\r\n\tat com.pinterest.ktlint.rule.engine.internal.RuleExecutionContext.executeRuleOnNodeRecursively(RuleExecutionContext.kt:99)\r\n\tat com.pinterest.ktlint.rule.engine.internal.RuleExecutionContext.executeRule(RuleExecutionContext.kt:61)\r\n\t... 13 more\r\n```\r\n\r\n## Steps to Reproduce\r\n1. Create a file with just :\r\n```kotlin\r\nsealed class Hello\r\n\r\n\r\n\r\n```\r\n2. run ktlint on the file\r\n\r\n\r\n## Your Environment\r\n\r\n* Version of ktlint used: 0.49.0\r\n* Relevant parts of the `.editorconfig` settings: None\r\n* Name and version (or code for custom task) of integration used (Gradle plugin, Maven plugin, command line, custom Gradle task): CLI\r\n* Version of Gradle used (if applicable): N/A\r\n* Operating System and version: MacOS\r\n\n", "hints_text": "", "created_at": "2023-05-05T14:39:33Z", "version": "0.49", "FAIL_TO_PASS": [ "gradle_test_execution" ], "PASS_TO_PASS": [], "ERROR_TO_PASS": [], "environment_setup_commit": "410d8849874f4d3600f9d4572e0850adccce4f2d" }, { "repo": "pinterest/ktlint", "pull_number": 1826, "instance_id": "pinterest__ktlint-1826", "issue_numbers": [ "1711" ], "base_commit": "1469c486be0f0ce48b0a6b2ff397af4cc5eaa427", "patch": "diff --git a/CHANGELOG.md b/CHANGELOG.md\nindex 15d3221d6c..298af6b7f2 100644\n--- a/CHANGELOG.md\n+++ b/CHANGELOG.md\n@@ -212,6 +212,7 @@ Like before, the API Consumer can still offer a mix of rules originating from `k\n * Do not add the first line of a multiline body expression on the same line as the function signature in case function body expression wrapping property is set to `multiline`. `function-signature`. \n * Disable the `standard:filename` rule whenever Ktlint CLI is run with option `--stdin` ([#1742](https://github.com/pinterest/ktlint/issues/1742))\n * The parameters of a function literal containing a multiline parameter list are aligned with first parameter whenever the first parameter is on the same line as the start of that function literal (not allowed in `ktlint_official` code style) `indent` ([#1756](https://github.com/pinterest/ktlint/issues/1756)).\n+* Do not throw exception when enum class does not contain entries `trailing-comma-on-declaration-site` ([#1711](https://github.com/pinterest/ktlint/issues/1711))\n * Fix continuation indent for a dot qualified array access expression in `ktlint_official` code style only `indent` ([#1540](https://github.com/pinterest/ktlint/issues/1540)).\n * When generating the `.editorconfig` use value `off` for the `max_line_length` property instead of value `-1` to denote that lines are not restricted to a maximum length ([#1824](https://github.com/pinterest/ktlint/issues/1824)).\n \ndiff --git a/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/TrailingCommaOnDeclarationSiteRule.kt b/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/TrailingCommaOnDeclarationSiteRule.kt\nindex 18ebcfdcdd..5010ad175b 100644\n--- a/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/TrailingCommaOnDeclarationSiteRule.kt\n+++ b/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/TrailingCommaOnDeclarationSiteRule.kt\n@@ -198,34 +198,22 @@ public class TrailingCommaOnDeclarationSiteRule :\n .takeIf { psi.isEnum() }\n ?.findChildByType(ElementType.CLASS_BODY)\n ?.takeUnless {\n- // Do nothing when last two entries are on same line as no trailing comma should be inserted\n- it.lastTwoEnumEntriesAreOnSameLine()\n+ it.noEnumEntries() || it.lastTwoEnumEntriesAreOnSameLine()\n }?.let { classBody ->\n- val nodeAfterTrailingCommaPosition = classBody.findNodeAfterTrailingCommaPosition()\n- node.reportAndCorrectTrailingCommaNodeBefore(\n- inspectNode = nodeAfterTrailingCommaPosition,\n- isTrailingCommaAllowed = node.isTrailingCommaAllowed(),\n- autoCorrect = autoCorrect,\n- emit = emit,\n- )\n+ classBody\n+ .findNodeAfterLastEnumEntry()\n+ ?.let { nodeAfterLastEnumEntry ->\n+ node.reportAndCorrectTrailingCommaNodeBefore(\n+ inspectNode = nodeAfterLastEnumEntry,\n+ isTrailingCommaAllowed = node.isTrailingCommaAllowed(),\n+ autoCorrect = autoCorrect,\n+ emit = emit,\n+ )\n+ }\n }\n }\n \n- /**\n- * Determines the [ASTNode] before which the trailing comma is allowed.\n- *\n- * If the list of enumeration entries is terminated by a semicolon, that semicolon will be returned. Otherwise, the\n- * last element of the class.\n- */\n- private fun ASTNode.findNodeAfterTrailingCommaPosition(): ASTNode {\n- val lastEnumEntry = children().last { it.psi is KtEnumEntry }\n-\n- val semicolonAfterLastEnumEntry = lastEnumEntry\n- .children()\n- .singleOrNull { it.elementType == ElementType.SEMICOLON }\n-\n- return semicolonAfterLastEnumEntry ?: lastChildNode\n- }\n+ private fun ASTNode.noEnumEntries() = children().none { it.psi is KtEnumEntry }\n \n private fun ASTNode.lastTwoEnumEntriesAreOnSameLine(): Boolean {\n val lastTwoEnumEntries =\n@@ -237,6 +225,19 @@ public class TrailingCommaOnDeclarationSiteRule :\n return lastTwoEnumEntries.count() == 2 && noNewLineInClosedRange(lastTwoEnumEntries[0], lastTwoEnumEntries[1])\n }\n \n+ /**\n+ * Determines the [ASTNode] before which the trailing comma is allowed.\n+ *\n+ * If the list of enumeration entries is terminated by a semicolon, that semicolon will be returned. Otherwise, the\n+ * last element of the class.\n+ */\n+ private fun ASTNode.findNodeAfterLastEnumEntry() =\n+ children()\n+ .lastOrNull { it.psi is KtEnumEntry }\n+ ?.children()\n+ ?.singleOrNull { it.elementType == ElementType.SEMICOLON }\n+ ?: lastChildNode\n+\n private fun ASTNode.reportAndCorrectTrailingCommaNodeBefore(\n inspectNode: ASTNode,\n isTrailingCommaAllowed: Boolean,\n", "test_patch": "diff --git a/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/TrailingCommaOnDeclarationSiteRuleTest.kt b/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/TrailingCommaOnDeclarationSiteRuleTest.kt\nindex 541d323ad1..355e15fa02 100644\n--- a/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/TrailingCommaOnDeclarationSiteRuleTest.kt\n+++ b/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/TrailingCommaOnDeclarationSiteRuleTest.kt\n@@ -1033,4 +1033,17 @@ class TrailingCommaOnDeclarationSiteRuleTest {\n .hasNoLintViolationsForRuleId(\"no-semi\")\n .isFormattedAs(formattedCode)\n }\n+\n+ @Test\n+ fun `Issue 1711 - Given an empty enum class then do not throw an exception`() {\n+ val code =\n+ \"\"\"\n+ enum class Dummy(val type: String) {\n+ // empty\n+ }\n+ \"\"\".trimIndent()\n+ trailingCommaOnDeclarationSiteRuleAssertThat(code)\n+ .withEditorConfigOverride(TRAILING_COMMA_ON_DECLARATION_SITE_PROPERTY to true)\n+ .hasNoLintViolations()\n+ }\n }\n", "problem_statement": "ktlint raise error when there is empty enum class\n\r\n\r\n## Expected Behavior\r\n\r\n\r\n\r\n\r\nWhen kotlin project has empty enum class, ktlint raise error.\r\n\r\n```\r\n$ git clone https://github.com/ganadist/VersionCodeDemo -b ktlint_0471_error\r\n$ cd VersionCodeDemo\r\n$ ./gradlew :ktlint\r\n```\r\n\r\n## Observed Behavior\r\n\r\n\r\n\r\n\r\n```\r\n> Task :ktlint FAILED\r\n00:41:59.889 [main] DEBUG com.pinterest.ktlint.internal.KtlintCommandLine - Discovered reporter with \"baseline\" id.\r\n00:41:59.890 [main] DEBUG com.pinterest.ktlint.internal.KtlintCommandLine - Discovered reporter with \"checkstyle\" id.\r\n00:41:59.890 [main] DEBUG com.pinterest.ktlint.internal.KtlintCommandLine - Discovered reporter with \"json\" id.\r\n00:41:59.890 [main] DEBUG com.pinterest.ktlint.internal.KtlintCommandLine - Discovered reporter with \"format\" id.\r\n00:41:59.890 [main] DEBUG com.pinterest.ktlint.internal.KtlintCommandLine - Discovered reporter with \"html\" id.\r\n00:41:59.890 [main] DEBUG com.pinterest.ktlint.internal.KtlintCommandLine - Discovered reporter with \"plain\" id.\r\n00:41:59.890 [main] DEBUG com.pinterest.ktlint.internal.KtlintCommandLine - Discovered reporter with \"sarif\" id.\r\n00:41:59.890 [main] DEBUG com.pinterest.ktlint.internal.KtlintCommandLine - Initializing \"plain\" reporter with {verbose=false, color=false, color_name=DARK_GRAY, format=false}\r\n00:41:59.904 [main] DEBUG com.pinterest.ktlint.internal.FileUtils - Start walkFileTree for rootDir: 'VersionCodeDemo'\r\n include:\r\n[ - sun.nio.fs.UnixFileSystem$3@2e4b8173]\r\n exclude:\r\n[ - sun.nio.fs.UnixFileSystem$3@70e8f8e, - sun.nio.fs.UnixFileSystem$3@17046283, - sun.nio.fs.UnixFileSystem$3@5bd03f44, - sun.nio.fs.UnixFileSystem$3@29626d54, - sun.nio.fs.UnixFileSystem$3@5a63f509, - sun.nio.fs.UnixFileSystem$3@6e4784bc, - sun.nio.fs.UnixFileSystem$3@34b7ac2f, - sun.nio.fs.UnixFileSystem$3@e056f20]\r\n00:41:59.913 [main] DEBUG com.pinterest.ktlint.internal.FileUtils - Discovered 1 files to be processed in 9 ms\r\n00:42:00.357 [pool-1-thread-1] DEBUG com.pinterest.ktlint.core.internal.RuleRunnerSorter - Rule with id 'standard:indent' should run after the rule with id 'experimental:function-signature'. However, the latter rule is not loaded and is allowed to be ignored. For best results, it is advised load the rule.\r\n00:42:00.358 [pool-1-thread-1] DEBUG com.pinterest.ktlint.core.internal.RuleRunnerSorter - Rules will be executed in order below (unless disabled):\r\n - standard:annotation, \r\n - standard:annotation-spacing, \r\n - standard:argument-list-wrapping, \r\n - standard:chain-wrapping, \r\n - standard:colon-spacing, \r\n - standard:comma-spacing, \r\n - standard:comment-spacing, \r\n - standard:curly-spacing, \r\n - standard:dot-spacing, \r\n - standard:double-colon-spacing, \r\n - standard:enum-entry-name-case, \r\n - standard:filename, \r\n - standard:final-newline, \r\n - standard:import-ordering, \r\n - standard:keyword-spacing, \r\n - standard:modifier-order, \r\n - standard:multiline-if-else, \r\n - standard:no-blank-line-before-rbrace, \r\n - standard:no-blank-lines-in-chained-method-calls, \r\n - standard:no-consecutive-blank-lines, \r\n - standard:no-empty-class-body, \r\n - standard:no-empty-first-line-in-method-block, \r\n - standard:no-line-break-after-else, \r\n - standard:no-line-break-before-assignment, \r\n - standard:no-multi-spaces, \r\n - standard:no-semi, \r\n - standard:no-trailing-spaces, \r\n - standard:no-unit-return, \r\n - standard:no-unused-imports, \r\n - standard:no-wildcard-imports, \r\n - standard:op-spacing, \r\n - standard:package-name, \r\n - standard:parameter-list-wrapping, \r\n - standard:paren-spacing, \r\n - standard:range-spacing, \r\n - standard:spacing-around-angle-brackets, \r\n - standard:spacing-between-declarations-with-annotations, \r\n - standard:spacing-between-declarations-with-comments, \r\n - standard:string-template, \r\n - standard:unary-op-spacing, \r\n - standard:wrapping, \r\n - standard:indent, \r\n - standard:trailing-comma-on-call-site, \r\n - standard:max-line-length, \r\n - standard:trailing-comma-on-declaration-site\r\n00:42:00.407 [pool-1-thread-1] DEBUG com.pinterest.ktlint.internal.KtlintCommandLine - Internal Error (trailing-comma-on-declaration-site) in file '/home/ganadist/src/build/AndroidStudioProjects/vcd/lib/hostconfig/src/main/java/com/example/myapplication/hostconfig/TestView.kt' at position '1:1\r\ncom.pinterest.ktlint.core.RuleExecutionException: com.pinterest.ktlint.core.RuleExecutionException: com.pinterest.ktlint.core.RuleExecutionException: com.pinterest.ktlint.core.RuleExecutionException: java.util.NoSuchElementException: Sequence contains no element matching the predicate.\r\n\tat com.pinterest.ktlint.core.KtLint.executeRuleOnNodeRecursively(KtLint.kt:233)\r\n\tat com.pinterest.ktlint.core.KtLint.executeRule(KtLint.kt:195)\r\n\tat com.pinterest.ktlint.core.KtLint.access$executeRule(KtLint.kt:30)\r\n\tat com.pinterest.ktlint.core.KtLint$lint$1.invoke(KtLint.kt:176)\r\n\tat com.pinterest.ktlint.core.KtLint$lint$1.invoke(KtLint.kt:175)\r\n\tat com.pinterest.ktlint.core.internal.VisitorProvider$visitor$6.invoke(VisitorProvider.kt:80)\r\n\tat com.pinterest.ktlint.core.internal.VisitorProvider$visitor$6.invoke(VisitorProvider.kt:78)\r\n\tat com.pinterest.ktlint.core.KtLint.lint(KtLint.kt:175)\r\n\tat com.pinterest.ktlint.internal.FileUtilsKt.lintFile(FileUtils.kt:363)\r\n\tat com.pinterest.ktlint.internal.KtlintCommandLine.process(KtlintCommandLine.kt:410)\r\n\tat com.pinterest.ktlint.internal.KtlintCommandLine.access$process(KtlintCommandLine.kt:52)\r\n\tat com.pinterest.ktlint.internal.KtlintCommandLine$lintFiles$3.invoke$lambda-0(KtlintCommandLine.kt:313)\r\n\tat java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264)\r\n\tat java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)\r\n\tat java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)\r\n\tat java.base/java.lang.Thread.run(Thread.java:829)\r\nCaused by: com.pinterest.ktlint.core.RuleExecutionException: com.pinterest.ktlint.core.RuleExecutionException: com.pinterest.ktlint.core.RuleExecutionException: java.util.NoSuchElementException: Sequence contains no element matching the predicate.\r\n\tat com.pinterest.ktlint.core.KtLint.executeRuleOnNodeRecursively(KtLint.kt:233)\r\n\tat com.pinterest.ktlint.core.KtLint.executeRuleOnNodeRecursively(KtLint.kt:219)\r\n\t... 15 common frames omitted\r\nCaused by: com.pinterest.ktlint.core.RuleExecutionException: com.pinterest.ktlint.core.RuleExecutionException: java.util.NoSuchElementException: Sequence contains no element matching the predicate.\r\n\tat com.pinterest.ktlint.core.KtLint.executeRuleOnNodeRecursively(KtLint.kt:233)\r\n\tat com.pinterest.ktlint.core.KtLint.executeRuleOnNodeRecursively(KtLint.kt:219)\r\n\t... 16 common frames omitted\r\nCaused by: com.pinterest.ktlint.core.RuleExecutionException: java.util.NoSuchElementException: Sequence contains no element matching the predicate.\r\n\tat com.pinterest.ktlint.core.KtLint.executeRuleOnNodeRecursively(KtLint.kt:233)\r\n\tat com.pinterest.ktlint.core.KtLint.executeRuleOnNodeRecursively(KtLint.kt:219)\r\n\t... 17 common frames omitted\r\nCaused by: java.util.NoSuchElementException: Sequence contains no element matching the predicate.\r\n\tat com.pinterest.ktlint.ruleset.standard.TrailingCommaOnDeclarationSiteRule.findNodeAfterTrailingCommaPosition(TrailingCommaOnDeclarationSiteRule.kt:505)\r\n\tat com.pinterest.ktlint.ruleset.standard.TrailingCommaOnDeclarationSiteRule.visitClass(TrailingCommaOnDeclarationSiteRule.kt:205)\r\n\tat com.pinterest.ktlint.ruleset.standard.TrailingCommaOnDeclarationSiteRule.beforeVisitChildNodes(TrailingCommaOnDeclarationSiteRule.kt:88)\r\n\tat com.pinterest.ktlint.core.KtLint.executeRuleOnNodeRecursively(KtLint.kt:209)\r\n\t... 18 common frames omitted\r\nVersionCodeDemo/lib/hostconfig/src/main/java/com/example/myapplication/hostconfig/TestView.kt:1:1: Internal Error (trailing-comma-on-declaration-site) in file 'VersionCodeDemo/lib/hostconfig/src/main/java/com/example/myapplication/hostconfig/TestView.kt' at position '1:1. Please create a ticket at https://github.com/pinterest/ktlint/issues (if possible, please re-run with the --debug flag to get the stacktrace and provide the source code that triggered an error) (cannot be auto-corrected) ()\r\n00:42:00.409 [main] DEBUG com.pinterest.ktlint.internal.KtlintCommandLine - 555ms / 1 file(s) / 1 error(s)\r\n\r\n```\r\n\r\n## Steps to Reproduce\r\n\r\n\r\n\r\n\r\n\r\n* perform ktlint 0.47.1 or master branch with https://github.com/ganadist/VersionCodeDemo/blob/ktlint_0471_error/lib/hostconfig/src/main/java/com/example/myapplication/hostconfig/TestView.kt#L23-L25 code\r\n\r\n\r\n## Your Environment\r\n\r\n* Version of ktlint used: 0.47.1 / 0.48.0-SNAPSHOT\r\n* Relevant parts of the `.editorconfig` settings : https://github.com/ganadist/VersionCodeDemo/blob/ktlint_0471_error/.editorconfig \r\n* Name and version (or code for custom task) of integration used (Gradle plugin, Maven plugin, command line, custom Gradle task): https://github.com/ganadist/VersionCodeDemo/blob/ktlint_0471_error/gradle/ktlint.gradle\r\n* Version of Gradle used (if applicable): 7.5.1\r\n* Operating System and version: ArchLinux / OSX 13.0\r\n\n", "hints_text": "Tnx for reporting. It seems a rare edge case to me. I will skip it for the upcoming release (0.48) and fix it later.", "created_at": "2023-02-18T13:33:20Z", "version": "0.49", "FAIL_TO_PASS": [ "gradle_test_execution" ], "PASS_TO_PASS": [], "ERROR_TO_PASS": [], "environment_setup_commit": "410d8849874f4d3600f9d4572e0850adccce4f2d" }, { "repo": "pinterest/ktlint", "pull_number": 2134, "instance_id": "pinterest__ktlint-2134", "issue_numbers": [ "2128" ], "base_commit": "5c17a629234f324f9930d96629789a7201d1c2b7", "patch": "diff --git a/CHANGELOG.md b/CHANGELOG.md\nindex 78898ab3ed..7f615783a6 100644\n--- a/CHANGELOG.md\n+++ b/CHANGELOG.md\n@@ -17,6 +17,7 @@ This project adheres to [Semantic Versioning](https://semver.org/).\n * Log message `Format was not able to resolve all violations which (theoretically) can be autocorrected in file ... in 3 consecutive runs of format` is now only displayed in case a new ktlint rule is actually needed. [#2129](https://github.com/pinterest/ktlint/issues/2129)\n * Fix wrapping of function signature in case the opening brace of the function body block exceeds the maximum line length. Fix upsert of whitespace into composite nodes. `function-signature` [#2130](https://github.com/pinterest/ktlint/issues/2130)\n * Fix spacing around colon in annotations `spacing-around-colon` ([#2093](https://github.com/pinterest/ktlint/issues/2093))\n+* Do not wrap a binary expression after an elvis operator in case the max line length is exceeded ([#2128](https://github.com/pinterest/ktlint/issues/2128))\n * Fix indent of IS_EXPRESSION, PREFIX_EXPRESSION and POSTFIX_EXPRESSION in case it contains a linebreak `indent` [#2094](https://github.com/pinterest/ktlint/issues/2094)\n \n ### Changed\ndiff --git a/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/BinaryExpressionWrappingRule.kt b/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/BinaryExpressionWrappingRule.kt\nindex dbed17961a..119dc62bc6 100644\n--- a/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/BinaryExpressionWrappingRule.kt\n+++ b/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/BinaryExpressionWrappingRule.kt\n@@ -2,6 +2,7 @@ package com.pinterest.ktlint.ruleset.standard.rules\n \n import com.pinterest.ktlint.rule.engine.core.api.ElementType.BINARY_EXPRESSION\n import com.pinterest.ktlint.rule.engine.core.api.ElementType.CALL_EXPRESSION\n+import com.pinterest.ktlint.rule.engine.core.api.ElementType.ELVIS\n import com.pinterest.ktlint.rule.engine.core.api.ElementType.EQ\n import com.pinterest.ktlint.rule.engine.core.api.ElementType.FUN\n import com.pinterest.ktlint.rule.engine.core.api.ElementType.LAMBDA_ARGUMENT\n@@ -20,11 +21,13 @@ import com.pinterest.ktlint.rule.engine.core.api.editorconfig.INDENT_STYLE_PROPE\n import com.pinterest.ktlint.rule.engine.core.api.editorconfig.MAX_LINE_LENGTH_PROPERTY\n import com.pinterest.ktlint.rule.engine.core.api.firstChildLeafOrSelf\n import com.pinterest.ktlint.rule.engine.core.api.indent\n+import com.pinterest.ktlint.rule.engine.core.api.isWhiteSpaceWithNewline\n import com.pinterest.ktlint.rule.engine.core.api.leavesOnLine\n import com.pinterest.ktlint.rule.engine.core.api.nextCodeSibling\n import com.pinterest.ktlint.rule.engine.core.api.nextSibling\n import com.pinterest.ktlint.rule.engine.core.api.noNewLineInClosedRange\n import com.pinterest.ktlint.rule.engine.core.api.parent\n+import com.pinterest.ktlint.rule.engine.core.api.prevLeaf\n import com.pinterest.ktlint.rule.engine.core.api.prevSibling\n import com.pinterest.ktlint.rule.engine.core.api.upsertWhitespaceBeforeMe\n import com.pinterest.ktlint.ruleset.standard.StandardRule\n@@ -121,7 +124,16 @@ public class BinaryExpressionWrappingRule :\n if (node.isCallExpressionFollowedByLambdaArgument() || cannotBeWrappedAtOperationReference(operationReference)) {\n // Wrapping after operation reference might not be the best place in case of a call expression or just won't work as\n // the left hand side still does not fit on a single line\n- emit(operationReference.startOffset, \"Line is exceeding max line length\", false)\n+ val offset =\n+ operationReference\n+ .prevLeaf { it.isWhiteSpaceWithNewline() }\n+ ?.let { previousNewlineNode ->\n+ previousNewlineNode.startOffset +\n+ previousNewlineNode.text.indexOfLast { it == '\\n' } +\n+ 1\n+ }\n+ ?: operationReference.startOffset\n+ emit(offset, \"Line is exceeding max line length\", false)\n } else {\n operationReference\n .nextSibling()\n@@ -146,17 +158,21 @@ public class BinaryExpressionWrappingRule :\n .let { it?.elementType == LAMBDA_ARGUMENT }\n \n private fun cannotBeWrappedAtOperationReference(operationReference: ASTNode) =\n- operationReference\n- .takeUnless { it.nextCodeSibling()?.elementType == BINARY_EXPRESSION }\n- ?.let {\n- val stopAtOperationReferenceLeaf = operationReference.firstChildLeafOrSelf()\n- maxLineLength <=\n- it\n- .leavesOnLine()\n- .takeWhile { leaf -> leaf != stopAtOperationReferenceLeaf }\n- .lengthWithoutNewlinePrefix()\n- }\n- ?: false\n+ if (operationReference.firstChildNode.elementType == ELVIS) {\n+ true\n+ } else {\n+ operationReference\n+ .takeUnless { it.nextCodeSibling()?.elementType == BINARY_EXPRESSION }\n+ ?.let {\n+ val stopAtOperationReferenceLeaf = operationReference.firstChildLeafOrSelf()\n+ maxLineLength <=\n+ it\n+ .leavesOnLine()\n+ .takeWhile { leaf -> leaf != stopAtOperationReferenceLeaf }\n+ .lengthWithoutNewlinePrefix()\n+ }\n+ ?: false\n+ }\n \n private fun ASTNode.isOnLineExceedingMaxLineLength() = leavesOnLine().lengthWithoutNewlinePrefix() > maxLineLength\n \n", "test_patch": "diff --git a/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/BinaryExpressionWrappingRuleTest.kt b/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/BinaryExpressionWrappingRuleTest.kt\nindex c8e3a9f774..8adb2bede8 100644\n--- a/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/BinaryExpressionWrappingRuleTest.kt\n+++ b/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/BinaryExpressionWrappingRuleTest.kt\n@@ -176,9 +176,9 @@ class BinaryExpressionWrappingRuleTest {\n // When linting, a violation is reported for each operation reference. While when formatting, the nested binary expression\n // is evaluated (working from outside to inside). After wrapping an outer binary expression, the inner binary expressions\n // are evaluated and only wrapped again at the operation reference when needed.\n+ LintViolation(3, 1, \"Line is exceeding max line length\", canBeAutoCorrected = false),\n LintViolation(3, 35, \"Line is exceeding max line length. Break line after operator in binary expression\"),\n LintViolation(3, 63, \"Line is exceeding max line length. Break line after operator in binary expression\"),\n- LintViolation(3, 92, \"Line is exceeding max line length\", canBeAutoCorrected = false),\n ).isFormattedAs(formattedCode)\n }\n \n@@ -194,7 +194,7 @@ class BinaryExpressionWrappingRuleTest {\n \"\"\".trimIndent()\n binaryExpressionWrappingRuleAssertThat(code)\n .setMaxLineLength()\n- .hasLintViolationWithoutAutoCorrect(3, 36, \"Line is exceeding max line length\")\n+ .hasLintViolationWithoutAutoCorrect(3, 1, \"Line is exceeding max line length\")\n }\n \n @Test\n@@ -211,10 +211,9 @@ class BinaryExpressionWrappingRuleTest {\n \"\"\".trimIndent()\n binaryExpressionWrappingRuleAssertThat(code)\n .setMaxLineLength()\n- .hasLintViolationsWithoutAutoCorrect(\n+ .hasLintViolations(\n+ LintViolation(2, 1, \"Line is exceeding max line length\", canBeAutoCorrected = false),\n LintViolation(2, 12, \"Line is exceeding max line length. Break line between assignment and expression\"),\n- LintViolation(2, 20, \"Line is exceeding max line length. Break line after operator in binary expression\"),\n- LintViolation(2, 36, \"Line is exceeding max line length\"),\n )\n }\n \n@@ -307,6 +306,23 @@ class BinaryExpressionWrappingRuleTest {\n .setMaxLineLength()\n .addAdditionalRuleProvider { ArgumentListWrappingRule() }\n .addAdditionalRuleProvider { WrappingRule() }\n- .hasLintViolationWithoutAutoCorrect(3, 17, \"Line is exceeding max line length\")\n+ .hasLintViolationWithoutAutoCorrect(3, 1, \"Line is exceeding max line length\")\n+ }\n+\n+ @Test\n+ fun `Issue 2128 - Given an elvis expression exceeding the line length`() {\n+ val code =\n+ \"\"\"\n+ // $MAX_LINE_LENGTH_MARKER $EOL_CHAR\n+ val foo =\n+ bar\n+ ?: throw UnsupportedOperationException(\"foobar\")\n+ \"\"\".trimIndent()\n+ binaryExpressionWrappingRuleAssertThat(code)\n+ .setMaxLineLength()\n+ .addAdditionalRuleProvider { ArgumentListWrappingRule() }\n+ .addAdditionalRuleProvider { WrappingRule() }\n+ .addAdditionalRuleProvider { MaxLineLengthRule() }\n+ .hasLintViolationWithoutAutoCorrect(4, 1, \"Line is exceeding max line length\")\n }\n }\ndiff --git a/ktlint-test/src/main/kotlin/com/pinterest/ktlint/test/KtLintAssertThat.kt b/ktlint-test/src/main/kotlin/com/pinterest/ktlint/test/KtLintAssertThat.kt\nindex 55758b436f..c40587a03c 100644\n--- a/ktlint-test/src/main/kotlin/com/pinterest/ktlint/test/KtLintAssertThat.kt\n+++ b/ktlint-test/src/main/kotlin/com/pinterest/ktlint/test/KtLintAssertThat.kt\n@@ -76,8 +76,8 @@ public class KtLintAssertThat(\n */\n private val code: String,\n /**\n- * Providers of rules which have to be executed in addition to the main rule when linting/formatting the code. Note\n- * that lint errors for those rules are suppressed.\n+ * Providers of rules which have to be executed in addition to the main rule when linting/formatting the code. Note that lint errors for\n+ * those rules are suppressed.\n */\n private val additionalRuleProviders: MutableSet,\n /**\n@@ -89,8 +89,8 @@ public class KtLintAssertThat(\n private var kotlinScript = false\n \n /**\n- * Set the [EditorConfigOverride] properties to be used by the rule. This function can be called multiple times.\n- * Properties which have been set before, are silently overwritten with the new vale.\n+ * Set the [EditorConfigOverride] properties to be used by the rule. This function can be called multiple times. Properties which have\n+ * been set before, are silently overwritten with the new vale.\n */\n public fun withEditorConfigOverride(vararg properties: Pair, *>): KtLintAssertThat {\n editorConfigProperties.addAll(properties)\n@@ -99,9 +99,8 @@ public class KtLintAssertThat(\n }\n \n /**\n- * Set the [EditorConfigOverride] \"max_line_length\" property based on the EOL Marker which is places at the first\n- * line of the code sample. If the property has been set before via [withEditorConfigOverride] then that value is\n- * silently overwritten.\n+ * Set the [EditorConfigOverride] \"max_line_length\" property based on the EOL Marker which is places at the first line of the code\n+ * sample. If the property has been set before via [withEditorConfigOverride] then that value is silently overwritten.\n *\n * Example of usage:\n * ```\n@@ -145,16 +144,15 @@ public class KtLintAssertThat(\n }\n \n /**\n- * Adds a single provider of an additional rule to be executed when linting/formatting the code. This can to be used\n- * to unit test rules which are best to be tested in conjunction with other rules, for example wrapping and\n- * indenting.\n+ * Adds a single provider of an additional rule to be executed when linting/formatting the code. This can to be used to unit test rules\n+ * which are best to be tested in conjunction with other rules, for example wrapping and indenting.\n *\n * Caution:\n- * An additional rule provider for a rule which actually is executed before the rule under test, might result in\n- * unexpected [LintViolation] in case that additional rule is modifying the AST. During the [lint] phase, all rules\n- * are executed in parallel and as of that both the rule under test and the additional rule are using the exact same\n- * version of the AST. When, in the [format] stage the additional rule is run first, and if it modifies the AST,\n- * this could result in a [LintViolation] for the rule under test which is executed later than the additional rule.\n+ * An additional rule provider for a rule which actually is executed before the rule under test, might result in unexpected\n+ * [LintViolation] in case that additional rule is modifying the AST. During the [lint] phase, all rules are executed in parallel and as\n+ * of that both the rule under test and the additional rule are using the exact same version of the AST. When, in the [format] stage the\n+ * additional rule is run first, and if it modifies the AST, this could result in a [LintViolation] for the rule under test which is\n+ * executed later than the additional rule.\n *\n * Prefer to use [addAdditionalRuleProviders] when adding multiple providers of rules.\n */\n@@ -165,16 +163,15 @@ public class KtLintAssertThat(\n }\n \n /**\n- * Adds a single provider of an additional rule to be executed when linting/formatting the code. This can to be used\n- * to unit test rules which are best to be tested in conjunction with other rules, for example wrapping and\n- * indenting.\n+ * Adds a single provider of an additional rule to be executed when linting/formatting the code. This can to be used to unit test rules\n+ * which are best to be tested in conjunction with other rules, for example wrapping and indenting.\n *\n * Caution:\n- * An additional rule provider for a rule which actually is executed before the rule under test, might result in\n- * unexpected [LintViolation] in case that additional rule is modifying the AST. During the [lint] phase, all rules\n- * are executed in parallel and as of that both the rule under test and the additional rule are using the exact same\n- * version of the AST. When, in the [format] stage the additional rule is run first, and if it modifies the AST,\n- * this could result in a [LintViolation] for the rule under test which is executed later than the additional rule.\n+ * An additional rule provider for a rule which actually is executed before the rule under test, might result in unexpected\n+ * [LintViolation] in case that additional rule is modifying the AST. During the [lint] phase, all rules are executed in parallel and as\n+ * of that both the rule under test and the additional rule are using the exact same version of the AST. When, in the [format] stage the\n+ * additional rule is run first, and if it modifies the AST, this could result in a [LintViolation] for the rule under test which is\n+ * executed later than the additional rule.\n *\n * Prefer to use [addAdditionalRuleProvider] when only a singe provider of a rule is to be added.\n */\n@@ -208,8 +205,8 @@ public class KtLintAssertThat(\n ktLintAssertThatAssertable().hasNoLintViolationsExceptInAdditionalRules()\n \n /**\n- * Asserts that the code does contain given [LintViolation] which automatically can be corrected. This is a sugar\n- * coated version of [hasLintViolations] for the case that the code contains exactly one lint violation.\n+ * Asserts that the code does contain given [LintViolation] which automatically can be corrected. This is a sugar-coated version of\n+ * [hasLintViolations] for the case that the code contains exactly one lint violation.\n */\n public fun hasLintViolation(\n line: Int,\n@@ -218,16 +215,15 @@ public class KtLintAssertThat(\n ): KtLintAssertThatAssertable = ktLintAssertThatAssertable().hasLintViolation(line, col, detail)\n \n /**\n- * Asserts that the code does contain given [LintViolation]s which can be automatically corrected. Note that tests\n- * resulting in only one (type of) [LintViolation] are usually easier to comprehend.\n+ * Asserts that the code does contain given [LintViolation]s which can be automatically corrected. Note that tests resulting in only one\n+ * (type of) [LintViolation] are usually easier to comprehend.\n */\n public fun hasLintViolations(vararg expectedErrors: LintViolation): KtLintAssertThatAssertable =\n ktLintAssertThatAssertable().hasLintViolations(*expectedErrors)\n \n /**\n- * Asserts that the code does contain given [LintViolation] caused by an additional rule which automatically can be\n- * corrected. This is a sugar coated version of [hasLintViolations] for the case that the code contains exactly one\n- * lint violation.\n+ * Asserts that the code does contain given [LintViolation] caused by an additional rule which automatically can be corrected. This is a\n+ * sugar-coated version of [hasLintViolations] for the case that the code contains exactly one lint violation.\n */\n public fun hasLintViolationForAdditionalRule(\n line: Int,\n@@ -236,9 +232,8 @@ public class KtLintAssertThat(\n ): KtLintAssertThatAssertable = ktLintAssertThatAssertable().hasLintViolationForAdditionalRule(line, col, detail)\n \n /**\n- * Asserts that the code does contain given [LintViolation]s caused by an additional rules which can be\n- * automatically corrected. Note that tests resulting in only one (type of) [LintViolation] are usually easier to\n- * comprehend.\n+ * Asserts that the code does contain given [LintViolation]s caused by an additional rules which can be automatically corrected. Note\n+ * that tests resulting in only one (type of) [LintViolation] are usually easier to comprehend.\n */\n public fun hasLintViolationsForAdditionalRule(vararg expectedErrors: LintViolation): KtLintAssertThatAssertable =\n ktLintAssertThatAssertable().hasLintViolationsForAdditionalRules(*expectedErrors)\n@@ -258,8 +253,8 @@ public class KtLintAssertThat(\n ): Unit = ktLintAssertThatAssertable().hasLintViolationWithoutAutoCorrect(line, col, detail)\n \n /**\n- * Asserts that the code does contain the given [LintViolation]s which can not be automatically corrected. Note that\n- * tests resulting in only one [LintViolation] are usually easier to comprehend.\n+ * Asserts that the code does contain the given [LintViolation]s which can not be automatically corrected. Note that tests resulting in\n+ * only one [LintViolation] are usually easier to comprehend.\n */\n public fun hasLintViolationsWithoutAutoCorrect(vararg expectedErrors: LintViolation): Unit =\n ktLintAssertThatAssertable().hasLintViolationsWithoutAutocorrect(*expectedErrors)\n@@ -292,17 +287,17 @@ public class KtLintAssertThat(\n \n public companion object {\n /**\n- * Creates an assertThat assertion function for the rule provided by [provider]. This assertion function has\n- * extensions specifically for testing KtLint rules.\n+ * Creates an assertThat assertion function for the rule provided by [provider]. This assertion function has extensions specifically\n+ * for testing KtLint rules.\n */\n public fun assertThatRule(provider: () -> Rule): (String) -> KtLintAssertThat = RuleProvider { provider() }.assertThat()\n \n /**\n- * Creates an assertThat assertion function for the rule provided by [provider]. This assertion function has\n- * extensions specifically for testing KtLint rules. The rules provided via [additionalRuleProviders] are only\n- * executed during the format phase of the test. This means that the unit test only has to check the lint\n- * violations thrown by the rule for which the assertThat is created. But the code is formatted by both the rule\n- * and the rules provided by [additionalRuleProviders] in the order as defined by the rule definitions.\n+ * Creates an assertThat assertion function for the rule provided by [provider]. This assertion function has extensions specifically\n+ * for testing KtLint rules. The rules provided via [additionalRuleProviders] are only executed during the format phase of the test.\n+ * This means that the unit test only has to check the lint violations thrown by the rule for which the assertThat is created. But\n+ * the code is formatted by both the rule and the rules provided by [additionalRuleProviders] in the order as defined by the rule\n+ * definitions.\n */\n \n public fun assertThatRule(\n@@ -353,9 +348,8 @@ public class KtLintAssertThat(\n }\n \n /**\n- * Immutable assertable. Once the first assertion is made on [KtLintAssertThat] it is converted to the\n- * [KtLintAssertThatAssertable] which allows no further modifications of the internal state. This guarantees that all\n- * assertions operate on the same state.\n+ * Immutable assertable. Once the first assertion is made on [KtLintAssertThat] it is converted to the [KtLintAssertThatAssertable] which\n+ * allows no further modifications of the internal state. This guarantees that all assertions operate on the same state.\n */\n public class KtLintAssertThatAssertable(\n /** The provider of the rule which is the subject of the test, e.g. the rule for which the AssertThat is created. */\n@@ -371,8 +365,7 @@ public class KtLintAssertThatAssertable(\n private val ruleId = ruleProvider.createNewRuleInstance().ruleId\n \n /**\n- * Asserts that the code does not contain any [LintViolation]s caused by the rule associated with the\n- * KtLintAssertThat.\n+ * Asserts that the code does not contain any [LintViolation]s caused by the rule associated with the KtLintAssertThat.\n *\n * Note: When linting succeeds without errors, formatting is also checked.\n */\n@@ -428,13 +421,11 @@ public class KtLintAssertThatAssertable(\n /**\n * Asserts that the code does not contain any [LintViolation]s except in the additional formatting rules.\n *\n- * Note that this method can and should be chained with [isFormattedAs] to verify whether the code is correctly\n- * formatted.\n+ * Note that this method can and should be chained with [isFormattedAs] to verify whether the code is correctly formatted.\n *\n- * This method can be used when the rule which is associated with the KtLintAssertThat is not violated by the sample\n- * code, but the code is reformatted by the additional formatting rules. In case that rules are dependent on each\n- * other, a unit test cal still verify that code is formatted correctly even when the rule under test is not\n- * violated.\n+ * This method can be used when the rule which is associated with the KtLintAssertThat is not violated by the sample code, but the code\n+ * is reformatted by the additional formatting rules. In case that rules are dependent on each other, a unit test cal still verify that\n+ * code is formatted correctly even when the rule under test is not violated.\n */\n public fun hasNoLintViolationsExceptInAdditionalRules(): KtLintAssertThatAssertable {\n check(additionalRuleProviders.isNotEmpty()) {\n@@ -449,8 +440,8 @@ public class KtLintAssertThatAssertable(\n }\n \n /**\n- * Asserts that the code does contain given [LintViolation]. This is a sugar coated version of\n- * [hasLintViolation] for the case that the code contains exactly one lint violation.\n+ * Asserts that the code does contain given [LintViolation]. This is a sugar-coated version of [hasLintViolation] for the case that the\n+ * code contains exactly one lint violation.\n */\n public fun hasLintViolation(\n line: Int,\n@@ -466,8 +457,8 @@ public class KtLintAssertThatAssertable(\n )\n \n /**\n- * Asserts that the code does contain given [LintViolation] caused by an additional rule. This is a sugar coated\n- * version of [hasLintViolationsForAdditionalRules] for the case that the code contains exactly one lint violation.\n+ * Asserts that the code does contain given [LintViolation] caused by an additional rule. This is a sugar-coated version of\n+ * [hasLintViolationsForAdditionalRules] for the case that the code contains exactly one lint violation.\n */\n public fun hasLintViolationForAdditionalRule(\n line: Int,\n@@ -499,8 +490,7 @@ public class KtLintAssertThatAssertable(\n }\n \n /**\n- * Asserts that the code does contain given [LintViolation]s caused by additional rules and which can be\n- * automatically corrected.\n+ * Asserts that the code does contain given [LintViolation]s caused by additional rules and which can be automatically corrected.\n */\n public fun hasLintViolationsForAdditionalRules(vararg expectedErrors: LintViolation): KtLintAssertThatAssertable {\n check(expectedErrors.isNotEmpty())\n@@ -550,8 +540,7 @@ public class KtLintAssertThatAssertable(\n )\n \n /**\n- * Asserts that the code does contain the given [LintViolation]s and that those violations can not be automatically\n- * corrected.\n+ * Asserts that the code does contain the given [LintViolation]s and that those violations can not be automatically corrected.\n */\n public fun hasLintViolationsWithoutAutocorrect(vararg expectedLintViolations: LintViolation) {\n check(expectedLintViolations.isNotEmpty())\n@@ -591,14 +580,15 @@ public class KtLintAssertThatAssertable(\n detail = it.detail,\n canBeAutoCorrected = it.canBeAutoCorrected,\n )\n- }.toTypedArray()\n+ }.distinct()\n+ .toTypedArray()\n }\n \n- private fun List.filterAdditionalRulesOnly() = filter { it.ruleId != ruleId }\n+ private fun Set.filterAdditionalRulesOnly() = filter { it.ruleId != ruleId }.toSet()\n \n- private fun List.filterCurrentRuleOnly() = filter { it.ruleId == ruleId }\n+ private fun Set.filterCurrentRuleOnly() = filter { it.ruleId == ruleId }.toSet()\n \n- private fun List.toLintViolationsFields(): Array =\n+ private fun Set.toLintViolationsFields(): Array =\n map {\n LintViolationFields(\n line = it.line,\n@@ -606,13 +596,14 @@ public class KtLintAssertThatAssertable(\n detail = it.detail,\n canBeAutoCorrected = it.canBeAutoCorrected,\n )\n- }.toTypedArray()\n+ }.distinct()\n+ .toTypedArray()\n \n private fun createKtLintRuleEngine(): KtLintRuleEngine {\n val ruleProviders =\n setOf(ruleProvider)\n- // Also run the additional rules as the main rule might have a VisitorModifier which requires one or more of\n- // the additional rules to be loaded and enabled as well.\n+ // Also run the additional rules as the main rule might have a VisitorModifier which requires one or more of the additional\n+ // rules to be loaded and enabled as well.\n .plus(additionalRuleProviders)\n val editorConfigOverride =\n editorConfigOverride\n@@ -625,20 +616,21 @@ public class KtLintAssertThatAssertable(\n )\n }\n \n- private fun lint(): List {\n- val lintErrors = ArrayList()\n+ private fun lint(): Set {\n+ val lintErrors = mutableSetOf()\n createKtLintRuleEngine().lint(code) { lintError -> lintErrors.add(lintError) }\n return lintErrors\n }\n \n- private fun format(): Pair> {\n- val lintErrors = ArrayList()\n+ private fun format(): Pair> {\n+ val lintErrors = mutableSetOf()\n val formattedCode = createKtLintRuleEngine().format(code) { lintError, _ -> lintErrors.add(lintError) }\n return Pair(formattedCode, lintErrors)\n }\n \n- /* Representation of the field of the [LintError] that should be identical. Note that no comparison can be made\n- * against the original [LintError] as the [canBeAutoCorrected] flag is excluded from the hashcode.\n+ /**\n+ * Representation of the field of the [LintError] that should be identical. Note that no comparison can be made against the original\n+ * [LintError] as the [canBeAutoCorrected] flag is excluded from the hashcode.\n */\n private data class LintViolationFields(\n val line: Int,\n@@ -657,8 +649,8 @@ internal class MissingEolMarker : RuntimeException(\n )\n \n /**\n- * Expectation of the [LintError]. Contrary to the [LintError] it does not contain the ruleId. The ruleId will be\n- * derived from the rule for which the AssertThat was created.\n+ * Expectation of the [LintError]. Contrary to the [LintError] it does not contain the ruleId. The ruleId will be derived from the rule for\n+ * which the AssertThat was created.\n */\n public data class LintViolation(\n val line: Int,\n@@ -668,8 +660,7 @@ public data class LintViolation(\n )\n \n /**\n- * Enables the rule sets for the given set of [ruleProviders] unless the rule execution of that rule set was already\n- * provided.\n+ * Enables the rule sets for the given set of [ruleProviders] unless the rule execution of that rule set was already provided.\n */\n private fun EditorConfigOverride.extendWithRuleSetRuleExecutionsFor(ruleProviders: Set): EditorConfigOverride {\n val ruleSetRuleExecutions =\n", "problem_statement": "Endless loop in wrapping binary expression after elvis operator\nGiven code below:\r\n```\r\nval foo =\r\n bar\r\n ?:\r\n throw UnsupportedOperationException(\"xxxxxxxxxxx\")\r\n```\r\nand `.editorconfig`:\r\n```\r\nroot = true\r\n\r\n[**/*.{kt,kts}]\r\nmax_line_length = 60\r\nktlint_code_style = ktlint_official\r\nktlint_experimental = enabled\r\nktlint_standard = enabled\r\n```\r\nthen ktlint `0.50.0` is not able to format this in 3 consecutive runs:\r\n```\r\n20:32:35.107 [pool-1-thread-1] WARN com.pinterest.ktlint.rule.engine.api.KtLintRuleEngine - Format was not able to resolve all violations which (theoretically) can be autocorrected in file src/main/kotlin/Foo.kt in 3 consecutive runs of format.\r\n```\r\n\r\nAs a line may not end with `?:` ktlint merges the last two lines. This however results in wrapping the line again to the original situation. As of that an endless loop results.\n", "hints_text": "", "created_at": "2023-07-16T08:00:43Z", "version": "0.50", "FAIL_TO_PASS": [ "gradle_test_execution" ], "PASS_TO_PASS": [], "ERROR_TO_PASS": [], "environment_setup_commit": "0a2500665d514f27ad06828544c43a6f28924426" }, { "repo": "pinterest/ktlint", "pull_number": 2068, "instance_id": "pinterest__ktlint-2068", "issue_numbers": [ "1947" ], "base_commit": "ef4afbe7b634492181b72cca468d9e014dac1ebe", "patch": "diff --git a/.editorconfig b/.editorconfig\nindex 00a10e0581..01626914c0 100644\n--- a/.editorconfig\n+++ b/.editorconfig\n@@ -4,6 +4,7 @@ root = true\n [*]\n indent_style = space\n indent_size = 2\n+max_line_length = 140\n \n end_of_line = lf\n charset = utf-8\n@@ -26,8 +27,13 @@ ktlint_experimental = enabled\n # Don't allow any wildcard imports\n ij_kotlin_packages_to_use_import_on_demand = unset\n \n+# Prevent wildcard imports\n+ij_kotlin_name_count_to_use_star_import = 99\n+ij_kotlin_name_count_to_use_star_import_for_members = 99\n+\n [*.md]\n trim_trailing_whitespace = false\n+max_line_length = unset\n \n [gradle/verification-metadata.xml]\n indent_size = 3\ndiff --git a/CHANGELOG.md b/CHANGELOG.md\nindex 435c78789e..fe4aba945a 100644\n--- a/CHANGELOG.md\n+++ b/CHANGELOG.md\n@@ -4,6 +4,14 @@ This project adheres to [Semantic Versioning](https://semver.org/).\n \n ## Unreleased\n \n+### Deprecation of ktlint-enable and ktlint-disable directives\n+\n+The `ktlint-disable` and `ktlint-enable` directives are no longer supported. Ktlint rules can now only be suppressed using the `@Suppress` or `@SuppressWarnings` annotations. A new rule, `internal:ktlint-suppression`, is provided to replace the directives with annotations.\n+\n+API consumers do not need to provide this rule, but it does no harm when done.\n+\n+The `internal:ktlint-suppression` rule can not be disabled via the `.editorconfig` nor via `@Suppress` or `@SuppressWarnings` annotations.\n+\n ### Custom Rule Providers need to prepare for Kotlin 1.9\n \n In Kotlin 1.9 the extension points of the embedded kotlin compiler will change. Ktlint only uses the `org.jetbrains.kotlin.com.intellij.treeCopyHandler` extension point. This extension is not yet supported in 1.9, neither is it documented ([#KT-58704](https://youtrack.jetbrains.com/issue/KT-58704/Support-and-document-extension-point-org.jetbrains.kotlin.com.intellij.treeCopyHandler)). Without this extension point it might happen that your custom rules will throw exceptions during runtime. See [#1981](https://github.com/pinterest/ktlint/issues/1981).\n@@ -32,6 +40,7 @@ At this point in time, it is not yet decided what the next steps will be. Ktlint\n * Add new experimental rule `statement-wrapping` which ensures function, class, or other blocks statement body doesn't start or end at starting or ending braces of the block ([#1938](https://github.com/pinterest/ktlint/issues/1938))\n * Add new experimental rule `blank-line-before-declaration`. This rule requires a blank line before class, function or property declarations ([#1939](https://github.com/pinterest/ktlint/issues/1939))\n * Wrap multiple statements on same line `wrapping` ([#1078](https://github.com/pinterest/ktlint/issues/1078))\n+* Add new rule `ktlint-suppression` to replace the `ktlint-disable` and `ktlint-enable` directives with annotations. This rule can not be disabled via the `.editorconfig` ([#1947](https://github.com/pinterest/ktlint/issues/1947))\n * Inform user about using `--format` option of KtLint CLI when finding a violation that can be autocorrected ([#1071](https://github.com/pinterest/ktlint/issues/1071))\n \n ### Removed\ndiff --git a/documentation/snapshot/docs/faq.md b/documentation/snapshot/docs/faq.md\nindex c7343c8f45..31a6601b82 100644\n--- a/documentation/snapshot/docs/faq.md\n+++ b/documentation/snapshot/docs/faq.md\n@@ -43,21 +43,17 @@ See [adding a custom rule set](../api/custom-rule-set/) for more information.\n !!! tip\n Suppressing a `ktlint` violation is meant primarily as an escape latch for the rare cases when **ktlint** is not able to produce the correct result. Please report any such instances using [GitHub Issues](https://github.com/pinterest/ktlint/issues)).\n \n-To disable a specific rule you'll need the rule identifier which is displayed at the end of the lint error.\n+To disable a specific rule you'll need the fully qualified rule identifier. This identifier is displayed at the end of the lint error. In case your code was autocorrected, you need to revert the code and run the `lint` task instead of the `format` to find the rule identifier.\n \n-An error can be suppressed using:\n+As of Ktlint 0.50, an error can only be suppressed using @Suppress or @SuppressWarnings annotations\n \n-* EOL comments\n-* Block comments\n-* @Suppress annotations\n-\n-=== \"[:material-heart:](#) Suppress annotation\"\n+=== \"[:material-heart:](#) Allowed\"\n \n ```kotlin\n // Suppressing all rules for the entire file\n @file:Suppress(\"ktlint\")\n \n- // Suppress a single rule (with id 'rule-id', defined in rule set with id 'rule-set-id') from the annotated construct\n+ // Suppress a single rule (with id 'rule-id', defined in rule set with id 'rule-set-id') in the scope of the annotated construct\n @Suppress(\"ktlint:rule-set-id:rule-id\")\n class Foo {}\n \n@@ -69,43 +65,6 @@ An error can be suppressed using:\n @Suppress(\"ktlint\")\n import foo.*\n ```\n-=== \"[:material-heart:](#) EOL comments\"\n-\n- ```kotlin\n- // Suppress a single rule for the commented line\n- import foo.* // ktlint-disable standard_no-wildcard-imports\n-\n- // Suppress multiple rules for the commented line\n- import foo.* // ktlint-disable standard_no-wildcard-imports standard_other-rule-id\n-\n- // Suppress all rules for the commented line\n- import foo.* // ktlint-disable\n- ```\n-\n-=== \"[:material-heart-off-outline:](#) Block comments\"\n-\n- ```kotlin\n- // Suppress a single rule for all code between the start and end tag\n- /* ktlint-disable standard_no-wildcard-imports */\n- import foo.*\n- /* ktlint-disable standard_no-wildcard-imports */\n-\n- // Suppress multiple rules for all code between the start and end tag\n- /* ktlint-disable standard_no-wildcard-imports standard_no-wildcard-imports */\n- import foo.*\n- /* ktlint-enable standard_no-wildcard-imports standard_no-wildcard-imports */\n-\n- // Suppress all rules for all code between the start and end tag\n- /* ktlint-disable */\n- import foo.*\n- /* ktlint-enable */\n- ```\n-\n-!!! important\n- When using the block comments, the `ktlint-enable` directive needs to specify the exact same rule-id's and in the same order as the `ktlint-disable` directive.\n-\n-!!! warning\n- From a consistency perspective seen, it might be best to **not** mix the (EOL/Block) comment style with the annotation style in the same project.\n \n ## How do I globally disable a rule without `.editorconfig`?\n \ndiff --git a/documentation/snapshot/docs/rules/experimental.md b/documentation/snapshot/docs/rules/experimental.md\nindex b7b92ac4f6..95de4adc34 100644\n--- a/documentation/snapshot/docs/rules/experimental.md\n+++ b/documentation/snapshot/docs/rules/experimental.md\n@@ -465,10 +465,6 @@ A single line block comment should be replaced with an EOL comment when possible\n */\n val foo = \"foo\" // Some comment\n val foo = { /* no-op */ }\n-\n- /* ktlint-disable foo-rule-id bar-rule-id */\n- val foo = \"foo\"\n- /* ktlint-enable foo-rule-id bar-rule-id */\n ```\n === \"[:material-heart-off-outline:](#) Disallowed\"\n \ndiff --git a/documentation/snapshot/docs/rules/standard.md b/documentation/snapshot/docs/rules/standard.md\nindex 8539f5cfef..1711bcfe42 100644\n--- a/documentation/snapshot/docs/rules/standard.md\n+++ b/documentation/snapshot/docs/rules/standard.md\n@@ -251,6 +251,54 @@ Indentation formatting - respects `.editorconfig` `indent_size` with no continua\n \n Rule id: `indent` (`standard` rule set)\n \n+## Ktlint-suppression rule\n+\n+The `ktlint-disable` and `ktlint-enable` directives are no longer supported as of ktlint version `0.50.0`. This rule migrates the directives to Suppress or SuppressWarnings annotations.\n+\n+Identifiers in the @Suppress and @SuppressWarnings annotations to suppress ktlint rules are checked for validity and autocorrected when possible. \n+\n+=== \"[:material-heart:](#) Ktlint\"\n+\n+ ```kotlin\n+ @file:Suppress(\"ktlint:standard:no-wildcard-imports\")\n+\n+ class FooBar {\n+ @Suppress(\"ktlint:standard:max-line-length\")\n+ val foo = \"some longggggggggggggggggggg text\"\n+\n+ fun bar() =\n+ @Suppress(\"ktlint:standard:no-multi-spaces\")\n+ listOf(\n+ \"1 One\", \n+ \"10 Ten\", \n+ \"100 Hundred\", \n+ )\n+ }\n+ ```\n+=== \"[:material-heart-off-outline:](#) Disallowed\"\n+\n+ ```kotlin\n+ /* ktlint-disable standard:no-wildcard-imports */\n+\n+ class FooBar {\n+ val foo = \"some longggggggggggggggggggg text\" // ktlint-disable standard:max-line-length\n+\n+ fun bar() =\n+ listOf(\n+ /* ktlint-disable standard:no-multi-spaces */\n+ \"1 One\", \n+ \"10 Ten\", \n+ \"100 Hundred\", \n+ /* ktlint-enable standard:no-multi-spaces */\n+ )\n+ }\n+ ```\n+\n+Rule id: `ktlint-suppression` (`standard` rule set)\n+\n+!!! note\n+ This rule can not be disabled in the `.editorconfig`.\n+\n ## Max line length\n \n Ensures that lines do not exceed the given length of `.editorconfig` property `max_line_length` (see [EditorConfig](../configuration-ktlint/) section for more). This rule does not apply in a number of situations. For example, in the case a line exceeds the maximum line length due to a comment that disables ktlint rules then that comment is being ignored when validating the length of the line. The `.editorconfig` property `ktlint_ignore_back_ticked_identifier` can be set to ignore identifiers which are enclosed in backticks, which for example is very useful when you want to allow longer names for unit tests.\ndiff --git a/ktlint-rule-engine/build.gradle.kts b/ktlint-rule-engine/build.gradle.kts\nindex 1c4daf4bb0..b9be8c80ca 100644\n--- a/ktlint-rule-engine/build.gradle.kts\n+++ b/ktlint-rule-engine/build.gradle.kts\n@@ -11,4 +11,5 @@ dependencies {\n \n testImplementation(projects.ktlintTest)\n testImplementation(projects.ktlintRulesetStandard)\n+ testRuntimeOnly(libs.logback)\n }\ndiff --git a/ktlint-rule-engine/src/main/kotlin/com/pinterest/ktlint/rule/engine/api/KtLintRuleEngine.kt b/ktlint-rule-engine/src/main/kotlin/com/pinterest/ktlint/rule/engine/api/KtLintRuleEngine.kt\nindex f8c897033e..3fdbdc1129 100644\n--- a/ktlint-rule-engine/src/main/kotlin/com/pinterest/ktlint/rule/engine/api/KtLintRuleEngine.kt\n+++ b/ktlint-rule-engine/src/main/kotlin/com/pinterest/ktlint/rule/engine/api/KtLintRuleEngine.kt\n@@ -25,7 +25,6 @@ import org.ec4j.core.Resource\n import org.ec4j.core.model.PropertyType.EndOfLineValue.crlf\n import org.ec4j.core.model.PropertyType.EndOfLineValue.lf\n import org.jetbrains.kotlin.com.intellij.lang.FileASTNode\n-import org.jetbrains.kotlin.utils.addToStdlib.ifFalse\n import java.nio.charset.StandardCharsets\n import java.nio.file.FileSystem\n import java.nio.file.FileSystems\n@@ -108,7 +107,14 @@ public class KtLintRuleEngine(\n .invoke { rule ->\n ruleExecutionContext.executeRule(rule, false) { offset, errorMessage, canBeAutoCorrected ->\n val (line, col) = ruleExecutionContext.positionInTextLocator(offset)\n- errors.add(LintError(line, col, rule.ruleId, errorMessage, canBeAutoCorrected))\n+ LintError(line, col, rule.ruleId, errorMessage, canBeAutoCorrected)\n+ .let { lintError ->\n+ errors.add(lintError)\n+ // In trace mode report the violation immediately. The order in which violations are actually found might be\n+ // different from the order in which they are reported. For debugging purposes it can be helpful to know the\n+ // exact order in which violations are being solved.\n+ LOGGER.trace { \"Lint violation: ${lintError.logMessage(code)}\" }\n+ }\n }\n }\n \n@@ -155,21 +161,20 @@ public class KtLintRuleEngine(\n ruleExecutionContext.rebuildSuppressionLocator()\n }\n val (line, col) = ruleExecutionContext.positionInTextLocator(offset)\n- errors.add(\n- Pair(\n- LintError(line, col, rule.ruleId, errorMessage, canBeAutoCorrected),\n- // It is assumed that a rule that emits that an error can be autocorrected, also\n- // does correct the error.\n- canBeAutoCorrected,\n- ),\n- )\n- // In trace mode report the violation immediately. The order in which violations are actually found might be different\n- // from the order in which they are reported. For debugging purposes it cn be helpful to know the exact order in which\n- // violations are being solved.\n- LOGGER.trace {\n- \"Format violation: ${code.fileNameOrStdin()}:$line:$col: $errorMessage (${rule.ruleId})\" +\n- canBeAutoCorrected.ifFalse { \" [cannot be autocorrected]\" }\n- }\n+ LintError(line, col, rule.ruleId, errorMessage, canBeAutoCorrected)\n+ .let { lintError ->\n+ errors.add(\n+ Pair(\n+ lintError,\n+ // It is assumed that a rule that emits that an error can be autocorrected, also does correct the error.\n+ canBeAutoCorrected,\n+ ),\n+ )\n+ // In trace mode report the violation immediately. The order in which violations are actually found might be\n+ // different from the order in which they are reported. For debugging purposes it can be helpful to know the\n+ // exact order in which violations are being solved.\n+ LOGGER.trace { \"Format violation: ${lintError.logMessage(code)}\" }\n+ }\n }\n }\n } while (mutated && formatRunCount < MAX_FORMAT_RUNS_PER_FILE)\n@@ -270,6 +275,14 @@ public class KtLintRuleEngine(\n \n public fun transformToAst(code: Code): FileASTNode = createRuleExecutionContext(this, code).rootNode\n \n+ private fun LintError.logMessage(code: Code) =\n+ \"${code.fileNameOrStdin()}:$line:$col: $detail ($ruleId)\" +\n+ if (canBeAutoCorrected) {\n+ \"\"\n+ } else {\n+ \" [cannot be autocorrected]\"\n+ }\n+\n public companion object {\n internal const val UTF8_BOM = \"\\uFEFF\"\n \ndiff --git a/ktlint-rule-engine/src/main/kotlin/com/pinterest/ktlint/rule/engine/internal/RuleExecutionContext.kt b/ktlint-rule-engine/src/main/kotlin/com/pinterest/ktlint/rule/engine/internal/RuleExecutionContext.kt\nindex fee8e1c763..f5ec6eec62 100644\n--- a/ktlint-rule-engine/src/main/kotlin/com/pinterest/ktlint/rule/engine/internal/RuleExecutionContext.kt\n+++ b/ktlint-rule-engine/src/main/kotlin/com/pinterest/ktlint/rule/engine/internal/RuleExecutionContext.kt\n@@ -10,9 +10,10 @@ import com.pinterest.ktlint.rule.engine.core.api.Rule\n import com.pinterest.ktlint.rule.engine.core.api.RuleProvider\n import com.pinterest.ktlint.rule.engine.core.api.editorconfig.CODE_STYLE_PROPERTY\n import com.pinterest.ktlint.rule.engine.core.api.editorconfig.EditorConfig\n+import com.pinterest.ktlint.rule.engine.internal.rulefilter.InternalRuleProvidersFilter\n import com.pinterest.ktlint.rule.engine.internal.rulefilter.RuleExecutionRuleFilter\n import com.pinterest.ktlint.rule.engine.internal.rulefilter.RunAfterRuleFilter\n-import com.pinterest.ktlint.rule.engine.internal.rulefilter.ruleProviders\n+import com.pinterest.ktlint.rule.engine.internal.rulefilter.applyRuleFilters\n import mu.KotlinLogging\n import org.jetbrains.kotlin.com.intellij.lang.ASTNode\n import org.jetbrains.kotlin.com.intellij.lang.FileASTNode\n@@ -180,7 +181,8 @@ internal class RuleExecutionContext private constructor(\n \n val ruleProviders =\n ktLintRuleEngine\n- .ruleProviders(\n+ .applyRuleFilters(\n+ InternalRuleProvidersFilter(ktLintRuleEngine),\n RuleExecutionRuleFilter(editorConfig),\n RunAfterRuleFilter(),\n )\ndiff --git a/ktlint-rule-engine/src/main/kotlin/com/pinterest/ktlint/rule/engine/internal/RuleProviderSorter.kt b/ktlint-rule-engine/src/main/kotlin/com/pinterest/ktlint/rule/engine/internal/RuleProviderSorter.kt\nindex f2e8cab23a..df3d121595 100644\n--- a/ktlint-rule-engine/src/main/kotlin/com/pinterest/ktlint/rule/engine/internal/RuleProviderSorter.kt\n+++ b/ktlint-rule-engine/src/main/kotlin/com/pinterest/ktlint/rule/engine/internal/RuleProviderSorter.kt\n@@ -5,6 +5,7 @@ import com.pinterest.ktlint.rule.engine.core.api.Rule\n import com.pinterest.ktlint.rule.engine.core.api.RuleId\n import com.pinterest.ktlint.rule.engine.core.api.RuleProvider\n import com.pinterest.ktlint.rule.engine.core.api.RuleSetId\n+import com.pinterest.ktlint.rule.engine.internal.rules.KTLINT_SUPPRESSION_RULE_ID\n import mu.KotlinLogging\n \n private val LOGGER = KotlinLogging.logger {}.initKtLintKLogger()\n@@ -104,6 +105,14 @@ internal class RuleProviderSorter {\n // The sort order below should guarantee a stable order of the rule between multiple invocations of KtLint given\n // the same set of input parameters. There should be no dependency on data ordering outside this class.\n compareBy {\n+ if (it.ruleId == KTLINT_SUPPRESSION_RULE_ID) {\n+ // This rule replaces the old ktlint-disable directives with @Suppress or @SuppressWarnings annotations. It should run as\n+ // first rule as the SuppressionLocatorBuilder no longer transforms the ktlint-disable directives to suppressions.\n+ 0\n+ } else {\n+ 1\n+ }\n+ }.thenBy {\n if (it.runAsLateAsPossible) {\n 1\n } else {\ndiff --git a/ktlint-rule-engine/src/main/kotlin/com/pinterest/ktlint/rule/engine/internal/SuppressionLocatorBuilder.kt b/ktlint-rule-engine/src/main/kotlin/com/pinterest/ktlint/rule/engine/internal/SuppressionLocatorBuilder.kt\nindex 3a70af99ac..fe2d2d1a1d 100644\n--- a/ktlint-rule-engine/src/main/kotlin/com/pinterest/ktlint/rule/engine/internal/SuppressionLocatorBuilder.kt\n+++ b/ktlint-rule-engine/src/main/kotlin/com/pinterest/ktlint/rule/engine/internal/SuppressionLocatorBuilder.kt\n@@ -1,6 +1,5 @@\n package com.pinterest.ktlint.rule.engine.internal\n \n-import com.pinterest.ktlint.logger.api.initKtLintKLogger\n import com.pinterest.ktlint.rule.engine.core.api.RuleId\n import com.pinterest.ktlint.rule.engine.core.api.editorconfig.EditorConfig\n import com.pinterest.ktlint.rule.engine.core.api.isWhiteSpaceWithNewline\n@@ -9,7 +8,7 @@ import com.pinterest.ktlint.rule.engine.core.util.safeAs\n import com.pinterest.ktlint.rule.engine.internal.SuppressionLocatorBuilder.CommentSuppressionHint.Type.BLOCK_END\n import com.pinterest.ktlint.rule.engine.internal.SuppressionLocatorBuilder.CommentSuppressionHint.Type.BLOCK_START\n import com.pinterest.ktlint.rule.engine.internal.SuppressionLocatorBuilder.CommentSuppressionHint.Type.EOL\n-import mu.KotlinLogging\n+import com.pinterest.ktlint.rule.engine.internal.rules.KTLINT_SUPPRESSION_RULE_ID\n import org.jetbrains.kotlin.com.intellij.lang.ASTNode\n import org.jetbrains.kotlin.com.intellij.psi.PsiComment\n import org.jetbrains.kotlin.com.intellij.psi.PsiElement\n@@ -30,8 +29,6 @@ internal object SuppressionLocatorBuilder {\n */\n private val NO_SUPPRESSION: SuppressionLocator = { _, _ -> false }\n \n- private val LOGGER = KotlinLogging.logger {}.initKtLintKLogger()\n-\n /**\n * Mapping of non-ktlint annotations to ktlint-annotation so that ktlint rules will be suppressed automatically\n * when specific non-ktlint annotations are found. The prevents that developers have to specify multiple annotations\n@@ -39,17 +36,17 @@ internal object SuppressionLocatorBuilder {\n */\n private val SUPPRESS_ANNOTATION_RULE_MAP =\n mapOf(\n- // It would have been nice if the official rule id's as defined in the Rules themselves could have been used here. But that would\n- // introduce a circular dependency between the ktlint-rule-engine and the ktlint-ruleset-standard modules.\n- \"EnumEntryName\" to RuleId(\"standard:enum-entry-name-case\"),\n- \"RemoveCurlyBracesFromTemplate\" to RuleId(\"standard:string-template\"),\n- \"ClassName\" to RuleId(\"standard:class-naming\"),\n- \"FunctionName\" to RuleId(\"standard:function-naming\"),\n- \"PackageName\" to RuleId(\"standard:package-name\"),\n- \"PropertyName\" to RuleId(\"standard:property-naming\"),\n+ // It would have been nice if the official rule id's as defined in the Rules themselves could have been used here. But that\n+ // would introduce a circular dependency between the ktlint-rule-engine and the ktlint-ruleset-standard modules.\n+ \"EnumEntryName\" to \"standard:enum-entry-name-case\",\n+ \"RemoveCurlyBracesFromTemplate\" to \"standard:string-template\",\n+ \"ClassName\" to \"standard:class-naming\",\n+ \"FunctionName\" to \"standard:function-naming\",\n+ \"PackageName\" to \"standard:package-name\",\n+ \"PropertyName\" to \"standard:property-naming\",\n )\n private val SUPPRESS_ANNOTATIONS = setOf(\"Suppress\", \"SuppressWarnings\")\n- private val SUPPRESS_ALL_KTLINT_RULES_RULE_ID = RuleId(\"ktlint:suppress-all-rules\")\n+ private const val ALL_KTLINT_RULES_SUPPRESSION_ID = \"ktlint:suppress-all-rules\"\n \n /**\n * Builds [SuppressionLocator] for given [rootNode] of AST tree.\n@@ -68,9 +65,15 @@ internal object SuppressionLocatorBuilder {\n \n private fun toSuppressedRegionsLocator(hintsList: List): SuppressionLocator =\n { offset, ruleId ->\n- hintsList\n- .filter { offset in it.range }\n- .any { hint -> hint.disabledRuleIds.isEmpty() || hint.disabledRuleIds.contains(ruleId) }\n+ if (ruleId == KTLINT_SUPPRESSION_RULE_ID) {\n+ // The rule to detect deprecated rule directives may not be disabled itself as otherwise the directives\n+ // will not be reported and fixed.\n+ false\n+ } else {\n+ hintsList\n+ .filter { offset in it.range }\n+ .any { hint -> hint.disabledRuleIds.isEmpty() || hint.disabledRuleIds.contains(ruleId.value) }\n+ }\n }\n \n private fun collect(\n@@ -118,11 +121,11 @@ internal object SuppressionLocatorBuilder {\n .trim()\n .split(\" \")\n .takeIf { it.isNotEmpty() }\n- ?.takeIf { it[0] == KTLINT_DISABLE || it[0] == formatterTags.formatterTagOff }\n+ ?.takeIf { it[0] == formatterTags.formatterTagOff }\n ?.let { parts ->\n CommentSuppressionHint(\n this,\n- HashSet(parts.tailToRuleIds()),\n+ HashSet(parts.tail()),\n EOL,\n )\n }\n@@ -135,16 +138,16 @@ internal object SuppressionLocatorBuilder {\n .split(\" \")\n .takeIf { it.isNotEmpty() }\n ?.let { parts ->\n- if (parts[0] == KTLINT_DISABLE || parts[0] == formatterTags.formatterTagOff) {\n+ if (parts[0] == formatterTags.formatterTagOff) {\n CommentSuppressionHint(\n this,\n- HashSet(parts.tailToRuleIds()),\n+ HashSet(parts.tail()),\n BLOCK_START,\n )\n- } else if (parts[0] == KTLINT_ENABLE || parts[0] == formatterTags.formatterTagOn) {\n+ } else if (parts[0] == formatterTags.formatterTagOn) {\n CommentSuppressionHint(\n this,\n- HashSet(parts.tailToRuleIds()),\n+ HashSet(parts.tail()),\n BLOCK_END,\n )\n } else {\n@@ -173,7 +176,6 @@ internal object SuppressionLocatorBuilder {\n \n BLOCK_END -> {\n // match open hint\n- Unit\n blockCommentSuppressionHints\n .lastOrNull { it.disabledRuleIds == commentSuppressionHint.disabledRuleIds }\n ?.let { openHint ->\n@@ -204,8 +206,6 @@ internal object SuppressionLocatorBuilder {\n ?.let { it.startOffset + it.text.lastIndexOf('\\n') + 1 }\n ?: 0\n \n- private fun List.tailToRuleIds() = tail().mapNotNull { createRuleIdOrNull(it) }\n-\n private fun List.tail() = this.subList(1, this.size)\n \n /**\n@@ -225,22 +225,22 @@ internal object SuppressionLocatorBuilder {\n .let { suppressedRuleIds ->\n when {\n suppressedRuleIds.isEmpty() -> null\n- suppressedRuleIds.contains(SUPPRESS_ALL_KTLINT_RULES_RULE_ID) ->\n+ suppressedRuleIds.contains(ALL_KTLINT_RULES_SUPPRESSION_ID) ->\n SuppressionHint(\n- IntRange(ktAnnotated.startOffset, ktAnnotated.endOffset),\n+ IntRange(ktAnnotated.startOffset, ktAnnotated.endOffset - 1),\n emptySet(),\n )\n \n else ->\n SuppressionHint(\n- IntRange(ktAnnotated.startOffset, ktAnnotated.endOffset),\n+ IntRange(ktAnnotated.startOffset, ktAnnotated.endOffset - 1),\n suppressedRuleIds.toSet(),\n )\n }\n }\n }\n \n- private fun ValueArgument.toRuleId(annotationValueToRuleMapping: Map): RuleId? =\n+ private fun ValueArgument.toRuleId(annotationValueToRuleMapping: Map): String? =\n getArgumentExpression()\n ?.text\n ?.removeSurrounding(\"\\\"\")\n@@ -248,13 +248,15 @@ internal object SuppressionLocatorBuilder {\n when {\n argumentExpressionText == \"ktlint\" -> {\n // Disable all rules\n- SUPPRESS_ALL_KTLINT_RULES_RULE_ID\n+ ALL_KTLINT_RULES_SUPPRESSION_ID\n }\n argumentExpressionText.startsWith(\"ktlint:\") -> {\n- // Disable specific rule\n+ // Disable specific rule. For backwards compatibility prefix rules without rule set id with the \"standard\" rule set\n+ // id. Note that the KtlintSuppressionRule will emit a lint violation on the id. So this fix is only applicable for\n+ // code bases in which the rule and suppression id's have not yet been fixed.\n argumentExpressionText\n .removePrefix(\"ktlint:\")\n- .let { createRuleIdOrNull(it) }\n+ .let { RuleId.prefixWithStandardRuleSetIdWhenMissing(it) }\n }\n else -> {\n // Disable specific rule if the annotation value is mapped to a specific rule\n@@ -263,39 +265,18 @@ internal object SuppressionLocatorBuilder {\n }\n }\n \n- private fun createRuleIdOrNull(ruleId: String): RuleId? =\n- try {\n- // For backwards compatibility the suppression hints have to be prefixed with the standard rule set id when the rule id is\n- // not prefixed with any rule set id.\n- RuleId\n- .prefixWithStandardRuleSetIdWhenMissing(ruleId)\n- .let { RuleId(it) }\n- } catch (illegalArgumentException: IllegalArgumentException) {\n- // Ktlint should not terminate with an exception in case the code being scanned contains a suppression for a non-existing rule.\n- // Instead, a warning should be printed and the invalid reference is to be ignored. The original ruleId is printed in the\n- // warning message so that user will not go searching for the fully qualified rule id while the code actually contained an\n- // unqualified ruleId.\n- LOGGER.warn {\n- \"\"\"\n- Can not suppress rule with id '$ruleId'. Please check and fix references to this rule in your code.\n- Underlying cause: ${illegalArgumentException.message}\n- \"\"\".trimIndent()\n- }\n- null\n- }\n-\n /**\n * @param range zero-based range of lines where lint errors should be suppressed\n * @param disabledRuleIds empty set means \"all\"\n */\n private data class SuppressionHint(\n val range: IntRange,\n- val disabledRuleIds: Set = emptySet(),\n+ val disabledRuleIds: Set = emptySet(),\n )\n \n private data class CommentSuppressionHint(\n val node: ASTNode,\n- val disabledRuleIds: Set = emptySet(),\n+ val disabledRuleIds: Set = emptySet(),\n val type: Type,\n ) {\n enum class Type {\n@@ -304,7 +285,4 @@ internal object SuppressionLocatorBuilder {\n BLOCK_END,\n }\n }\n-\n- private const val KTLINT_DISABLE = \"ktlint-disable\"\n- private const val KTLINT_ENABLE = \"ktlint-enable\"\n }\ndiff --git a/ktlint-rule-engine/src/main/kotlin/com/pinterest/ktlint/rule/engine/internal/rulefilter/InternalRuleProvidersFilter.kt b/ktlint-rule-engine/src/main/kotlin/com/pinterest/ktlint/rule/engine/internal/rulefilter/InternalRuleProvidersFilter.kt\nnew file mode 100644\nindex 0000000000..c806ec1a65\n--- /dev/null\n+++ b/ktlint-rule-engine/src/main/kotlin/com/pinterest/ktlint/rule/engine/internal/rulefilter/InternalRuleProvidersFilter.kt\n@@ -0,0 +1,38 @@\n+package com.pinterest.ktlint.rule.engine.internal.rulefilter\n+\n+import com.pinterest.ktlint.logger.api.initKtLintKLogger\n+import com.pinterest.ktlint.rule.engine.api.KtLintRuleEngine\n+import com.pinterest.ktlint.rule.engine.core.api.RuleProvider\n+import com.pinterest.ktlint.rule.engine.internal.rules.KtlintSuppressionRule\n+import mu.KotlinLogging\n+\n+private val LOGGER = KotlinLogging.logger {}.initKtLintKLogger()\n+\n+/**\n+ * Add internal [RuleProvider]s. These rule providers always have to run regardless of the rules providers which are provided by the API\n+ * consumer. In case the API consumer tries to provide a rule with the same rule id as an internal rule provider than it will be ignored.\n+ */\n+internal class InternalRuleProvidersFilter(private val ktLintRuleEngine: KtLintRuleEngine) : RuleFilter {\n+ private val internalRuleProviders =\n+ setOf(\n+ RuleProvider {\n+ KtlintSuppressionRule(\n+ ktLintRuleEngine.ruleProviders.map { it.ruleId },\n+ )\n+ },\n+ )\n+\n+ override fun filter(ruleProviders: Set): Set {\n+ val internalRuleIds = internalRuleProviders.map { it.ruleId }\n+ return ruleProviders\n+ .mapNotNullTo(mutableSetOf()) {\n+ if (it.ruleId in internalRuleIds) {\n+ LOGGER.error { \"The provided rule with id '${it.ruleId}' is ignored in favour of Ktlint's rule with same id\" }\n+ null\n+ } else {\n+ it\n+ }\n+ }.plus(internalRuleProviders)\n+ .toSet()\n+ }\n+}\ndiff --git a/ktlint-rule-engine/src/main/kotlin/com/pinterest/ktlint/rule/engine/internal/rulefilter/RuleFilter.kt b/ktlint-rule-engine/src/main/kotlin/com/pinterest/ktlint/rule/engine/internal/rulefilter/RuleFilter.kt\nindex 8d4ba3e137..49f4d04675 100644\n--- a/ktlint-rule-engine/src/main/kotlin/com/pinterest/ktlint/rule/engine/internal/rulefilter/RuleFilter.kt\n+++ b/ktlint-rule-engine/src/main/kotlin/com/pinterest/ktlint/rule/engine/internal/rulefilter/RuleFilter.kt\n@@ -7,7 +7,7 @@ import com.pinterest.ktlint.rule.engine.core.api.RuleProvider\n * Gets the rule provider for the [KtLintRuleEngine] by applying the [ruleFilters] in the given order on the set of [RuleProvider]s provided\n * by the previous (or the initial list of [RuleProvider]s).\n */\n-internal fun KtLintRuleEngine.ruleProviders(vararg ruleFilters: RuleFilter): Set {\n+internal fun KtLintRuleEngine.applyRuleFilters(vararg ruleFilters: RuleFilter): Set {\n var ruleProviders = initialRuleProviders()\n val ruleFilterIterator = ruleFilters.iterator()\n while (ruleFilterIterator.hasNext()) {\ndiff --git a/ktlint-rule-engine/src/main/kotlin/com/pinterest/ktlint/rule/engine/internal/rules/InternalRule.kt b/ktlint-rule-engine/src/main/kotlin/com/pinterest/ktlint/rule/engine/internal/rules/InternalRule.kt\nnew file mode 100644\nindex 0000000000..963e302aec\n--- /dev/null\n+++ b/ktlint-rule-engine/src/main/kotlin/com/pinterest/ktlint/rule/engine/internal/rules/InternalRule.kt\n@@ -0,0 +1,26 @@\n+package com.pinterest.ktlint.rule.engine.internal.rules\n+\n+import com.pinterest.ktlint.rule.engine.core.api.Rule\n+import com.pinterest.ktlint.rule.engine.core.api.RuleId\n+import com.pinterest.ktlint.rule.engine.core.api.editorconfig.EditorConfigProperty\n+\n+internal val INTERNAL_RULE_ABOUT =\n+ Rule.About(\n+ maintainer = \"KtLint\",\n+ repositoryUrl = \"https://github.com/pinterest/ktlint\",\n+ issueTrackerUrl = \"https://github.com/pinterest/ktlint/issues\",\n+ )\n+\n+/**\n+ * Internal rules can only be declared and instantiated in the 'ktlint-rule-engine'.\n+ */\n+public open class InternalRule internal constructor(\n+ id: String,\n+ override val visitorModifiers: Set = emptySet(),\n+ override val usesEditorConfigProperties: Set> = emptySet(),\n+) : Rule(\n+ ruleId = RuleId(\"internal:$id\"),\n+ visitorModifiers = visitorModifiers,\n+ usesEditorConfigProperties = usesEditorConfigProperties,\n+ about = INTERNAL_RULE_ABOUT,\n+)\ndiff --git a/ktlint-rule-engine/src/main/kotlin/com/pinterest/ktlint/rule/engine/internal/rules/KtlintSuppressionRule.kt b/ktlint-rule-engine/src/main/kotlin/com/pinterest/ktlint/rule/engine/internal/rules/KtlintSuppressionRule.kt\nnew file mode 100644\nindex 0000000000..dfa0c295fa\n--- /dev/null\n+++ b/ktlint-rule-engine/src/main/kotlin/com/pinterest/ktlint/rule/engine/internal/rules/KtlintSuppressionRule.kt\n@@ -0,0 +1,685 @@\n+package com.pinterest.ktlint.rule.engine.internal.rules\n+\n+import com.pinterest.ktlint.rule.engine.core.api.ElementType\n+import com.pinterest.ktlint.rule.engine.core.api.ElementType.ANNOTATION\n+import com.pinterest.ktlint.rule.engine.core.api.ElementType.ANNOTATION_ENTRY\n+import com.pinterest.ktlint.rule.engine.core.api.ElementType.BLOCK_COMMENT\n+import com.pinterest.ktlint.rule.engine.core.api.ElementType.CLASS\n+import com.pinterest.ktlint.rule.engine.core.api.ElementType.EOL_COMMENT\n+import com.pinterest.ktlint.rule.engine.core.api.ElementType.FILE\n+import com.pinterest.ktlint.rule.engine.core.api.ElementType.FILE_ANNOTATION_LIST\n+import com.pinterest.ktlint.rule.engine.core.api.ElementType.FUN\n+import com.pinterest.ktlint.rule.engine.core.api.ElementType.MODIFIER_LIST\n+import com.pinterest.ktlint.rule.engine.core.api.ElementType.PACKAGE_DIRECTIVE\n+import com.pinterest.ktlint.rule.engine.core.api.ElementType.PROPERTY\n+import com.pinterest.ktlint.rule.engine.core.api.ElementType.PROPERTY_ACCESSOR\n+import com.pinterest.ktlint.rule.engine.core.api.ElementType.STRING_TEMPLATE\n+import com.pinterest.ktlint.rule.engine.core.api.ElementType.VALUE_ARGUMENT\n+import com.pinterest.ktlint.rule.engine.core.api.ElementType.VALUE_ARGUMENT_LIST\n+import com.pinterest.ktlint.rule.engine.core.api.RuleId\n+import com.pinterest.ktlint.rule.engine.core.api.indent\n+import com.pinterest.ktlint.rule.engine.core.api.isRoot\n+import com.pinterest.ktlint.rule.engine.core.api.isWhiteSpace\n+import com.pinterest.ktlint.rule.engine.core.api.isWhiteSpaceWithNewline\n+import com.pinterest.ktlint.rule.engine.core.api.nextLeaf\n+import com.pinterest.ktlint.rule.engine.core.api.nextSibling\n+import com.pinterest.ktlint.rule.engine.core.api.parent\n+import com.pinterest.ktlint.rule.engine.core.api.prevLeaf\n+import com.pinterest.ktlint.rule.engine.internal.rules.KtLintDirective.KtlintDirectiveType.KTLINT_DISABLE\n+import com.pinterest.ktlint.rule.engine.internal.rules.KtLintDirective.KtlintDirectiveType.KTLINT_ENABLE\n+import com.pinterest.ktlint.rule.engine.internal.rules.KtLintDirective.SuppressionIdChange.InvalidSuppressionId\n+import com.pinterest.ktlint.rule.engine.internal.rules.KtLintDirective.SuppressionIdChange.ValidSuppressionId\n+import com.pinterest.ktlint.rule.engine.internal.rules.KtlintSuppressionRule.SuppressAnnotationType.SUPPRESS\n+import com.pinterest.ktlint.rule.engine.internal.rules.KtlintSuppressionRule.SuppressAnnotationType.SUPPRESS_WARNINGS\n+import org.jetbrains.kotlin.com.intellij.lang.ASTNode\n+import org.jetbrains.kotlin.com.intellij.psi.PsiElement\n+import org.jetbrains.kotlin.com.intellij.psi.PsiFileFactory\n+import org.jetbrains.kotlin.com.intellij.psi.impl.source.tree.PsiWhiteSpaceImpl\n+import org.jetbrains.kotlin.idea.KotlinLanguage\n+import org.jetbrains.kotlin.psi.KtAnnotationEntry\n+import org.jetbrains.kotlin.psi.KtBlockExpression\n+import org.jetbrains.kotlin.psi.KtCallExpression\n+import org.jetbrains.kotlin.psi.KtClassInitializer\n+import org.jetbrains.kotlin.psi.KtCollectionLiteralExpression\n+import org.jetbrains.kotlin.psi.KtDeclaration\n+import org.jetbrains.kotlin.psi.KtDeclarationModifierList\n+import org.jetbrains.kotlin.psi.KtExpression\n+import org.jetbrains.kotlin.psi.KtFile\n+import org.jetbrains.kotlin.psi.KtFileAnnotationList\n+import org.jetbrains.kotlin.psi.KtFunctionLiteral\n+import org.jetbrains.kotlin.psi.KtLambdaExpression\n+import org.jetbrains.kotlin.psi.KtLiteralStringTemplateEntry\n+import org.jetbrains.kotlin.psi.KtNamedFunction\n+import org.jetbrains.kotlin.psi.KtPrimaryConstructor\n+import org.jetbrains.kotlin.psi.KtScript\n+import org.jetbrains.kotlin.psi.KtScriptInitializer\n+import org.jetbrains.kotlin.psi.KtStringTemplateExpression\n+import org.jetbrains.kotlin.psi.KtValueArgument\n+import org.jetbrains.kotlin.psi.KtValueArgumentList\n+import org.jetbrains.kotlin.psi.psiUtil.children\n+import org.jetbrains.kotlin.psi.psiUtil.findDescendantOfType\n+import org.jetbrains.kotlin.psi.psiUtil.getChildOfType\n+import org.jetbrains.kotlin.psi.psiUtil.siblings\n+import org.jetbrains.kotlin.util.prefixIfNot\n+import org.jetbrains.kotlin.utils.addToStdlib.applyIf\n+\n+private const val KTLINT_SUPPRESSION_ID_PREFIX = \"ktlint:\"\n+private const val KTLINT_SUPPRESSION_ID_ALL_RULES = \"\\\"ktlint\\\"\"\n+private const val DOUBLE_QUOTE = \"\\\"\"\n+\n+/**\n+ * Disallow usage of the old \"ktlint-disable\" and \"ktlint-enable\" directives.\n+ *\n+ * A ktlint-disable directive is replaced with an annotation on the closest parent declaration or expression, or as annotation on the file\n+ * level in case the directive is associated with a top level element. Ktlint-disable directives placed in block comments are only\n+ * autocorrected when placed as top level element or in case a matching Ktlint-enable directive is found in the same parent as the disable\n+ * directive.\n+ *\n+ * If the target element is annotated with a [Suppress] (or, if missing, is annotated with a [SuppressWarnings] annotation) then the\n+ * ktlint-directive will be matched against this annotation. If this annotation already contains a suppression for *all* ktlint rules, or\n+ * for the specific rule id, then it is not added to annotation as it would be redundant. In case a suppression identifier is added to an\n+ * existing annotation then all identifiers in the annotation are alphabetically sorted.\n+ *\n+ * If the target element is not annotated with [Suppress] or [SuppressWarnings] then a [Suppress] annotation is added.\n+ *\n+ * Ktlint-enable directives are removed as annotations have a scope in which the suppression will be active.\n+ */\n+public class KtlintSuppressionRule(private val allowedRuleIds: List) : InternalRule(\"ktlint-suppression\") {\n+ private val allowedRuleIdAsStrings = allowedRuleIds.map { it.value }\n+\n+ private val ruleIdValidator: (String) -> Boolean = { ruleId -> allowedRuleIdAsStrings.contains(ruleId) }\n+\n+ override fun beforeVisitChildNodes(\n+ node: ASTNode,\n+ autoCorrect: Boolean,\n+ emit: (offset: Int, errorMessage: String, canBeAutoCorrected: Boolean) -> Unit,\n+ ) {\n+ node\n+ .takeIf { isKtlintRuleSuppressionInAnnotation(it) }\n+ ?.let { visitKtlintSuppressionInAnnotation(node, autoCorrect, emit) }\n+\n+ node\n+ .ktlintDirectiveOrNull(ruleIdValidator)\n+ ?.visitKtlintDirective(autoCorrect, emit)\n+ }\n+\n+ private fun isKtlintRuleSuppressionInAnnotation(node: ASTNode) =\n+ node\n+ .takeIf { it.elementType == STRING_TEMPLATE }\n+ ?.takeIf { it.text.isKtlintSuppressionId() }\n+ ?.let { literalStringTemplate ->\n+ literalStringTemplate\n+ .parent(VALUE_ARGUMENT)\n+ ?.isPartOfAnnotation()\n+ }\n+ ?: false\n+\n+ private fun String.isKtlintSuppressionId() = removePrefix(DOUBLE_QUOTE).startsWith(KTLINT_SUPPRESSION_ID_PREFIX)\n+\n+ private fun ASTNode.isPartOfAnnotation() = parent { it.elementType == ANNOTATION || it.elementType == ANNOTATION_ENTRY } != null\n+\n+ private fun visitKtlintSuppressionInAnnotation(\n+ node: ASTNode,\n+ autoCorrect: Boolean,\n+ emit: (offset: Int, errorMessage: String, canBeAutoCorrected: Boolean) -> Unit,\n+ ) {\n+ node\n+ .psi\n+ .findDescendantOfType()\n+ ?.node\n+ ?.let { literalStringTemplateEntry ->\n+ val prefixedSuppression =\n+ literalStringTemplateEntry\n+ .text\n+ .prefixKtlintSuppressionWithRuleSetIdOrNull()\n+ val offset = literalStringTemplateEntry.startOffset + KTLINT_SUPPRESSION_ID_PREFIX.length\n+ if (prefixedSuppression.isUnknownKtlintSuppression()) {\n+ emit(offset, \"Ktlint rule with id '$prefixedSuppression' is unknown or not loaded\", false)\n+ } else if (prefixedSuppression != literalStringTemplateEntry.text) {\n+ emit(offset, \"Identifier to suppress ktlint rule must be fully qualified with the rule set id\", true)\n+ if (autoCorrect) {\n+ node\n+ .createLiteralStringTemplateEntry(prefixedSuppression)\n+ ?.let { literalStringTemplateEntry.replaceWith(it) }\n+ }\n+ }\n+ }\n+ }\n+\n+ private fun ASTNode.createLiteralStringTemplateEntry(prefixedSuppression: String) =\n+ PsiFileFactory\n+ .getInstance(psi.project)\n+ .createFileFromText(KotlinLanguage.INSTANCE, \"listOf(\\\"$prefixedSuppression\\\")\")\n+ .getChildOfType()\n+ ?.getChildOfType()\n+ ?.getChildOfType()\n+ ?.getChildOfType()\n+ ?.getChildOfType()\n+ ?.getChildOfType()\n+ ?.getChildOfType()\n+ ?.getChildOfType()\n+ ?.node\n+\n+ private fun String.prefixKtlintSuppressionWithRuleSetIdOrNull(): String {\n+ val isPrefixedWithDoubleQuote = startsWith(DOUBLE_QUOTE)\n+ return removePrefix(DOUBLE_QUOTE)\n+ .takeIf { startsWith(KTLINT_SUPPRESSION_ID_PREFIX) }\n+ ?.substringAfter(KTLINT_SUPPRESSION_ID_PREFIX)\n+ ?.let { prefixWithRuleSetIdWhenMissing(it) }\n+ ?.prefixIfNot(KTLINT_SUPPRESSION_ID_PREFIX)\n+ ?.applyIf(isPrefixedWithDoubleQuote) { prefixIfNot(DOUBLE_QUOTE) }\n+ ?: this\n+ }\n+\n+ private fun String.isUnknownKtlintSuppression(): Boolean =\n+ removePrefix(DOUBLE_QUOTE)\n+ .takeIf { startsWith(KTLINT_SUPPRESSION_ID_PREFIX) }\n+ ?.substringAfter(KTLINT_SUPPRESSION_ID_PREFIX)\n+ ?.let { prefixWithRuleSetIdWhenMissing(it) }\n+ ?.let { ruleId ->\n+ allowedRuleIds.none { it.value == ruleId }\n+ }\n+ ?: false\n+\n+ private fun KtLintDirective.visitKtlintDirective(\n+ autoCorrect: Boolean,\n+ emit: (offset: Int, errorMessage: String, canBeAutoCorrected: Boolean) -> Unit,\n+ ) {\n+ when (ktlintDirectiveType) {\n+ KTLINT_DISABLE -> {\n+ if (node.elementType == EOL_COMMENT && node.prevLeaf().isWhiteSpaceWithNewline()) {\n+ removeDanglingEolCommentWithKtlintDisableDirective(autoCorrect, emit)\n+ } else {\n+ visitKtlintDisableDirective(autoCorrect, emit)\n+ }\n+ }\n+\n+ KTLINT_ENABLE -> {\n+ removeKtlintEnableDirective(autoCorrect, emit)\n+ }\n+ }\n+ }\n+\n+ private fun KtLintDirective.removeDanglingEolCommentWithKtlintDisableDirective(\n+ autoCorrect: Boolean,\n+ emit: (offset: Int, errorMessage: String, canBeAutoCorrected: Boolean) -> Unit,\n+ ) {\n+ emit(offset, \"Directive 'ktlint-disable' in EOL comment is ignored as it is not preceded by a code element\", true)\n+ if (autoCorrect) {\n+ node.removePrecedingWhitespace()\n+ node.remove()\n+ }\n+ }\n+\n+ private fun KtLintDirective.visitKtlintDisableDirective(\n+ autoCorrect: Boolean,\n+ emit: (offset: Int, errorMessage: String, canBeAutoCorrected: Boolean) -> Unit,\n+ ) {\n+ if (node.elementType == BLOCK_COMMENT && hasNoMatchingKtlintEnableDirective(ruleIdValidator)) {\n+ emit(\n+ offset,\n+ \"Directive 'ktlint-disable' is deprecated. The matching 'ktlint-enable' directive is not found in same scope. Replace \" +\n+ \"with @Suppress annotation\",\n+ false,\n+ )\n+ return\n+ }\n+ emit(offset, \"Directive 'ktlint-disable' is deprecated. Replace with @Suppress annotation\", true)\n+ suppressionIdChanges\n+ .filterIsInstance()\n+ .forEach { ktlintDirectiveChange ->\n+ emit(\n+ offset +\n+ ktlintDirectiveType.id.length +\n+ ktlintDirectiveChange.offsetOriginalRuleId,\n+ \"Ktlint rule with id '${ktlintDirectiveChange.originalRuleId}' is unknown or not loaded\",\n+ false,\n+ )\n+ }\n+ if (autoCorrect) {\n+ findParentDeclarationOrExpression()\n+ .addKtlintRuleSuppression(suppressionIdChanges)\n+ if (node.elementType == EOL_COMMENT) {\n+ node.removePrecedingWhitespace()\n+ } else {\n+ if (node.nextLeaf().isWhiteSpaceWithNewline()) {\n+ node\n+ .nextLeaf()\n+ ?.remove()\n+ } else {\n+ node.removePrecedingWhitespace()\n+ }\n+ }\n+ node.remove()\n+ }\n+ }\n+\n+ private fun KtLintDirective.findParentDeclarationOrExpression(): ASTNode {\n+ val shouldBeConvertedToFileAnnotation = shouldBeConvertedToFileAnnotation()\n+ var targetNode =\n+ if (node.elementType == BLOCK_COMMENT &&\n+ shouldBePromotedToParentDeclaration(ruleIdValidator)\n+ ) {\n+ node.treeParent.treeParent.psi\n+ } else {\n+ node.psi\n+ }\n+ while (\n+ shouldBeConvertedToFileAnnotation ||\n+ targetNode is KtClassInitializer ||\n+ targetNode is KtBlockExpression ||\n+ targetNode is KtPrimaryConstructor ||\n+ targetNode is KtFunctionLiteral ||\n+ targetNode is KtLambdaExpression ||\n+ (targetNode is KtExpression && targetNode.parent is KtExpression && targetNode.parent !is KtDeclaration) ||\n+ (targetNode !is KtDeclaration && targetNode !is KtExpression)\n+ ) {\n+ if (targetNode.parent == null) {\n+ return targetNode.node\n+ }\n+ targetNode = targetNode.parent\n+ }\n+ return targetNode.node\n+ }\n+\n+ private fun ASTNode.remove() {\n+ treeParent.removeChild(this)\n+ }\n+\n+ private fun ASTNode.removePrecedingWhitespace() {\n+ prevLeaf()\n+ .takeIf { it.isWhiteSpace() }\n+ ?.remove()\n+ }\n+\n+ private fun ASTNode.addKtlintRuleSuppression(suppressionIdChanges: Set) {\n+ val ktlintRuleSuppressions =\n+ suppressionIdChanges\n+ .filterIsInstance()\n+ .map { it.suppressionId }\n+ .toSet()\n+ if (ktlintRuleSuppressions.isEmpty()) {\n+ // Do not add or alter the @Suppress / @SuppressWarnings\n+ return\n+ }\n+ val suppressionAnnotations = findSuppressionAnnotations()\n+ // Add ktlint rule suppressions:\n+ // - To the @Suppress annotation if found\n+ // - otherwise to the @SuppressWarnings annotation if found\n+ // - otherwise create a new @Suppress annotation\n+ when {\n+ suppressionAnnotations.containsKey(SUPPRESS) ->\n+ ktlintRuleSuppressions.mergeInto(suppressionAnnotations.getValue(SUPPRESS), SUPPRESS)\n+\n+ suppressionAnnotations.containsKey(SUPPRESS_WARNINGS) ->\n+ ktlintRuleSuppressions.mergeInto(suppressionAnnotations.getValue(SUPPRESS_WARNINGS), SUPPRESS_WARNINGS)\n+\n+ else -> createSuppressAnnotation(SUPPRESS, ktlintRuleSuppressions)\n+ }\n+ }\n+\n+ private fun Set.mergeInto(\n+ annotationNode: ASTNode,\n+ suppressType: SuppressAnnotationType,\n+ ) {\n+ annotationNode\n+ .existingSuppressions()\n+ .plus(this)\n+ .let { suppressions ->\n+ if (suppressions.contains(KTLINT_SUPPRESSION_ID_ALL_RULES)) {\n+ // When all ktlint rules are to be suppressed, then ignore all suppressions for specific ktlint rules\n+ suppressions\n+ .filterNot { it.isKtlintSuppressionId() }\n+ .toSet()\n+ } else {\n+ suppressions\n+ }\n+ }.map { it.prefixKtlintSuppressionWithRuleSetIdOrNull() }\n+ .toSet()\n+ .let { suppressions -> annotationNode.createSuppressAnnotation(suppressType, suppressions) }\n+ }\n+\n+ private fun ASTNode.existingSuppressions() =\n+ existingSuppressionsFromNamedArgumentOrNull()\n+ ?: getValueArguments()\n+\n+ private fun ASTNode.existingSuppressionsFromNamedArgumentOrNull() =\n+ psi\n+ .findDescendantOfType()\n+ ?.children\n+ ?.map { it.text }\n+ ?.toSet()\n+\n+ private fun ASTNode.findSuppressionAnnotations(): Map =\n+ if (this.isRoot()) {\n+ findChildByType(FILE_ANNOTATION_LIST)\n+ ?.findSuppressionAnnotationsInModifierList()\n+ .orEmpty()\n+ } else {\n+ findChildByType(MODIFIER_LIST)\n+ ?.findSuppressionAnnotationsInModifierList()\n+ .orEmpty()\n+ }\n+\n+ private fun ASTNode.findSuppressionAnnotationsInModifierList(): Map =\n+ children()\n+ .mapNotNull { modifier ->\n+ when (modifier.suppressionAnnotationTypeOrNull()) {\n+ SUPPRESS -> Pair(SUPPRESS, modifier)\n+ SUPPRESS_WARNINGS -> Pair(SUPPRESS_WARNINGS, modifier)\n+ else -> null\n+ }\n+ }.toMap()\n+\n+ private fun ASTNode.suppressionAnnotationTypeOrNull() =\n+ takeIf { elementType == ANNOTATION || elementType == ANNOTATION_ENTRY }\n+ ?.findChildByType(ElementType.CONSTRUCTOR_CALLEE)\n+ ?.findChildByType(ElementType.TYPE_REFERENCE)\n+ ?.findChildByType(ElementType.USER_TYPE)\n+ ?.findChildByType(ElementType.REFERENCE_EXPRESSION)\n+ ?.findChildByType(ElementType.IDENTIFIER)\n+ ?.text\n+ ?.let { SuppressAnnotationType.findByIdOrNull(it) }\n+\n+ private fun ASTNode.getValueArguments() =\n+ findChildByType(VALUE_ARGUMENT_LIST)\n+ ?.children()\n+ ?.filter { it.elementType == VALUE_ARGUMENT }\n+ ?.map { it.text }\n+ ?.toSet()\n+ .orEmpty()\n+\n+ private fun ASTNode.createSuppressAnnotation(\n+ suppressType: SuppressAnnotationType,\n+ suppressions: Set,\n+ ) {\n+ val targetNode =\n+ if (elementType == ANNOTATION_ENTRY) {\n+ treeParent\n+ } else {\n+ this\n+ }\n+\n+ if (targetNode.psi is KtFile || targetNode.psi is KtFileAnnotationList) {\n+ val fileAnnotation =\n+ targetNode\n+ .psi\n+ .createFileAnnotation(\n+ suppressType,\n+ suppressions\n+ .sorted()\n+ .joinToString(),\n+ ).node\n+ if (targetNode.elementType == FILE_ANNOTATION_LIST) {\n+ this.replaceWith(fileAnnotation.firstChildNode)\n+ } else {\n+ this.createFileAnnotationList(fileAnnotation)\n+ }\n+ } else {\n+ val modifierListWithAnnotation =\n+ targetNode\n+ .psi\n+ .createModifierListWithAnnotationEntry(\n+ suppressType,\n+ suppressions\n+ .sorted()\n+ .joinToString(),\n+ )\n+ when (elementType) {\n+ ANNOTATION_ENTRY ->\n+ this.replaceWith(\n+ modifierListWithAnnotation\n+ .getChildOfType()!!\n+ .node,\n+ )\n+ CLASS, FUN, PROPERTY, PROPERTY_ACCESSOR -> {\n+ this.addChild(PsiWhiteSpaceImpl(indent()), this.firstChildNode)\n+ this.addChild(modifierListWithAnnotation.node, this.firstChildNode)\n+ }\n+ else -> {\n+ treeParent.addChild(\n+ modifierListWithAnnotation\n+ .getChildOfType()!!\n+ .node,\n+ this,\n+ )\n+ treeParent.addChild(PsiWhiteSpaceImpl(indent()), this)\n+ }\n+ }\n+ }\n+ }\n+\n+ private fun PsiElement.createFileAnnotation(\n+ suppressType: SuppressAnnotationType,\n+ sortedSuppressionsString: String,\n+ ): PsiElement =\n+ \"@file:${suppressType.annotationName}($sortedSuppressionsString)\"\n+ .let { annotation ->\n+ PsiFileFactory\n+ .getInstance(project)\n+ .createFileFromText(KotlinLanguage.INSTANCE, annotation)\n+ ?.firstChild\n+ ?: throw IllegalStateException(\"Can not create annotation '$annotation'\")\n+ }\n+\n+ private fun ASTNode.createFileAnnotationList(annotation: ASTNode) {\n+ require(isRoot()) { \"File annotation list can only be created for root node\" }\n+ // Should always be inserted into the first (root) code child regardless in which root node the ktlint directive\n+ // was actually found\n+ findChildByType(PACKAGE_DIRECTIVE)\n+ ?.let { packageDirective ->\n+ packageDirective\n+ .treeParent\n+ .addChild(annotation, packageDirective)\n+ packageDirective\n+ .treeParent\n+ .addChild(PsiWhiteSpaceImpl(\"\\n\" + indent()), packageDirective)\n+ }\n+ }\n+\n+ private fun PsiElement.createModifierListWithAnnotationEntry(\n+ suppressType: SuppressAnnotationType,\n+ sortedSuppressionsString: String,\n+ ): PsiElement =\n+ \"@${suppressType.annotationName}($sortedSuppressionsString)\"\n+ .let { annotation ->\n+ PsiFileFactory\n+ .getInstance(project)\n+ .createFileFromText(\n+ KotlinLanguage.INSTANCE,\n+ // Create the annotation for a dummy declaration as the entire code block should be valid Kotlin code\n+ \"\"\"\n+ $annotation\n+ fun foo() {}\n+ \"\"\".trimIndent(),\n+ ).getChildOfType()\n+ ?.getChildOfType()\n+ ?.getChildOfType()\n+ ?.getChildOfType()\n+ ?: throw IllegalStateException(\"Can not create annotation '$annotation'\")\n+ }\n+\n+ private fun KtLintDirective.removeKtlintEnableDirective(\n+ autoCorrect: Boolean,\n+ emit: (offset: Int, errorMessage: String, canBeAutoCorrected: Boolean) -> Unit,\n+ ) {\n+ emit(offset, \"Directive 'ktlint-enable' is obsolete after migrating to suppress annotations\", true)\n+ if (autoCorrect) {\n+ node.removePrecedingWhitespace()\n+ node.remove()\n+ }\n+ }\n+\n+ private fun ASTNode.replaceWith(node: ASTNode) {\n+ treeParent.addChild(node, this)\n+ this.remove()\n+ }\n+\n+ private enum class SuppressAnnotationType(val annotationName: String) {\n+ SUPPRESS(\"Suppress\"),\n+ SUPPRESS_WARNINGS(\"SuppressWarnings\"),\n+ ;\n+\n+ companion object {\n+ fun findByIdOrNull(id: String): SuppressAnnotationType? =\n+ SuppressAnnotationType\n+ .values()\n+ .firstOrNull { it.annotationName == id }\n+ }\n+ }\n+}\n+\n+private data class KtLintDirective(\n+ val node: ASTNode,\n+ val ktlintDirectiveType: KtlintDirectiveType,\n+ val ktlintDirectives: String,\n+ val suppressionIdChanges: Set,\n+) {\n+ val offset = node.startOffset + node.text.indexOf(ktlintDirectiveType.id)\n+\n+ fun hasNoMatchingKtlintEnableDirective(ruleIdValidator: (String) -> Boolean): Boolean {\n+ require(ktlintDirectiveType == KTLINT_DISABLE && node.elementType == BLOCK_COMMENT)\n+\n+ return if (shouldBeConvertedToFileAnnotation()) {\n+ false\n+ } else {\n+ findMatchingKtlintEnableDirective(ruleIdValidator) == null\n+ }\n+ }\n+\n+ private fun findMatchingKtlintEnableDirective(ruleIdValidator: (String) -> Boolean) =\n+ node\n+ .applyIf(node.isSuppressibleDeclaration()) { node.treeParent }\n+ .siblings()\n+ .firstOrNull {\n+ it\n+ .ktlintDirectiveOrNull(ruleIdValidator)\n+ ?.takeIf { it.ktlintDirectiveType == KTLINT_ENABLE }\n+ ?.ktlintDirectives == ktlintDirectives\n+ }\n+\n+ fun shouldBeConvertedToFileAnnotation() =\n+ node.isTopLevel() ||\n+ (node.elementType == BLOCK_COMMENT && node.isSuppressibleDeclaration() && node.treeParent.isTopLevel())\n+\n+ private fun ASTNode.isSuppressibleDeclaration() =\n+ when (treeParent.elementType) {\n+ CLASS, FUN, PROPERTY -> true\n+ else -> false\n+ }\n+\n+ private fun ASTNode.isTopLevel() =\n+ FILE ==\n+ this\n+ .treeParent\n+ .elementType\n+\n+ fun shouldBePromotedToParentDeclaration(ruleIdValidator: (String) -> Boolean): Boolean {\n+ require(ktlintDirectiveType == KTLINT_DISABLE && node.elementType == BLOCK_COMMENT)\n+\n+ return if (shouldBeConvertedToFileAnnotation()) {\n+ false\n+ } else {\n+ node\n+ .takeIf { it.isSuppressibleDeclaration() }\n+ ?.let { findMatchingKtlintEnableDirective(ruleIdValidator) }\n+ ?.let { matchingKtlintEnabledDirective ->\n+ // In case the node is part of a suppressible declaration and the next sibling matches the enable directive then the\n+ // block directive should be match with this declaration only and not be moved to the parent.\n+ matchingKtlintEnabledDirective !=\n+ node\n+ .treeParent\n+ .nextSibling { !it.isWhiteSpace() }\n+ }\n+ ?: false\n+ }\n+ }\n+\n+ enum class KtlintDirectiveType(val id: String) {\n+ KTLINT_DISABLE(\"ktlint-disable\"),\n+ KTLINT_ENABLE(\"ktlint-enable\"),\n+ }\n+\n+ sealed class SuppressionIdChange {\n+ class ValidSuppressionId(val suppressionId: String) : SuppressionIdChange()\n+\n+ class InvalidSuppressionId(\n+ val originalRuleId: String,\n+ val offsetOriginalRuleId: Int,\n+ ) : SuppressionIdChange()\n+ }\n+}\n+\n+private fun ASTNode.ktlintDirectiveOrNull(ruleIdValidator: (String) -> Boolean): KtLintDirective? {\n+ val ktlintDirectiveString =\n+ when (elementType) {\n+ EOL_COMMENT ->\n+ text\n+ .removePrefix(\"//\")\n+ .trim()\n+\n+ BLOCK_COMMENT ->\n+ text\n+ .removePrefix(\"/*\")\n+ .removeSuffix(\"*/\")\n+ .trim()\n+\n+ else ->\n+ return null\n+ }\n+ val ktlintDirectiveType =\n+ ktlintDirectiveString.toKtlintDirectiveTypeOrNull()\n+ ?: return null\n+ val ruleIds = ktlintDirectiveString.removePrefix(ktlintDirectiveType.id)\n+ val suppressionIdChanges = ruleIds.toSuppressionIdChanges(ruleIdValidator)\n+\n+ return KtLintDirective(this, ktlintDirectiveType, ruleIds, suppressionIdChanges)\n+}\n+\n+private fun String.toKtlintDirectiveTypeOrNull() =\n+ when {\n+ startsWith(KTLINT_DISABLE.id) -> KTLINT_DISABLE\n+ startsWith(KTLINT_ENABLE.id) -> KTLINT_ENABLE\n+ else -> null\n+ }\n+\n+// Transform the string: \"ktlint-disable foo standard:bar\"\n+// to a (sorted) list containing elements:\n+// ktlint:standard:bar\n+// ktlint:standard:foo\n+private fun String.toSuppressionIdChanges(ruleIdValidator: (String) -> Boolean) =\n+ trim()\n+ .split(\" \")\n+ .map { it.trim() }\n+ .filter { it.isNotBlank() }\n+ .map { originalRuleId ->\n+ val prefixedRuleId = prefixWithRuleSetIdWhenMissing(originalRuleId)\n+ if (ruleIdValidator(prefixedRuleId)) {\n+ ValidSuppressionId(\n+ prefixedRuleId\n+ .prefixIfNot(KTLINT_SUPPRESSION_ID_PREFIX)\n+ .surroundWith(DOUBLE_QUOTE),\n+ )\n+ } else {\n+ InvalidSuppressionId(\n+ originalRuleId,\n+ this.indexOf(originalRuleId),\n+ )\n+ }\n+ }.toSet()\n+ .ifEmpty { setOf(ValidSuppressionId(\"\\\"ktlint\\\"\")) }\n+\n+private fun prefixWithRuleSetIdWhenMissing(ruleIdString: String) =\n+ RuleId\n+ .prefixWithStandardRuleSetIdWhenMissing(\n+ // The experimental ruleset was removed in Ktlint 0.49. References to that ruleset however may still exist. Also, not all\n+ // user seem to understand that it is no longer a separate ruleset.\n+ ruleIdString.removePrefix(\"experimental:\"),\n+ )\n+\n+private fun String.surroundWith(string: String) =\n+ removeSurrounding(string)\n+ .prefixIfNot(string)\n+ .plus(string)\n+\n+public val KTLINT_SUPPRESSION_RULE_ID: RuleId = KtlintSuppressionRule(emptyList()).ruleId\ndiff --git a/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/MaxLineLengthRule.kt b/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/MaxLineLengthRule.kt\nindex 25fd1092e9..6474c7226a 100644\n--- a/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/MaxLineLengthRule.kt\n+++ b/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/MaxLineLengthRule.kt\n@@ -79,23 +79,18 @@ public class MaxLineLengthRule :\n // fixme:\n // normally we would emit here but due to API limitations we need to hold off until\n // node spanning the same offset is 'visit'ed\n- // (for ktlint-disable directive to have effect (when applied))\n // this will be rectified in the upcoming release(s)\n errorOffset.add(parsedLine.offset)\n }\n } else {\n- // Allow ktlint-disable comments to exceed max line length\n- if (!el.text.startsWith(\"// ktlint-disable\")) {\n- // if comment is the only thing on the line - fine, otherwise emit an error\n- val prevLeaf = el.prevCodeSibling()\n- if (prevLeaf != null && prevLeaf.startOffset >= parsedLine.offset) {\n- // fixme:\n- // normally we would emit here but due to API limitations we need to hold off until\n- // node spanning the same offset is 'visit'ed\n- // (for ktlint-disable directive to have effect (when applied))\n- // this will be rectified in the upcoming release(s)\n- errorOffset.add(parsedLine.offset)\n- }\n+ // if comment is the only thing on the line - fine, otherwise emit an error\n+ val prevLeaf = el.prevCodeSibling()\n+ if (prevLeaf != null && prevLeaf.startOffset >= parsedLine.offset) {\n+ // fixme:\n+ // normally we would emit here but due to API limitations we need to hold off until\n+ // node spanning the same offset is 'visit'ed\n+ // this will be rectified in the upcoming release(s)\n+ errorOffset.add(parsedLine.offset)\n }\n }\n }\ndiff --git a/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/NoSingleLineBlockCommentRule.kt b/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/NoSingleLineBlockCommentRule.kt\nindex 08b99363bc..e51babdebf 100644\n--- a/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/NoSingleLineBlockCommentRule.kt\n+++ b/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/NoSingleLineBlockCommentRule.kt\n@@ -47,7 +47,6 @@ public class NoSingleLineBlockCommentRule :\n ?: node.lastChildLeafOrSelf()\n \n if (!node.textContains('\\n') &&\n- !node.isKtlintSuppressionDirective() &&\n afterBlockComment.nextLeaf().isWhitespaceWithNewlineOrNull()\n ) {\n emit(node.startOffset, \"Replace the block comment with an EOL comment\", true)\n@@ -66,16 +65,6 @@ public class NoSingleLineBlockCommentRule :\n }\n \n private fun ASTNode?.isWhitespaceWithNewlineOrNull() = this == null || this.isWhiteSpaceWithNewline()\n-\n- // TODO: Remove when ktlint suppression directive in comments are no longer supported\n- private fun ASTNode?.isKtlintSuppressionDirective() =\n- this\n- ?.text\n- ?.removePrefix(\"/*\")\n- ?.removeSuffix(\"*/\")\n- ?.trim()\n- ?.let { it.startsWith(\"ktlint-enable\") || it.startsWith(\"ktlint-disable\") }\n- ?: false\n }\n \n public val NO_SINGLE_LINE_BLOCK_COMMENT_RULE_ID: RuleId = NoSingleLineBlockCommentRule().ruleId\n", "test_patch": "diff --git a/ktlint-cli-reporter-checkstyle/src/test/kotlin/com/pinterest/ktlint/cli/reporter/checkstyle/CheckStyleReporterTest.kt b/ktlint-cli-reporter-checkstyle/src/test/kotlin/com/pinterest/ktlint/cli/reporter/checkstyle/CheckStyleReporterTest.kt\nindex b890fc2986..bbc817cf86 100644\n--- a/ktlint-cli-reporter-checkstyle/src/test/kotlin/com/pinterest/ktlint/cli/reporter/checkstyle/CheckStyleReporterTest.kt\n+++ b/ktlint-cli-reporter-checkstyle/src/test/kotlin/com/pinterest/ktlint/cli/reporter/checkstyle/CheckStyleReporterTest.kt\n@@ -15,29 +15,29 @@ class CheckStyleReporterTest {\n val reporter = CheckStyleReporter(PrintStream(out, true))\n reporter.onLintError(\n \"/one-fixed-and-one-not.kt\",\n- @Suppress(\"ktlint:argument-list-wrapping\")\n+ @Suppress(\"ktlint:standard:argument-list-wrapping\")\n KtlintCliError(1, 1, \"rule-1\", \"<\\\"&'>\", LINT_CAN_BE_AUTOCORRECTED),\n )\n reporter.onLintError(\n \"/one-fixed-and-one-not.kt\",\n- @Suppress(\"ktlint:argument-list-wrapping\")\n+ @Suppress(\"ktlint:standard:argument-list-wrapping\")\n KtlintCliError(2, 1, \"rule-2\", \"And if you see my friend\", FORMAT_IS_AUTOCORRECTED),\n )\n \n reporter.onLintError(\n \"/two-not-fixed.kt\",\n- @Suppress(\"ktlint:argument-list-wrapping\")\n+ @Suppress(\"ktlint:standard:argument-list-wrapping\")\n KtlintCliError(1, 10, \"rule-1\", \"I thought I would again\", LINT_CAN_BE_AUTOCORRECTED),\n )\n reporter.onLintError(\n \"/two-not-fixed.kt\",\n- @Suppress(\"ktlint:argument-list-wrapping\")\n+ @Suppress(\"ktlint:standard:argument-list-wrapping\")\n KtlintCliError(2, 20, \"rule-2\", \"A single thin straight line\", LINT_CAN_BE_AUTOCORRECTED),\n )\n \n reporter.onLintError(\n \"/all-corrected.kt\",\n- @Suppress(\"ktlint:argument-list-wrapping\")\n+ @Suppress(\"ktlint:standard:argument-list-wrapping\")\n KtlintCliError(1, 1, \"rule-1\", \"I thought we had more time\", FORMAT_IS_AUTOCORRECTED),\n )\n reporter.afterAll()\ndiff --git a/ktlint-cli-reporter-format/src/test/kotlin/com/pinterest/ktlint/cli/reporter/format/FormatReporterTest.kt b/ktlint-cli-reporter-format/src/test/kotlin/com/pinterest/ktlint/cli/reporter/format/FormatReporterTest.kt\nindex 35e146f44a..cb36fc32c8 100644\n--- a/ktlint-cli-reporter-format/src/test/kotlin/com/pinterest/ktlint/cli/reporter/format/FormatReporterTest.kt\n+++ b/ktlint-cli-reporter-format/src/test/kotlin/com/pinterest/ktlint/cli/reporter/format/FormatReporterTest.kt\n@@ -123,15 +123,15 @@ class FormatReporterTest {\n }\n \n companion object {\n- @Suppress(\"ktlint:argument-list-wrapping\", \"ktlint:max-line-length\")\n+ @Suppress(\"ktlint:standard:argument-list-wrapping\", \"ktlint:standard:max-line-length\")\n val SOME_LINT_ERROR_CAN_BE_AUTOCORRECTED =\n KtlintCliError(1, 1, \"some-rule\", \"This error can be autocorrected\", LINT_CAN_BE_AUTOCORRECTED)\n \n- @Suppress(\"ktlint:argument-list-wrapping\", \"ktlint:max-line-length\")\n+ @Suppress(\"ktlint:standard:argument-list-wrapping\", \"ktlint:standard:max-line-length\")\n val SOME_LINT_ERROR_CAN_NOT_BE_AUTOCORRECTED =\n KtlintCliError(1, 1, \"rule-1\", \"This error can *not* be autocorrected\", LINT_CAN_NOT_BE_AUTOCORRECTED)\n \n- @Suppress(\"ktlint:argument-list-wrapping\", \"ktlint:max-line-length\")\n+ @Suppress(\"ktlint:standard:argument-list-wrapping\", \"ktlint:standard:max-line-length\")\n val SOME_FORMAT_ERROR_IS_AUTOCORRECTED =\n KtlintCliError(1, 1, \"rule-1\", \"This error can *not* be autocorrected\", FORMAT_IS_AUTOCORRECTED)\n \ndiff --git a/ktlint-cli-reporter-html/src/test/kotlin/com/pinterest/ktlint/cli/reporter/html/HtmlReporterTest.kt b/ktlint-cli-reporter-html/src/test/kotlin/com/pinterest/ktlint/cli/reporter/html/HtmlReporterTest.kt\nindex 2a93880cda..51b8b78187 100644\n--- a/ktlint-cli-reporter-html/src/test/kotlin/com/pinterest/ktlint/cli/reporter/html/HtmlReporterTest.kt\n+++ b/ktlint-cli-reporter-html/src/test/kotlin/com/pinterest/ktlint/cli/reporter/html/HtmlReporterTest.kt\n@@ -157,13 +157,13 @@ class HtmlReporterTest {\n val out = ByteArrayOutputStream()\n val reporter = HtmlReporter(PrintStream(out, true))\n \n- @Suppress(\"ktlint:argument-list-wrapping\", \"ktlint:max-line-length\")\n+ @Suppress(\"ktlint:standard:argument-list-wrapping\", \"ktlint:standard:max-line-length\")\n reporter.onLintError(\n \"/file1.kt\",\n KtlintCliError(1, 1, \"rule-1\", \"Error message contains a generic type like List (cannot be auto-corrected)\", LINT_CAN_BE_AUTOCORRECTED),\n )\n \n- @Suppress(\"ktlint:argument-list-wrapping\", \"ktlint:max-line-length\")\n+ @Suppress(\"ktlint:standard:argument-list-wrapping\", \"ktlint:standard:max-line-length\")\n reporter.onLintError(\n \"/file1.kt\",\n KtlintCliError(2, 1, \"rule-2\", \"Error message contains special html symbols like ac\\\"d'e&f (cannot be auto-corrected)\", LINT_CAN_BE_AUTOCORRECTED),\ndiff --git a/ktlint-cli-reporter-json/src/test/kotlin/com/pinterest/ktlint/cli/reporter/json/JsonReporterTest.kt b/ktlint-cli-reporter-json/src/test/kotlin/com/pinterest/ktlint/cli/reporter/json/JsonReporterTest.kt\nindex 7f22039b16..ea8f095977 100644\n--- a/ktlint-cli-reporter-json/src/test/kotlin/com/pinterest/ktlint/cli/reporter/json/JsonReporterTest.kt\n+++ b/ktlint-cli-reporter-json/src/test/kotlin/com/pinterest/ktlint/cli/reporter/json/JsonReporterTest.kt\n@@ -15,29 +15,29 @@ class JsonReporterTest {\n val reporter = JsonReporter(PrintStream(out, true))\n reporter.onLintError(\n \"/one-fixed-and-one-not.kt\",\n- @Suppress(\"ktlint:argument-list-wrapping\")\n+ @Suppress(\"ktlint:standard:argument-list-wrapping\")\n KtlintCliError(1, 1, \"rule-1\", \"<\\\"&'>\", LINT_CAN_BE_AUTOCORRECTED),\n )\n reporter.onLintError(\n \"/one-fixed-and-one-not.kt\",\n- @Suppress(\"ktlint:argument-list-wrapping\")\n+ @Suppress(\"ktlint:standard:argument-list-wrapping\")\n KtlintCliError(2, 1, \"rule-2\", \"And if you see my friend\", FORMAT_IS_AUTOCORRECTED),\n )\n \n reporter.onLintError(\n \"/two-not-fixed.kt\",\n- @Suppress(\"ktlint:argument-list-wrapping\")\n+ @Suppress(\"ktlint:standard:argument-list-wrapping\")\n KtlintCliError(1, 10, \"rule-1\", \"I thought I would again\", LINT_CAN_BE_AUTOCORRECTED),\n )\n reporter.onLintError(\n \"/two-not-fixed.kt\",\n- @Suppress(\"ktlint:argument-list-wrapping\")\n+ @Suppress(\"ktlint:standard:argument-list-wrapping\")\n KtlintCliError(2, 20, \"rule-2\", \"A single thin straight line\", LINT_CAN_BE_AUTOCORRECTED),\n )\n \n reporter.onLintError(\n \"/all-corrected.kt\",\n- @Suppress(\"ktlint:argument-list-wrapping\")\n+ @Suppress(\"ktlint:standard:argument-list-wrapping\")\n KtlintCliError(1, 1, \"rule-1\", \"I thought we had more time\", FORMAT_IS_AUTOCORRECTED),\n )\n reporter.afterAll()\ndiff --git a/ktlint-cli-reporter-plain-summary/src/test/kotlin/com/pinterest/ktlint/cli/reporter/plain/PlainSummaryReporterTest.kt b/ktlint-cli-reporter-plain-summary/src/test/kotlin/com/pinterest/ktlint/cli/reporter/plain/PlainSummaryReporterTest.kt\nindex 45ffbdb88a..121bc9d391 100644\n--- a/ktlint-cli-reporter-plain-summary/src/test/kotlin/com/pinterest/ktlint/cli/reporter/plain/PlainSummaryReporterTest.kt\n+++ b/ktlint-cli-reporter-plain-summary/src/test/kotlin/com/pinterest/ktlint/cli/reporter/plain/PlainSummaryReporterTest.kt\n@@ -19,29 +19,29 @@ class PlainSummaryReporterTest {\n ).apply {\n onLintError(\n \"file-1.kt\",\n- @Suppress(\"ktlint:argument-list-wrapping\")\n+ @Suppress(\"ktlint:standard:argument-list-wrapping\")\n KtlintCliError(1, 1, \"rule-1\", \"description-error-at-position-1:1 (cannot be auto-corrected)\", LINT_CAN_BE_AUTOCORRECTED),\n )\n onLintError(\n \"file-1.kt\",\n- @Suppress(\"ktlint:argument-list-wrapping\")\n+ @Suppress(\"ktlint:standard:argument-list-wrapping\")\n KtlintCliError(2, 1, \"rule-2\", \"description-error-at-position-2:1\", FORMAT_IS_AUTOCORRECTED),\n )\n \n onLintError(\n \"file-2.kt\",\n- @Suppress(\"ktlint:argument-list-wrapping\")\n+ @Suppress(\"ktlint:standard:argument-list-wrapping\")\n KtlintCliError(1, 10, \"rule-1\", \"description-error-at-position-1:10 (cannot be auto-corrected)\", LINT_CAN_BE_AUTOCORRECTED),\n )\n onLintError(\n \"file-2.kt\",\n- @Suppress(\"ktlint:argument-list-wrapping\")\n+ @Suppress(\"ktlint:standard:argument-list-wrapping\")\n KtlintCliError(2, 20, \"rule-2\", \"description-error-at-position-2:20 (cannot be auto-corrected)\", LINT_CAN_BE_AUTOCORRECTED),\n )\n \n onLintError(\n \"file-3.kt\",\n- @Suppress(\"ktlint:argument-list-wrapping\")\n+ @Suppress(\"ktlint:standard:argument-list-wrapping\")\n KtlintCliError(1, 1, \"rule-1\", \"description-error-at-position-1:1\", FORMAT_IS_AUTOCORRECTED),\n )\n \n@@ -72,17 +72,17 @@ class PlainSummaryReporterTest {\n val reporter = PlainSummaryReporter(PrintStream(out, true))\n reporter.onLintError(\n \"file-1.kt\",\n- @Suppress(\"ktlint:argument-list-wrapping\", \"ktlint:max-line-length\")\n+ @Suppress(\"ktlint:standard:argument-list-wrapping\", \"ktlint:standard:max-line-length\")\n KtlintCliError(18, 51, \"\", \"Not a valid Kotlin file (18:51 unexpected tokens (use ';' to separate expressions on the same line)) (cannot be auto-corrected) ()\", KOTLIN_PARSE_EXCEPTION),\n )\n reporter.onLintError(\n \"file-2.kt\",\n- @Suppress(\"ktlint:argument-list-wrapping\", \"ktlint:max-line-length\")\n+ @Suppress(\"ktlint:standard:argument-list-wrapping\", \"ktlint:standard:max-line-length\")\n KtlintCliError(18, 51, \"\", \"Not a valid Kotlin file (18:51 unexpected tokens (use ';' to separate expressions on the same line)) (cannot be auto-corrected) ()\", KOTLIN_PARSE_EXCEPTION),\n )\n reporter.onLintError(\n \"file-3.kt\",\n- @Suppress(\"ktlint:argument-list-wrapping\")\n+ @Suppress(\"ktlint:standard:argument-list-wrapping\")\n KtlintCliError(18, 51, \"\", \"Something else\", LINT_CAN_BE_AUTOCORRECTED),\n )\n reporter.afterAll()\ndiff --git a/ktlint-cli-reporter-plain/src/test/kotlin/com/pinterest/ktlint/cli/reporter/plain/PlainReporterTest.kt b/ktlint-cli-reporter-plain/src/test/kotlin/com/pinterest/ktlint/cli/reporter/plain/PlainReporterTest.kt\nindex 100ef42aa6..cf207b61cb 100644\n--- a/ktlint-cli-reporter-plain/src/test/kotlin/com/pinterest/ktlint/cli/reporter/plain/PlainReporterTest.kt\n+++ b/ktlint-cli-reporter-plain/src/test/kotlin/com/pinterest/ktlint/cli/reporter/plain/PlainReporterTest.kt\n@@ -17,29 +17,29 @@ class PlainReporterTest {\n val reporter = PlainReporter(PrintStream(out, true))\n reporter.onLintError(\n \"file-1.kt\",\n- @Suppress(\"ktlint:argument-list-wrapping\")\n+ @Suppress(\"ktlint:standard:argument-list-wrapping\")\n KtlintCliError(1, 1, \"rule-1\", \"description-error-at-position-1:1\", LINT_CAN_BE_AUTOCORRECTED),\n )\n reporter.onLintError(\n \"file-1.kt\",\n- @Suppress(\"ktlint:argument-list-wrapping\")\n+ @Suppress(\"ktlint:standard:argument-list-wrapping\")\n KtlintCliError(2, 1, \"rule-2\", \"description-error-at-position-2:1\", FORMAT_IS_AUTOCORRECTED),\n )\n \n reporter.onLintError(\n \"file-2.kt\",\n- @Suppress(\"ktlint:argument-list-wrapping\")\n+ @Suppress(\"ktlint:standard:argument-list-wrapping\")\n KtlintCliError(1, 10, \"rule-1\", \"description-error-at-position-1:10\", LINT_CAN_BE_AUTOCORRECTED),\n )\n reporter.onLintError(\n \"file-2.kt\",\n- @Suppress(\"ktlint:argument-list-wrapping\")\n+ @Suppress(\"ktlint:standard:argument-list-wrapping\")\n KtlintCliError(2, 20, \"rule-2\", \"description-error-at-position-2:20\", LINT_CAN_BE_AUTOCORRECTED),\n )\n \n reporter.onLintError(\n \"file-3.kt\",\n- @Suppress(\"ktlint:argument-list-wrapping\")\n+ @Suppress(\"ktlint:standard:argument-list-wrapping\")\n KtlintCliError(1, 1, \"rule-1\", \"description-error-at-position-1:1\", FORMAT_IS_AUTOCORRECTED),\n )\n \n@@ -65,17 +65,17 @@ class PlainReporterTest {\n val reporter = PlainReporter(PrintStream(out, true))\n reporter.onLintError(\n \"file-1.kt\",\n- @Suppress(\"ktlint:argument-list-wrapping\", \"ktlint:max-line-length\")\n+ @Suppress(\"ktlint:standard:argument-list-wrapping\", \"ktlint:standard:max-line-length\")\n KtlintCliError(18, 51, \"\", \"Not a valid Kotlin file (18:51 unexpected tokens (use ';' to separate expressions on the same line)) (cannot be auto-corrected) ()\", KOTLIN_PARSE_EXCEPTION),\n )\n reporter.onLintError(\n \"file-2.kt\",\n- @Suppress(\"ktlint:argument-list-wrapping\", \"ktlint:max-line-length\")\n+ @Suppress(\"ktlint:standard:argument-list-wrapping\", \"ktlint:standard:max-line-length\")\n KtlintCliError(18, 51, \"\", \"Not a valid Kotlin file (18:51 unexpected tokens (use ';' to separate expressions on the same line)) (cannot be auto-corrected) ()\", KOTLIN_PARSE_EXCEPTION),\n )\n reporter.onLintError(\n \"file-3.kt\",\n- @Suppress(\"ktlint:argument-list-wrapping\")\n+ @Suppress(\"ktlint:standard:argument-list-wrapping\")\n KtlintCliError(18, 51, \"\", \"Something else\", LINT_CAN_BE_AUTOCORRECTED),\n )\n reporter.afterAll()\n@@ -106,7 +106,7 @@ class PlainReporterTest {\n )\n reporter.onLintError(\n File.separator + \"one-fixed-and-one-not.kt\",\n- @Suppress(\"ktlint:argument-list-wrapping\")\n+ @Suppress(\"ktlint:standard:argument-list-wrapping\")\n KtlintCliError(1, 1, \"rule-1\", \"<\\\"&'>\", LINT_CAN_BE_AUTOCORRECTED),\n )\n val outputString = String(out.toByteArray())\n@@ -130,29 +130,29 @@ class PlainReporterTest {\n val reporter = PlainReporter(PrintStream(out, true), groupByFile = true)\n reporter.onLintError(\n \"/one-fixed-and-one-not.kt\",\n- @Suppress(\"ktlint:argument-list-wrapping\")\n+ @Suppress(\"ktlint:standard:argument-list-wrapping\")\n KtlintCliError(1, 1, \"rule-1\", \"<\\\"&'>\", LINT_CAN_BE_AUTOCORRECTED),\n )\n reporter.onLintError(\n \"/one-fixed-and-one-not.kt\",\n- @Suppress(\"ktlint:argument-list-wrapping\")\n+ @Suppress(\"ktlint:standard:argument-list-wrapping\")\n KtlintCliError(2, 1, \"rule-2\", \"And if you see my friend\", FORMAT_IS_AUTOCORRECTED),\n )\n \n reporter.onLintError(\n \"/two-not-fixed.kt\",\n- @Suppress(\"ktlint:argument-list-wrapping\")\n+ @Suppress(\"ktlint:standard:argument-list-wrapping\")\n KtlintCliError(1, 10, \"rule-1\", \"I thought I would again\", LINT_CAN_BE_AUTOCORRECTED),\n )\n reporter.onLintError(\n \"/two-not-fixed.kt\",\n- @Suppress(\"ktlint:argument-list-wrapping\")\n+ @Suppress(\"ktlint:standard:argument-list-wrapping\")\n KtlintCliError(2, 20, \"rule-2\", \"A single thin straight line\", LINT_CAN_BE_AUTOCORRECTED),\n )\n \n reporter.onLintError(\n \"/all-corrected.kt\",\n- @Suppress(\"ktlint:argument-list-wrapping\")\n+ @Suppress(\"ktlint:standard:argument-list-wrapping\")\n KtlintCliError(1, 1, \"rule-1\", \"I thought we had more time\", FORMAT_IS_AUTOCORRECTED),\n )\n reporter.after(\"/one-fixed-and-one-not.kt\")\ndiff --git a/ktlint-rule-engine/src/test/kotlin/com/pinterest/ktlint/rule/engine/internal/SuppressionLocatorBuilderTest.kt b/ktlint-rule-engine/src/test/kotlin/com/pinterest/ktlint/rule/engine/internal/SuppressionLocatorBuilderTest.kt\nindex c0acb7df7c..b7c2d4b579 100644\n--- a/ktlint-rule-engine/src/test/kotlin/com/pinterest/ktlint/rule/engine/internal/SuppressionLocatorBuilderTest.kt\n+++ b/ktlint-rule-engine/src/test/kotlin/com/pinterest/ktlint/rule/engine/internal/SuppressionLocatorBuilderTest.kt\n@@ -2,6 +2,7 @@ package com.pinterest.ktlint.rule.engine.internal\n \n import com.pinterest.ktlint.rule.engine.api.Code\n import com.pinterest.ktlint.rule.engine.api.EditorConfigOverride\n+import com.pinterest.ktlint.rule.engine.api.EditorConfigOverride.Companion.EMPTY_EDITOR_CONFIG_OVERRIDE\n import com.pinterest.ktlint.rule.engine.api.EditorConfigOverride.Companion.plus\n import com.pinterest.ktlint.rule.engine.api.KtLintRuleEngine\n import com.pinterest.ktlint.rule.engine.api.LintError\n@@ -15,6 +16,8 @@ import com.pinterest.ktlint.rule.engine.core.api.editorconfig.createRuleExecutio\n import com.pinterest.ktlint.rule.engine.internal.FormatterTags.Companion.FORMATTER_TAGS_ENABLED_PROPERTY\n import com.pinterest.ktlint.rule.engine.internal.FormatterTags.Companion.FORMATTER_TAG_OFF_ENABLED_PROPERTY\n import com.pinterest.ktlint.rule.engine.internal.FormatterTags.Companion.FORMATTER_TAG_ON_ENABLED_PROPERTY\n+import com.pinterest.ktlint.rule.engine.internal.rules.KTLINT_SUPPRESSION_RULE_ID\n+import com.pinterest.ktlint.ruleset.standard.rules.IndentationRule\n import org.assertj.core.api.Assertions.assertThat\n import org.jetbrains.kotlin.com.intellij.lang.ASTNode\n import org.junit.jupiter.api.Nested\n@@ -37,51 +40,16 @@ class SuppressionLocatorBuilderTest {\n }\n \n @Test\n- fun `Given that a NoFooIdentifierRule violation is suppressed with an EOL-comment to disable all rules then do not find a violation`() {\n+ fun `Given a line having a NoFooIdentifierRule violation and an EOL-comment with a ktlint-directive to disable all rules then do not suppress the violation anymore`() {\n val code =\n \"\"\"\n val foo = \"foo\" // ktlint-disable\n \"\"\".trimIndent()\n- assertThat(lint(code)).isEmpty()\n- }\n-\n- @Test\n- fun `Given that a NoFooIdentifierRule violation is suppressed with an EOL-comment for the specific rule then do not find a violation`() {\n- val code =\n- \"\"\"\n- val foo = \"foo\" // ktlint-disable no-foo-identifier-standard $NON_STANDARD_RULE_SET_ID:no-foo-identifier\n- \"\"\".trimIndent()\n- assertThat(lint(code)).isEmpty()\n- }\n-\n- @Test\n- fun `Given that a NoFooIdentifierRule violation is suppressed with a block comment for all rules then do not find a violation in that block`() {\n- val code =\n- \"\"\"\n- /* ktlint-disable */\n- val fooNotReported = \"foo\"\n- /* ktlint-enable */\n- val fooReported = \"foo\"\n- \"\"\".trimIndent()\n- assertThat(lint(code)).containsExactly(\n- lintError(4, 5, \"standard:no-foo-identifier-standard\"),\n- lintError(4, 5, \"$NON_STANDARD_RULE_SET_ID:no-foo-identifier\"),\n- )\n- }\n-\n- @Test\n- fun `Given that a NoFooIdentifierRule violation is suppressed with a block comment for a specific rule then do not find a violation for that rule in that block`() {\n- val code =\n- \"\"\"\n- /* ktlint-disable no-foo-identifier-standard $NON_STANDARD_RULE_SET_ID:no-foo-identifier */\n- val fooNotReported = \"foo\"\n- /* ktlint-enable no-foo-identifier-standard $NON_STANDARD_RULE_SET_ID:no-foo-identifier */\n- val fooReported = \"foo\"\n- \"\"\".trimIndent()\n- assertThat(lint(code)).containsExactly(\n- lintError(4, 5, \"standard:no-foo-identifier-standard\"),\n- lintError(4, 5, \"$NON_STANDARD_RULE_SET_ID:no-foo-identifier\"),\n- )\n+ @Suppress(\"ktlint:standard:argument-list-wrapping\", \"ktlint:standard:max-line-length\")\n+ assertThat(lint(code))\n+ .contains(\n+ LintError(1, 5, STANDARD_NO_FOO_IDENTIFIER_RULE_ID, \"Line should not contain a foo identifier\", false),\n+ )\n }\n \n @Test\n@@ -214,24 +182,6 @@ class SuppressionLocatorBuilderTest {\n assertThat(lint(code)).isEmpty()\n }\n \n- @Test\n- fun `Given an invalid rule id then ignore it without throwing an exception`() {\n- val code =\n- \"\"\"\n- @file:Suppress(\"ktlint:standard:SOME-INVALID-RULE-ID-1\")\n-\n- @Suppress(\"ktlint:standard:SOME-INVALID-RULE-ID-2\")\n- class Foo {\n- /* ktlint-disable standard:SOME-INVALID-RULE-ID-3 */\n- fun foo() {\n- val fooNotReported = \"foo\" // ktlint-disable standard:SOME-INVALID-RULE-ID-4\n- }\n- /* ktlint-enable standard:SOME-INVALID-RULE-ID-3 */\n- }\n- \"\"\".trimIndent()\n- assertThat(lint(code)).isEmpty()\n- }\n-\n @Nested\n inner class `Given that formatter tags are enabled` {\n @Test\n@@ -329,6 +279,96 @@ class SuppressionLocatorBuilderTest {\n }\n }\n \n+ @Nested\n+ inner class `Given code that tries to disable to ktlint-suppression rule itself` {\n+ @Test\n+ fun `Given a @file annotation`() {\n+ val code =\n+ \"\"\"\n+ @file:Suppress(\"ktlint:internal:ktlint-suppression\")\n+ \"\"\".trimIndent()\n+ val actual = lint(code = code, ignoreKtlintSuppressionRule = false)\n+ @Suppress(\"ktlint:standard:argument-list-wrapping\", \"ktlint:standard:max-line-length\")\n+ assertThat(actual).containsExactly(\n+ LintError(1, 24, KTLINT_SUPPRESSION_RULE_ID, \"Ktlint rule with id 'ktlint:internal:ktlint-suppression' is unknown or not loaded\", false),\n+ )\n+ }\n+\n+ @Test\n+ fun `Given a block comment with a ktlint-disable directive`() {\n+ val code =\n+ \"\"\"\n+ /* ktlint-disable internal:ktlint-suppression */\n+ \"\"\".trimIndent()\n+ val actual = lint(code = code, ignoreKtlintSuppressionRule = false)\n+ @Suppress(\"ktlint:standard:argument-list-wrapping\", \"ktlint:standard:max-line-length\")\n+ assertThat(actual).containsExactly(\n+ LintError(1, 4, KTLINT_SUPPRESSION_RULE_ID, \"Directive 'ktlint-disable' is deprecated. Replace with @Suppress annotation\", true),\n+ LintError(1, 19, KTLINT_SUPPRESSION_RULE_ID, \"Ktlint rule with id 'internal:ktlint-suppression' is unknown or not loaded\", false),\n+ )\n+ }\n+\n+ @Test\n+ fun `Given an EOL comment with a ktlint-disable directive which is ignored then emit the violation`() {\n+ val code =\n+ \"\"\"\n+ val foo = \"foo\" // ktlint-disable internal:ktlint-suppression\n+ \"\"\".trimIndent()\n+ val actual = lint(code = code, ignoreKtlintSuppressionRule = false)\n+ @Suppress(\"ktlint:standard:argument-list-wrapping\", \"ktlint:standard:max-line-length\")\n+ assertThat(actual).containsExactly(\n+ lintError(1, 5, \"standard:no-foo-identifier-standard\"),\n+ lintError(1, 5, \"$NON_STANDARD_RULE_SET_ID:no-foo-identifier\"),\n+ LintError(1, 20, KTLINT_SUPPRESSION_RULE_ID, \"Directive 'ktlint-disable' is deprecated. Replace with @Suppress annotation\", true),\n+ LintError(1, 35, KTLINT_SUPPRESSION_RULE_ID, \"Ktlint rule with id 'internal:ktlint-suppression' is unknown or not loaded\", false),\n+ )\n+ }\n+ }\n+\n+ @Test\n+ fun `Given a suppression of a rule which alphabetically comes before rule id ktlint-suppression`() {\n+ val code =\n+ \"\"\"\n+ fun bar() {\n+ /* ktlint-disable standard:indent */\n+ return mapOf(\n+ 1 to \" 1 ms\",\n+ 10 to \" 10 ms\",\n+ 999 to \" 999 ms\",\n+ 1000 to \" 1 sec\",\n+ )\n+ /* ktlint-enable standard:indent */\n+ }\n+ \"\"\".trimIndent()\n+ val formattedCode =\n+ \"\"\"\n+ @Suppress(\"ktlint:standard:indent\")\n+ fun bar() {\n+ return mapOf(\n+ 1 to \" 1 ms\",\n+ 10 to \" 10 ms\",\n+ 999 to \" 999 ms\",\n+ 1000 to \" 1 sec\",\n+ )\n+ }\n+ \"\"\".trimIndent()\n+\n+ val actual =\n+ KtLintRuleEngine(\n+ ruleProviders =\n+ setOf(\n+ RuleProvider { IndentationRule() },\n+ ),\n+ editorConfigOverride =\n+ EMPTY_EDITOR_CONFIG_OVERRIDE\n+ .plus(\n+ STANDARD_NO_FOO_IDENTIFIER_RULE_ID.createRuleExecutionEditorConfigProperty() to RuleExecution.enabled,\n+ ),\n+ ).format(Code.fromSnippet(code)) { _, _ -> }\n+\n+ assertThat(actual).isEqualTo(formattedCode)\n+ }\n+\n private class NoFooIdentifierRule(id: RuleId) : Rule(\n ruleId = id,\n about = About(),\n@@ -347,6 +387,8 @@ class SuppressionLocatorBuilderTest {\n private fun lint(\n code: String,\n editorConfigOverride: EditorConfigOverride = EditorConfigOverride.EMPTY_EDITOR_CONFIG_OVERRIDE,\n+ ruleProviders: Set = emptySet(),\n+ ignoreKtlintSuppressionRule: Boolean = true,\n ) = ArrayList().apply {\n KtLintRuleEngine(\n ruleProviders =\n@@ -355,21 +397,27 @@ class SuppressionLocatorBuilderTest {\n // ruleIds are different.\n RuleProvider { NoFooIdentifierRule(STANDARD_NO_FOO_IDENTIFIER_RULE_ID) },\n RuleProvider { NoFooIdentifierRule(NON_STANDARD_NO_FOO_IDENTIFIER_RULE_ID) },\n- ),\n+ ).plus(ruleProviders),\n editorConfigOverride =\n editorConfigOverride\n .plus(\n STANDARD_NO_FOO_IDENTIFIER_RULE_ID.createRuleExecutionEditorConfigProperty() to RuleExecution.enabled,\n NON_STANDARD_NO_FOO_IDENTIFIER_RULE_ID.createRuleExecutionEditorConfigProperty() to RuleExecution.enabled,\n ),\n- ).lint(Code.fromSnippet(code)) { e -> add(e) }\n+ ).lint(Code.fromSnippet(code)) { e ->\n+ if (ignoreKtlintSuppressionRule && e.ruleId == KTLINT_SUPPRESSION_RULE_ID) {\n+ // This class should be able to test code snippets containing the deprecated ktlint-directives\n+ } else {\n+ add(e)\n+ }\n+ }\n }\n \n private fun lintError(\n line: Int,\n- col: Int,\n+ column: Int,\n ruleId: String,\n- ) = LintError(line, col, RuleId(ruleId), \"Line should not contain a foo identifier\", false)\n+ ) = LintError(line, column, RuleId(ruleId), \"Line should not contain a foo identifier\", false)\n \n private companion object {\n val NON_STANDARD_RULE_SET_ID = \"custom\".also { require(it != RuleSetId.STANDARD.value) }\ndiff --git a/ktlint-rule-engine/src/test/kotlin/com/pinterest/ktlint/rule/engine/internal/rulefilter/InternalRuleProvidersFilterTest.kt b/ktlint-rule-engine/src/test/kotlin/com/pinterest/ktlint/rule/engine/internal/rulefilter/InternalRuleProvidersFilterTest.kt\nnew file mode 100644\nindex 0000000000..433fe7dce2\n--- /dev/null\n+++ b/ktlint-rule-engine/src/test/kotlin/com/pinterest/ktlint/rule/engine/internal/rulefilter/InternalRuleProvidersFilterTest.kt\n@@ -0,0 +1,62 @@\n+package com.pinterest.ktlint.rule.engine.internal.rulefilter\n+\n+import com.pinterest.ktlint.rule.engine.api.KtLintRuleEngine\n+import com.pinterest.ktlint.rule.engine.core.api.Rule\n+import com.pinterest.ktlint.rule.engine.core.api.RuleId\n+import com.pinterest.ktlint.rule.engine.core.api.RuleProvider\n+import com.pinterest.ktlint.rule.engine.core.api.RuleSetId\n+import com.pinterest.ktlint.rule.engine.internal.rules.KTLINT_SUPPRESSION_RULE_ID\n+import org.assertj.core.api.Assertions.assertThat\n+import org.jetbrains.kotlin.com.intellij.lang.ASTNode\n+import org.junit.jupiter.api.Test\n+\n+class InternalRuleProvidersFilterTest {\n+ @Test\n+ fun `Given a ktlint rule engine then add the ktlint suppression rule provider`() {\n+ val ktLintRuleEngine =\n+ KtLintRuleEngine(\n+ ruleProviders =\n+ setOf(\n+ RuleProvider {\n+ object : R(ruleId = STANDARD_RULE_A) {}\n+ },\n+ ),\n+ )\n+ val actual =\n+ InternalRuleProvidersFilter(ktLintRuleEngine)\n+ .filter(ktLintRuleEngine.ruleProviders)\n+ .toRuleId()\n+\n+ assertThat(actual).containsExactly(\n+ STANDARD_RULE_A,\n+ KTLINT_SUPPRESSION_RULE_ID,\n+ )\n+ }\n+\n+ private companion object {\n+ const val RULE_A = \"rule-a\"\n+ val STANDARD = RuleSetId.STANDARD.value\n+ val STANDARD_RULE_A = RuleId(\"$STANDARD:$RULE_A\")\n+ }\n+\n+ private open class R(\n+ ruleId: RuleId,\n+ visitorModifiers: Set = emptySet(),\n+ ) : Rule(\n+ ruleId = ruleId,\n+ about = About(),\n+ visitorModifiers,\n+ ) {\n+ override fun beforeVisitChildNodes(\n+ node: ASTNode,\n+ autoCorrect: Boolean,\n+ emit: (offset: Int, errorMessage: String, canBeAutoCorrected: Boolean) -> Unit,\n+ ) {\n+ throw UnsupportedOperationException(\n+ \"Rule should never be really invoked because that is not the aim of this unit test.\",\n+ )\n+ }\n+ }\n+\n+ private fun Set.toRuleId() = map { it.ruleId }\n+}\ndiff --git a/ktlint-rule-engine/src/test/kotlin/com/pinterest/ktlint/rule/engine/internal/rulefilter/RuleFilterKtTest.kt b/ktlint-rule-engine/src/test/kotlin/com/pinterest/ktlint/rule/engine/internal/rulefilter/RuleFilterKtTest.kt\nindex 7e8167f065..aaa5b32248 100644\n--- a/ktlint-rule-engine/src/test/kotlin/com/pinterest/ktlint/rule/engine/internal/rulefilter/RuleFilterKtTest.kt\n+++ b/ktlint-rule-engine/src/test/kotlin/com/pinterest/ktlint/rule/engine/internal/rulefilter/RuleFilterKtTest.kt\n@@ -12,7 +12,7 @@ class RuleFilterKtTest {\n fun `Given an empty list of rule filters then the list of rule providers contains provider for all rule ids initially provided by the ktlint engine`() {\n val actual =\n createKtLintRuleEngine(arrayOf(RULE_SET_A_RULE_A, RULE_SET_A_RULE_B, RULE_SET_B_RULE_A, RULE_SET_B_RULE_B))\n- .ruleProviders()\n+ .applyRuleFilters()\n .map { it.ruleId }\n \n assertThat(actual).containsExactlyInAnyOrder(RULE_SET_A_RULE_A, RULE_SET_A_RULE_B, RULE_SET_B_RULE_A, RULE_SET_B_RULE_B)\n@@ -22,7 +22,7 @@ class RuleFilterKtTest {\n fun `Given a single rule filter then the list of rule providers contains only rule ids that match that filter`() {\n val actual =\n createKtLintRuleEngine(arrayOf(RULE_SET_A_RULE_A, RULE_SET_A_RULE_B, RULE_SET_B_RULE_A, RULE_SET_B_RULE_B))\n- .ruleProviders(RuleIdRuleFilter(RULE_SET_A))\n+ .applyRuleFilters(RuleIdRuleFilter(RULE_SET_A))\n .map { it.ruleId }\n \n assertThat(actual).containsExactlyInAnyOrder(RULE_SET_A_RULE_A, RULE_SET_A_RULE_B)\n@@ -32,7 +32,7 @@ class RuleFilterKtTest {\n fun `Given multiple rule filters then the list of rule providers contains only rule ids that match all filters`() {\n val actual =\n createKtLintRuleEngine(arrayOf(RULE_SET_A_RULE_A, RULE_SET_A_RULE_B, RULE_SET_B_RULE_B))\n- .ruleProviders(\n+ .applyRuleFilters(\n RuleIdRuleFilter(RULE_SET_A),\n RuleIdRuleFilter(RULE_B),\n ).map { it.ruleId }\n@@ -44,7 +44,7 @@ class RuleFilterKtTest {\n fun `Given multiple rule filters that exclude each other then the list of rule providers is empty`() {\n val actual =\n createKtLintRuleEngine(arrayOf(RULE_SET_A_RULE_A))\n- .ruleProviders(\n+ .applyRuleFilters(\n RuleIdRuleFilter(RULE_A),\n RuleIdRuleFilter(RULE_SET_B),\n ).map { it.ruleId }\ndiff --git a/ktlint-rule-engine/src/test/kotlin/com/pinterest/ktlint/rule/engine/internal/rules/KtlintSuppressionRuleTest.kt b/ktlint-rule-engine/src/test/kotlin/com/pinterest/ktlint/rule/engine/internal/rules/KtlintSuppressionRuleTest.kt\nnew file mode 100644\nindex 0000000000..4ee2aa4163\n--- /dev/null\n+++ b/ktlint-rule-engine/src/test/kotlin/com/pinterest/ktlint/rule/engine/internal/rules/KtlintSuppressionRuleTest.kt\n@@ -0,0 +1,1329 @@\n+package com.pinterest.ktlint.rule.engine.internal.rules\n+\n+import com.pinterest.ktlint.rule.engine.core.api.Rule\n+import com.pinterest.ktlint.rule.engine.core.api.RuleId\n+import com.pinterest.ktlint.rule.engine.core.api.RuleProvider\n+import com.pinterest.ktlint.ruleset.standard.rules.ArgumentListWrappingRule\n+import com.pinterest.ktlint.test.KtLintAssertThat.Companion.assertThatRule\n+import com.pinterest.ktlint.test.KtlintDocumentationTest\n+import com.pinterest.ktlint.test.LintViolation\n+import org.junit.jupiter.api.Nested\n+import org.junit.jupiter.api.Test\n+import org.junit.jupiter.params.ParameterizedTest\n+import org.junit.jupiter.params.provider.CsvSource\n+import org.junit.jupiter.params.provider.ValueSource\n+\n+class KtlintSuppressionRuleTest {\n+ private val ktlintSuppressionRuleAssertThat =\n+ assertThatRule(\n+ provider = { KtlintSuppressionRule(emptyList()) },\n+ additionalRuleProviders =\n+ setOf(\n+ // Create a dummy rule for each rule id that is used in a ktlint directive or suppression in the tests in this\n+ // class. If no rule provider is added for the rule id, a lint violation is thrown which will bloat the tests too\n+ // much.\n+ //\n+ // Ids of real rules used but for which the real implementation is unwanted as it would modify the formatted code\n+ RuleProvider { DummyRule(\"standard:no-wildcard-imports\") },\n+ RuleProvider { DummyRule(\"standard:no-multi-spaces\") },\n+ RuleProvider { DummyRule(\"standard:max-line-length\") },\n+ RuleProvider { DummyRule(\"standard:package-name\") },\n+ // Ids of fake rules in a custom and the standard rule set\n+ RuleProvider { DummyRule(\"custom:foo\") },\n+ RuleProvider { DummyRule(\"standard:bar\") },\n+ RuleProvider { DummyRule(\"standard:foo\") },\n+ ),\n+ )\n+\n+ @Nested\n+ inner class `Given a suppression annotation missing the rule set id prefix` {\n+ @Test\n+ fun `Given a @file Suppress annotation`() {\n+ val code =\n+ \"\"\"\n+ @file:Suppress(\"ktlint:bar\", \"ktlint:standard:foo\", \"ktlint:custom:foo\")\n+ \"\"\".trimIndent()\n+ val formattedCode =\n+ \"\"\"\n+ @file:Suppress(\"ktlint:standard:bar\", \"ktlint:standard:foo\", \"ktlint:custom:foo\")\n+ \"\"\".trimIndent()\n+ ktlintSuppressionRuleAssertThat(code)\n+ .hasLintViolation(1, 24, \"Identifier to suppress ktlint rule must be fully qualified with the rule set id\")\n+ .isFormattedAs(formattedCode)\n+ }\n+\n+ @Test\n+ fun `Given a @file SuppressWarnings annotation`() {\n+ val code =\n+ \"\"\"\n+ @file:SuppressWarnings(\"ktlint:bar\", \"ktlint:standard:foo\", \"ktlint:custom:foo\")\n+ \"\"\".trimIndent()\n+ val formattedCode =\n+ \"\"\"\n+ @file:SuppressWarnings(\"ktlint:standard:bar\", \"ktlint:standard:foo\", \"ktlint:custom:foo\")\n+ \"\"\".trimIndent()\n+ ktlintSuppressionRuleAssertThat(code)\n+ .hasLintViolation(1, 32, \"Identifier to suppress ktlint rule must be fully qualified with the rule set id\")\n+ .isFormattedAs(formattedCode)\n+ }\n+\n+ @Test\n+ fun `Given a @file array annotation with Suppress and SuppressWarnings annotations`() {\n+ val code =\n+ \"\"\"\n+ @file:[Suppress(\"ktlint:bar\", \"ktlint:custom:foo\") SuppressWarnings(\"ktlint:foo\")]\n+ \"\"\".trimIndent()\n+ val formattedCode =\n+ \"\"\"\n+ @file:[Suppress(\"ktlint:standard:bar\", \"ktlint:custom:foo\") SuppressWarnings(\"ktlint:standard:foo\")]\n+ \"\"\".trimIndent()\n+ ktlintSuppressionRuleAssertThat(code)\n+ .hasLintViolations(\n+ LintViolation(1, 25, \"Identifier to suppress ktlint rule must be fully qualified with the rule set id\"),\n+ LintViolation(1, 77, \"Identifier to suppress ktlint rule must be fully qualified with the rule set id\"),\n+ ).isFormattedAs(formattedCode)\n+ }\n+\n+ @Test\n+ fun `Given an array annotation with Suppress and SuppressWarnings annotations`() {\n+ val code =\n+ \"\"\"\n+ @[Suppress(\"ktlint:bar\", \"ktlint:custom:foo\") SuppressWarnings(\"ktlint:foo\")]\n+ val foo = \"foo\"\n+ \"\"\".trimIndent()\n+ val formattedCode =\n+ \"\"\"\n+ @[Suppress(\"ktlint:standard:bar\", \"ktlint:custom:foo\") SuppressWarnings(\"ktlint:standard:foo\")]\n+ val foo = \"foo\"\n+ \"\"\".trimIndent()\n+ ktlintSuppressionRuleAssertThat(code)\n+ .hasLintViolations(\n+ LintViolation(1, 20, \"Identifier to suppress ktlint rule must be fully qualified with the rule set id\"),\n+ LintViolation(1, 72, \"Identifier to suppress ktlint rule must be fully qualified with the rule set id\"),\n+ ).isFormattedAs(formattedCode)\n+ }\n+\n+ @Test\n+ fun `Given a Suppress annotation with a named argument with an arrayOf initialization`() {\n+ val code =\n+ \"\"\"\n+ @Suppress(names = arrayOf(\"ktlint:bar\", \"ktlint:standard:foo\", \"ktlint:custom:foo\"))\n+ val foo = \"foo\"\n+ \"\"\".trimIndent()\n+ val formattedCode =\n+ \"\"\"\n+ @Suppress(names = arrayOf(\"ktlint:standard:bar\", \"ktlint:standard:foo\", \"ktlint:custom:foo\"))\n+ val foo = \"foo\"\n+ \"\"\".trimIndent()\n+ ktlintSuppressionRuleAssertThat(code)\n+ .hasLintViolation(1, 35, \"Identifier to suppress ktlint rule must be fully qualified with the rule set id\")\n+ .isFormattedAs(formattedCode)\n+ }\n+\n+ @Test\n+ fun `Given a Suppress annotation with a named argument with an array (squared brackets) initialization`() {\n+ val code =\n+ \"\"\"\n+ @Suppress(names = [\"ktlint:bar\", \"ktlint:standard:foo\", \"ktlint:custom:foo\"])\n+ val foo = \"foo\"\n+ \"\"\".trimIndent()\n+ val formattedCode =\n+ \"\"\"\n+ @Suppress(names = [\"ktlint:standard:bar\", \"ktlint:standard:foo\", \"ktlint:custom:foo\"])\n+ val foo = \"foo\"\n+ \"\"\".trimIndent()\n+ ktlintSuppressionRuleAssertThat(code)\n+ .hasLintViolation(1, 28, \"Identifier to suppress ktlint rule must be fully qualified with the rule set id\")\n+ .isFormattedAs(formattedCode)\n+ }\n+\n+ @Test\n+ fun `Given a Suppress annotation on a declaration`() {\n+ val code =\n+ \"\"\"\n+ @Suppress(\"ktlint:bar\", \"ktlint:standard:foo\", \"ktlint:custom:foo\")\n+ val foo = \"foo\"\n+ \"\"\".trimIndent()\n+ val formattedCode =\n+ \"\"\"\n+ @Suppress(\"ktlint:standard:bar\", \"ktlint:standard:foo\", \"ktlint:custom:foo\")\n+ val foo = \"foo\"\n+ \"\"\".trimIndent()\n+ ktlintSuppressionRuleAssertThat(code)\n+ .hasLintViolation(1, 19, \"Identifier to suppress ktlint rule must be fully qualified with the rule set id\")\n+ .isFormattedAs(formattedCode)\n+ }\n+\n+ @Test\n+ fun `Given a SuppressWarnings annotation on a declaration`() {\n+ val code =\n+ \"\"\"\n+ @SuppressWarnings(\"ktlint:bar\", \"ktlint:standard:foo\", \"ktlint:custom:foo\")\n+ val foo = \"foo\"\n+ \"\"\".trimIndent()\n+ val formattedCode =\n+ \"\"\"\n+ @SuppressWarnings(\"ktlint:standard:bar\", \"ktlint:standard:foo\", \"ktlint:custom:foo\")\n+ val foo = \"foo\"\n+ \"\"\".trimIndent()\n+ ktlintSuppressionRuleAssertThat(code)\n+ .hasLintViolation(1, 27, \"Identifier to suppress ktlint rule must be fully qualified with the rule set id\")\n+ .isFormattedAs(formattedCode)\n+ }\n+ }\n+\n+ @Test\n+ fun `Given an EOL comment with a ktlint-disable directive not preceded by code leaf on same line`() {\n+ val code =\n+ \"\"\"\n+ val foo = \"foo\"\n+ // ktlint-disable\n+ val bar = \"bar\"\n+ \"\"\".trimIndent()\n+ val formattedCode =\n+ \"\"\"\n+ val foo = \"foo\"\n+ val bar = \"bar\"\n+ \"\"\".trimIndent()\n+ ktlintSuppressionRuleAssertThat(code)\n+ .hasLintViolation(2, 4, \"Directive 'ktlint-disable' in EOL comment is ignored as it is not preceded by a code element\")\n+ .isFormattedAs(formattedCode)\n+ }\n+\n+ @Nested\n+ inner class `Given an import statement` {\n+ @Test\n+ fun `Given an EOL comment with a ktlint-disable directive on an import`() {\n+ val code =\n+ \"\"\"\n+ import foo.bar\n+ import foobar.* // ktlint-disable no-wildcard-imports\n+ \"\"\".trimIndent()\n+ val formattedCode =\n+ \"\"\"\n+ @file:Suppress(\"ktlint:standard:no-wildcard-imports\")\n+\n+ import foo.bar\n+ import foobar.*\n+ \"\"\".trimIndent()\n+ ktlintSuppressionRuleAssertThat(code)\n+ .hasLintViolation(2, 20, \"Directive 'ktlint-disable' is deprecated. Replace with @Suppress annotation\")\n+ .isFormattedAs(formattedCode)\n+ }\n+\n+ @Test\n+ fun `Given an EOL comment with a ktlint-disable directive on an import and an existing @file Suppress annotation`() {\n+ val code =\n+ \"\"\"\n+ @file:Suppress(\"aaa\", \"zzz\")\n+\n+ import foo.bar\n+ import foobar.* // ktlint-disable no-wildcard-imports\n+ \"\"\".trimIndent()\n+ val formattedCode =\n+ \"\"\"\n+ @file:Suppress(\"aaa\", \"ktlint:standard:no-wildcard-imports\", \"zzz\")\n+\n+ import foo.bar\n+ import foobar.*\n+ \"\"\".trimIndent()\n+ ktlintSuppressionRuleAssertThat(code)\n+ .hasLintViolation(4, 20, \"Directive 'ktlint-disable' is deprecated. Replace with @Suppress annotation\")\n+ .isFormattedAs(formattedCode)\n+ }\n+\n+ @Test\n+ fun `Given an EOL comment with a ktlint-disable directive on an import and an existing @file Suppress annotation without parameters`() {\n+ val code =\n+ \"\"\"\n+ @file:Suppress\n+\n+ import foobar.* // ktlint-disable no-wildcard-imports\n+ \"\"\".trimIndent()\n+ val formattedCode =\n+ \"\"\"\n+ @file:Suppress(\"ktlint:standard:no-wildcard-imports\")\n+\n+ import foobar.*\n+ \"\"\".trimIndent()\n+ ktlintSuppressionRuleAssertThat(code)\n+ .hasLintViolation(3, 20, \"Directive 'ktlint-disable' is deprecated. Replace with @Suppress annotation\")\n+ .isFormattedAs(formattedCode)\n+ }\n+\n+ @Test\n+ fun `Given an EOL comment with a ktlint-disable directive on an import on a file starting with a (copyright) comment before the package statement`() {\n+ val code =\n+ \"\"\"\n+ /* Some copyright notice before package statement */\n+ package foo\n+\n+ import foo.bar\n+ import foobar.* // ktlint-disable no-wildcard-imports\n+ \"\"\".trimIndent()\n+ val formattedCode =\n+ \"\"\"\n+ /* Some copyright notice before package statement */\n+ @file:Suppress(\"ktlint:standard:no-wildcard-imports\")\n+\n+ package foo\n+\n+ import foo.bar\n+ import foobar.*\n+ \"\"\".trimIndent()\n+ ktlintSuppressionRuleAssertThat(code)\n+ .hasLintViolation(5, 20, \"Directive 'ktlint-disable' is deprecated. Replace with @Suppress annotation\")\n+ .isFormattedAs(formattedCode)\n+ }\n+\n+ @Test\n+ fun `Given an EOL comment with a ktlint-disable directive on an import and an existing @file Suppress annotation on a file starting with a (copyright) comment`() {\n+ val code =\n+ \"\"\"\n+ /* Some copyright notice before package statement */\n+ @file:Suppress(\"aaa\", \"zzz\")\n+ package foo\n+\n+ import foo.bar\n+ import foobar.* // ktlint-disable no-wildcard-imports\n+ \"\"\".trimIndent()\n+ val formattedCode =\n+ \"\"\"\n+ /* Some copyright notice before package statement */\n+ @file:Suppress(\"aaa\", \"ktlint:standard:no-wildcard-imports\", \"zzz\")\n+ package foo\n+\n+ import foo.bar\n+ import foobar.*\n+ \"\"\".trimIndent()\n+ ktlintSuppressionRuleAssertThat(code)\n+ .hasLintViolation(6, 20, \"Directive 'ktlint-disable' is deprecated. Replace with @Suppress annotation\")\n+ .isFormattedAs(formattedCode)\n+ }\n+ }\n+\n+ @Nested\n+ inner class `Given an EOL comment with a ktlint-disable directive` {\n+ @Test\n+ fun `Given a ktlint-disable directive without rule-id`() {\n+ val code =\n+ \"\"\"\n+ val foo = \"foo\" // ktlint-disable\n+ \"\"\".trimIndent()\n+ val formattedCode =\n+ \"\"\"\n+ @Suppress(\"ktlint\")\n+ val foo = \"foo\"\n+ \"\"\".trimIndent()\n+ ktlintSuppressionRuleAssertThat(code)\n+ .hasLintViolation(1, 20, \"Directive 'ktlint-disable' is deprecated. Replace with @Suppress annotation\")\n+ .isFormattedAs(formattedCode)\n+ }\n+\n+ @Test\n+ fun `Given a ktlint-disable directive with rule-id not prefixed with a rule set id`() {\n+ val code =\n+ \"\"\"\n+ val foo = \"foo\" // ktlint-disable foo\n+ \"\"\".trimIndent()\n+ val formattedCode =\n+ \"\"\"\n+ @Suppress(\"ktlint:standard:foo\")\n+ val foo = \"foo\"\n+ \"\"\".trimIndent()\n+ ktlintSuppressionRuleAssertThat(code)\n+ .hasLintViolation(1, 20, \"Directive 'ktlint-disable' is deprecated. Replace with @Suppress annotation\")\n+ .isFormattedAs(formattedCode)\n+ }\n+\n+ @Test\n+ fun `Given a ktlint-disable directive with rule-id prefixed with a rule set id`() {\n+ val code =\n+ \"\"\"\n+ val foo = \"foo\" // ktlint-disable standard:foo\n+ \"\"\".trimIndent()\n+ val formattedCode =\n+ \"\"\"\n+ @Suppress(\"ktlint:standard:foo\")\n+ val foo = \"foo\"\n+ \"\"\".trimIndent()\n+ ktlintSuppressionRuleAssertThat(code)\n+ .hasLintViolation(1, 20, \"Directive 'ktlint-disable' is deprecated. Replace with @Suppress annotation\")\n+ .isFormattedAs(formattedCode)\n+ }\n+\n+ @ParameterizedTest(name = \"Rules: {0}\")\n+ @ValueSource(\n+ strings = [\n+ // Rule ids are already sorted\n+ \"custom:foo standard:bar standard:foo\",\n+ // Redundant spaces between rule ids should not lead to suppressing all rules by adding \"ktlint\" as suppression id\n+ \"custom:foo standard:bar standard:foo\",\n+ // Duplicate rule ids are ignored\n+ \"standard:bar standard:foo standard:bar custom:foo\",\n+ // Unsorted rule ids are sorted\n+ \"standard:foo custom:foo standard:bar\",\n+ ],\n+ )\n+ fun `Given a ktlint-disable directive with multiple rule-ids`(ruleIds: String) {\n+ val code =\n+ \"\"\"\n+ val foo = \"foo\" // ktlint-disable $ruleIds\n+ \"\"\".trimIndent()\n+ val formattedCode =\n+ \"\"\"\n+ @Suppress(\"ktlint:custom:foo\", \"ktlint:standard:bar\", \"ktlint:standard:foo\")\n+ val foo = \"foo\"\n+ \"\"\".trimIndent()\n+ ktlintSuppressionRuleAssertThat(code)\n+ .hasLintViolation(1, 20, \"Directive 'ktlint-disable' is deprecated. Replace with @Suppress annotation\")\n+ .isFormattedAs(formattedCode)\n+ }\n+\n+ @Test\n+ fun `Given a ktlint-disable directive for which the target element is already annotated with @Suppress then add the ktlint suppression and sort all suppressions alphabetically`() {\n+ val code =\n+ \"\"\"\n+ @Suppress(\"zzz\", \"aaa\")\n+ val foo = \"foo\" // ktlint-disable standard:foo\n+ \"\"\".trimIndent()\n+ val formattedCode =\n+ \"\"\"\n+ @Suppress(\"aaa\", \"ktlint:standard:foo\", \"zzz\")\n+ val foo = \"foo\"\n+ \"\"\".trimIndent()\n+ ktlintSuppressionRuleAssertThat(code)\n+ .hasLintViolation(2, 20, \"Directive 'ktlint-disable' is deprecated. Replace with @Suppress annotation\")\n+ .isFormattedAs(formattedCode)\n+ }\n+\n+ @Test\n+ fun `Given a ktlint-disable directive for which the target element is already annotated with @SuppressWarnings then add the ktlint suppression and sort all suppressions alphabetically`() {\n+ val code =\n+ \"\"\"\n+ @SuppressWarnings(\"aaa\", \"zzz\")\n+ val foo = \"foo\" // ktlint-disable standard:foo\n+ \"\"\".trimIndent()\n+ val formattedCode =\n+ \"\"\"\n+ @SuppressWarnings(\"aaa\", \"ktlint:standard:foo\", \"zzz\")\n+ val foo = \"foo\"\n+ \"\"\".trimIndent()\n+ ktlintSuppressionRuleAssertThat(code)\n+ .hasLintViolation(2, 20, \"Directive 'ktlint-disable' is deprecated. Replace with @Suppress annotation\")\n+ .isFormattedAs(formattedCode)\n+ }\n+\n+ @Test\n+ fun `Given a ktlint-disable directive for which the target element is already annotated with both @Suppress and @SuppressWarnings then add the ktlint suppression to the @Suppress`() {\n+ val code =\n+ \"\"\"\n+ @Suppress(\"aaa\", \"zzz\")\n+ @SuppressWarnings(\"bbb\", \"yyy\")\n+ val foo = \"foo\" // ktlint-disable standard:foo\n+ \"\"\".trimIndent()\n+ val formattedCode =\n+ \"\"\"\n+ @Suppress(\"aaa\", \"ktlint:standard:foo\", \"zzz\")\n+ @SuppressWarnings(\"bbb\", \"yyy\")\n+ val foo = \"foo\"\n+ \"\"\".trimIndent()\n+ ktlintSuppressionRuleAssertThat(code)\n+ .hasLintViolation(3, 20, \"Directive 'ktlint-disable' is deprecated. Replace with @Suppress annotation\")\n+ .isFormattedAs(formattedCode)\n+ }\n+ }\n+\n+ // Note that the embedded kotlin compiler treats the last comment preceding a declaration or expression as integral part of the ASTNode\n+ // representing that declaration or expression. To match the working SuppressionBuilderLocator of Ktlint it should be treated as a top\n+ // level comment.\n+ // To keep test cases below concise, they only contain a ktlint-disable directive in a block comment and no declaration or expression.\n+ @Nested\n+ inner class `Given a top level block comment with a ktlint-disable directive` {\n+ @Test\n+ fun `Given a ktlint-disable directive without rule-id`() {\n+ val code =\n+ \"\"\"\n+ /* ktlint-disable */\n+ \"\"\".trimIndent()\n+ val formattedCode =\n+ \"\"\"\n+ @file:Suppress(\"ktlint\")\n+ \"\"\".trimIndent()\n+ ktlintSuppressionRuleAssertThat(code)\n+ .hasLintViolation(1, 4, \"Directive 'ktlint-disable' is deprecated. Replace with @Suppress annotation\")\n+ .isFormattedAs(formattedCode)\n+ }\n+\n+ @ParameterizedTest(name = \"Ktlint-disable: {0}\")\n+ @CsvSource(\n+ quoteCharacter = '\"',\n+ delimiter = '|',\n+ value = [\n+ \"foo | ktlint:standard:foo\",\n+ \"standard:foo | ktlint:standard:foo\",\n+ \"custom:foo | ktlint:custom:foo\",\n+ \"custom:foo standard:bar | ktlint:custom:foo,ktlint:standard:bar\",\n+ // Redundant spaces between rule ids should not lead to suppressing all rules by adding \"ktlint\" as suppression id\n+ \"custom:foo standard:bar | ktlint:custom:foo,ktlint:standard:bar\",\n+ // Duplicate rule ids are ignored\n+ \"custom:foo standard:bar custom:foo | ktlint:custom:foo,ktlint:standard:bar\",\n+ // Unsorted rule ids are sorted\n+ \"standard:bar custom:foo | ktlint:custom:foo,ktlint:standard:bar\",\n+ ],\n+ )\n+ fun `Given a top-level ktlint-disable directive`(\n+ ruleIds: String,\n+ expectedSuppressionIdString: String,\n+ ) {\n+ val code =\n+ \"\"\"\n+ /* ktlint-disable $ruleIds */\n+ \"\"\".trimIndent()\n+ val formattedCode =\n+ \"\"\"\n+ @file:Suppress(${\n+ expectedSuppressionIdString\n+ .split(',')\n+ .joinToString { \"\\\"$it\\\"\" }\n+ })\n+ \"\"\".trimIndent()\n+ ktlintSuppressionRuleAssertThat(code)\n+ .hasLintViolation(1, 4, \"Directive 'ktlint-disable' is deprecated. Replace with @Suppress annotation\")\n+ .isFormattedAs(formattedCode)\n+ }\n+\n+ @Test\n+ fun `Given a ktlint-disable directive for which the target element is already annotated with @Suppress then add the ktlint suppression and sort all suppressions alphabetically`() {\n+ val code =\n+ \"\"\"\n+ @file:Suppress(\"zzz\", \"aaa\")\n+ /* ktlint-disable standard:foo */\n+ \"\"\".trimIndent()\n+ val formattedCode =\n+ \"\"\"\n+ @file:Suppress(\"aaa\", \"ktlint:standard:foo\", \"zzz\")\n+ \"\"\".trimIndent()\n+ ktlintSuppressionRuleAssertThat(code)\n+ .hasLintViolation(2, 4, \"Directive 'ktlint-disable' is deprecated. Replace with @Suppress annotation\")\n+ .isFormattedAs(formattedCode)\n+ }\n+\n+ @Test\n+ fun `Given a ktlint-disable directive for which the target element is already annotated with @SuppressWarnings then add the ktlint suppression and sort all suppressions alphabetically`() {\n+ val code =\n+ \"\"\"\n+ @file:SuppressWarnings(\"aaa\", \"zzz\")\n+ /* ktlint-disable standard:foo */\n+ \"\"\".trimIndent()\n+ val formattedCode =\n+ \"\"\"\n+ @file:SuppressWarnings(\"aaa\", \"ktlint:standard:foo\", \"zzz\")\n+ \"\"\".trimIndent()\n+ ktlintSuppressionRuleAssertThat(code)\n+ .hasLintViolation(2, 4, \"Directive 'ktlint-disable' is deprecated. Replace with @Suppress annotation\")\n+ .isFormattedAs(formattedCode)\n+ }\n+\n+ @Test\n+ fun `Given a ktlint-disable directive for which the target element is already annotated with both @Suppress and @SuppressWarnings then add the ktlint suppression to the @Suppress`() {\n+ val code =\n+ \"\"\"\n+ @file:Suppress(\"aaa\", \"zzz\")\n+ @file:SuppressWarnings(\"bbb\", \"yyy\")\n+\n+ /* ktlint-disable standard:foo */\n+ \"\"\".trimIndent()\n+ val formattedCode =\n+ \"\"\"\n+ @file:Suppress(\"aaa\", \"ktlint:standard:foo\", \"zzz\")\n+ @file:SuppressWarnings(\"bbb\", \"yyy\")\n+ \"\"\".trimIndent()\n+ ktlintSuppressionRuleAssertThat(code)\n+ .hasLintViolation(4, 4, \"Directive 'ktlint-disable' is deprecated. Replace with @Suppress annotation\")\n+ .isFormattedAs(formattedCode)\n+ }\n+\n+ @Test\n+ fun `Given a ktlint-disable directive for which the target element is already annotated with both @SuppressWarnings and @Suppress then add the ktlint suppression to the @Suppress`() {\n+ val code =\n+ \"\"\"\n+ @file:SuppressWarnings(\"bbb\", \"yyy\")\n+ @file:Suppress(\"aaa\", \"zzz\")\n+\n+ /* ktlint-disable standard:foo */\n+ \"\"\".trimIndent()\n+ val formattedCode =\n+ \"\"\"\n+ @file:SuppressWarnings(\"bbb\", \"yyy\")\n+ @file:Suppress(\"aaa\", \"ktlint:standard:foo\", \"zzz\")\n+ \"\"\".trimIndent()\n+ ktlintSuppressionRuleAssertThat(code)\n+ .hasLintViolation(4, 4, \"Directive 'ktlint-disable' is deprecated. Replace with @Suppress annotation\")\n+ .isFormattedAs(formattedCode)\n+ }\n+ }\n+\n+ @Nested\n+ inner class `Given a pair of matching ktlint directives in block comments within the same parent node` {\n+ @Test\n+ fun `Given a ktlint-disable directive without rule-id`() {\n+ val code =\n+ \"\"\"\n+ fun foo() {\n+ /* ktlint-disable */\n+ doSomething()\n+ /* ktlint-enable */\n+ }\n+ \"\"\".trimIndent()\n+ val formattedCode =\n+ \"\"\"\n+ @Suppress(\"ktlint\")\n+ fun foo() {\n+ doSomething()\n+ }\n+ \"\"\".trimIndent()\n+ ktlintSuppressionRuleAssertThat(code)\n+ .hasLintViolations(\n+ LintViolation(2, 8, \"Directive 'ktlint-disable' is deprecated. Replace with @Suppress annotation\"),\n+ LintViolation(4, 8, \"Directive 'ktlint-enable' is obsolete after migrating to suppress annotations\"),\n+ ).isFormattedAs(formattedCode)\n+ }\n+\n+ @Test\n+ fun `Given a ktlint-disable directive with rule-id not prefixed with a rule set id`() {\n+ val code =\n+ \"\"\"\n+ fun foo() {\n+ /* ktlint-disable foo */\n+ doSomething()\n+ /* ktlint-enable foo */\n+ }\n+ \"\"\".trimIndent()\n+ val formattedCode =\n+ \"\"\"\n+ @Suppress(\"ktlint:standard:foo\")\n+ fun foo() {\n+ doSomething()\n+ }\n+ \"\"\".trimIndent()\n+ ktlintSuppressionRuleAssertThat(code)\n+ .hasLintViolations(\n+ LintViolation(2, 8, \"Directive 'ktlint-disable' is deprecated. Replace with @Suppress annotation\"),\n+ LintViolation(4, 8, \"Directive 'ktlint-enable' is obsolete after migrating to suppress annotations\"),\n+ ).isFormattedAs(formattedCode)\n+ }\n+\n+ @Test\n+ fun `Given a ktlint-disable directive with rule-id prefixed with a rule set id`() {\n+ val code =\n+ \"\"\"\n+ fun foo() {\n+ /* ktlint-disable standard:foo */\n+ doSomething()\n+ /* ktlint-enable standard:foo */\n+ }\n+ \"\"\".trimIndent()\n+ val formattedCode =\n+ \"\"\"\n+ @Suppress(\"ktlint:standard:foo\")\n+ fun foo() {\n+ doSomething()\n+ }\n+ \"\"\".trimIndent()\n+ ktlintSuppressionRuleAssertThat(code)\n+ .hasLintViolations(\n+ LintViolation(2, 8, \"Directive 'ktlint-disable' is deprecated. Replace with @Suppress annotation\"),\n+ LintViolation(4, 8, \"Directive 'ktlint-enable' is obsolete after migrating to suppress annotations\"),\n+ ).isFormattedAs(formattedCode)\n+ }\n+\n+ @ParameterizedTest(name = \"Rules: {0}\")\n+ @ValueSource(\n+ strings = [\n+ \"standard:bar standard:foo\",\n+ // Redundant spaces between rule ids should not lead to suppressing all rules by adding \"ktlint\" as suppression id\n+ \"standard:bar standard:foo\",\n+ // Duplicate rule ids are ignored\n+ \"standard:bar standard:foo standard:bar\",\n+ // Unsorted rule ids are sorted\n+ \"standard:foo standard:bar\",\n+ ],\n+ )\n+ fun `Given a ktlint-disable directive with multiple rule-ids`(ruleIds: String) {\n+ val code =\n+ \"\"\"\n+ fun foo() {\n+ /* ktlint-disable $ruleIds */\n+ doSomething()\n+ /* ktlint-enable $ruleIds */\n+ }\n+ \"\"\".trimIndent()\n+ val formattedCode =\n+ \"\"\"\n+ @Suppress(\"ktlint:standard:bar\", \"ktlint:standard:foo\")\n+ fun foo() {\n+ doSomething()\n+ }\n+ \"\"\".trimIndent()\n+ ktlintSuppressionRuleAssertThat(code)\n+ .hasLintViolations(\n+ LintViolation(2, 8, \"Directive 'ktlint-disable' is deprecated. Replace with @Suppress annotation\"),\n+ LintViolation(4, 8, \"Directive 'ktlint-enable' is obsolete after migrating to suppress annotations\"),\n+ ).isFormattedAs(formattedCode)\n+ }\n+\n+ @Test\n+ fun `Given a ktlint-disable directive for which the target element is already annotated with @Suppress then add the ktlint suppression and sort all suppressions alphabetically`() {\n+ val code =\n+ \"\"\"\n+ @Suppress(\"zzz\", \"aaa\")\n+ fun foo() {\n+ /* ktlint-disable standard:foo */\n+ doSomething()\n+ /* ktlint-enable standard:foo */\n+ }\n+ \"\"\".trimIndent()\n+ val formattedCode =\n+ \"\"\"\n+ @Suppress(\"aaa\", \"ktlint:standard:foo\", \"zzz\")\n+ fun foo() {\n+ doSomething()\n+ }\n+ \"\"\".trimIndent()\n+ ktlintSuppressionRuleAssertThat(code)\n+ .hasLintViolations(\n+ LintViolation(3, 8, \"Directive 'ktlint-disable' is deprecated. Replace with @Suppress annotation\"),\n+ LintViolation(5, 8, \"Directive 'ktlint-enable' is obsolete after migrating to suppress annotations\"),\n+ ).isFormattedAs(formattedCode)\n+ }\n+\n+ @Test\n+ fun `Given a ktlint-disable directive for which the target element is already annotated with @SuppressWarnings then add the ktlint suppression and sort all suppressions alphabetically`() {\n+ val code =\n+ \"\"\"\n+ @SuppressWarnings(\"aaa\", \"zzz\")\n+ fun foo() {\n+ /* ktlint-disable standard:foo */\n+ doSomething()\n+ /* ktlint-enable standard:foo */\n+ }\n+ \"\"\".trimIndent()\n+ val formattedCode =\n+ \"\"\"\n+ @SuppressWarnings(\"aaa\", \"ktlint:standard:foo\", \"zzz\")\n+ fun foo() {\n+ doSomething()\n+ }\n+ \"\"\".trimIndent()\n+ ktlintSuppressionRuleAssertThat(code)\n+ .hasLintViolations(\n+ LintViolation(3, 8, \"Directive 'ktlint-disable' is deprecated. Replace with @Suppress annotation\"),\n+ LintViolation(5, 8, \"Directive 'ktlint-enable' is obsolete after migrating to suppress annotations\"),\n+ ).isFormattedAs(formattedCode)\n+ }\n+\n+ @Test\n+ fun `Given a ktlint-disable directive for which the target element is already annotated with both @Suppress and @SuppressWarnings then add the ktlint suppression to the @Suppress`() {\n+ val code =\n+ \"\"\"\n+ @Suppress(\"aaa\", \"zzz\")\n+ @SuppressWarnings(\"bbb\", \"yyy\")\n+ fun foo() {\n+ /* ktlint-disable standard:foo */\n+ doSomething()\n+ /* ktlint-enable standard:foo */\n+ }\n+ \"\"\".trimIndent()\n+ val formattedCode =\n+ \"\"\"\n+ @Suppress(\"aaa\", \"ktlint:standard:foo\", \"zzz\")\n+ @SuppressWarnings(\"bbb\", \"yyy\")\n+ fun foo() {\n+ doSomething()\n+ }\n+ \"\"\".trimIndent()\n+ ktlintSuppressionRuleAssertThat(code)\n+ .hasLintViolations(\n+ LintViolation(4, 8, \"Directive 'ktlint-disable' is deprecated. Replace with @Suppress annotation\"),\n+ LintViolation(6, 8, \"Directive 'ktlint-enable' is obsolete after migrating to suppress annotations\"),\n+ ).isFormattedAs(formattedCode)\n+ }\n+ }\n+\n+ @Nested\n+ inner class `Given a ktlint-enable directive` {\n+ @Test\n+ fun `Given a ktlint-enable directive matching with a ktlint-disable directive`() {\n+ val code =\n+ \"\"\"\n+ fun foo() {\n+ /* ktlint-disable standard:foo */\n+ doSomething()\n+ /* ktlint-enable standard:foo */\n+ }\n+ \"\"\".trimIndent()\n+ val formattedCode =\n+ \"\"\"\n+ @Suppress(\"ktlint:standard:foo\")\n+ fun foo() {\n+ doSomething()\n+ }\n+ \"\"\".trimIndent()\n+ ktlintSuppressionRuleAssertThat(code)\n+ .hasLintViolations(\n+ LintViolation(2, 8, \"Directive 'ktlint-disable' is deprecated. Replace with @Suppress annotation\"),\n+ LintViolation(4, 8, \"Directive 'ktlint-enable' is obsolete after migrating to suppress annotations\"),\n+ ).isFormattedAs(formattedCode)\n+ }\n+\n+ @Test\n+ fun `Given a ktlint-enable directive not matching with a ktlint-disable directive`() {\n+ val code =\n+ \"\"\"\n+ fun foo() {\n+ doSomething()\n+ /* ktlint-enable standard:foo */\n+ }\n+ \"\"\".trimIndent()\n+ val formattedCode =\n+ \"\"\"\n+ fun foo() {\n+ doSomething()\n+ }\n+ \"\"\".trimIndent()\n+ ktlintSuppressionRuleAssertThat(code)\n+ .hasLintViolation(3, 8, \"Directive 'ktlint-enable' is obsolete after migrating to suppress annotations\")\n+ .isFormattedAs(formattedCode)\n+ }\n+ }\n+\n+ @Test\n+ fun `Given a ktlint-disable directive for a specific rule on a declaration which already has suppression annotation for all ktlint rules`() {\n+ val code =\n+ \"\"\"\n+ @Suppress(\"ktlint\")\n+ fun foo() {\n+ bar() // ktlint-disable standard:bar\n+\n+ /* ktlint-disable standard:foo */\n+ /* ktlint-disable custom:foo */\n+ bar()\n+ /* ktlint-enable custom:foo */\n+ /* ktlint-enable standard:foo */\n+ }\n+ \"\"\".trimIndent()\n+ val formattedCode =\n+ \"\"\"\n+ @Suppress(\"ktlint\")\n+ fun foo() {\n+ bar()\n+\n+ bar()\n+ }\n+ \"\"\".trimIndent()\n+ ktlintSuppressionRuleAssertThat(code)\n+ .hasLintViolations(\n+ LintViolation(3, 14, \"Directive 'ktlint-disable' is deprecated. Replace with @Suppress annotation\"),\n+ LintViolation(5, 8, \"Directive 'ktlint-disable' is deprecated. Replace with @Suppress annotation\"),\n+ LintViolation(6, 8, \"Directive 'ktlint-disable' is deprecated. Replace with @Suppress annotation\"),\n+ LintViolation(8, 8, \"Directive 'ktlint-enable' is obsolete after migrating to suppress annotations\"),\n+ LintViolation(9, 8, \"Directive 'ktlint-enable' is obsolete after migrating to suppress annotations\"),\n+ ).isFormattedAs(formattedCode)\n+ }\n+\n+ @KtlintDocumentationTest\n+ fun `Documentation example`() {\n+ val code =\n+ \"\"\"\n+ /* ktlint-disable standard:no-wildcard-imports */\n+\n+ class FooBar {\n+ val foo = \"some longggggggggggggggggggg text\" // ktlint-disable standard:max-line-length\n+\n+ fun bar() =\n+ listOf(\n+ /* ktlint-disable standard:no-multi-spaces */\n+ \"1 One\",\n+ \"10 Ten\",\n+ \"100 Hundred\",\n+ /* ktlint-enable standard:no-multi-spaces */\n+ )\n+ }\n+ \"\"\".trimIndent()\n+ val formattedCode =\n+ \"\"\"\n+ @file:Suppress(\"ktlint:standard:no-wildcard-imports\")\n+\n+ class FooBar {\n+ @Suppress(\"ktlint:standard:max-line-length\")\n+ val foo = \"some longggggggggggggggggggg text\"\n+\n+ fun bar() =\n+ @Suppress(\"ktlint:standard:no-multi-spaces\")\n+ listOf(\n+ \"1 One\",\n+ \"10 Ten\",\n+ \"100 Hundred\",\n+ )\n+ }\n+ \"\"\".trimIndent()\n+ ktlintSuppressionRuleAssertThat(code)\n+ .addAdditionalRuleProvider { ArgumentListWrappingRule() }\n+ .hasLintViolations(\n+ LintViolation(1, 4, \"Directive 'ktlint-disable' is deprecated. Replace with @Suppress annotation\"),\n+ LintViolation(4, 54, \"Directive 'ktlint-disable' is deprecated. Replace with @Suppress annotation\"),\n+ LintViolation(8, 16, \"Directive 'ktlint-disable' is deprecated. Replace with @Suppress annotation\"),\n+ LintViolation(12, 16, \"Directive 'ktlint-enable' is obsolete after migrating to suppress annotations\"),\n+ ).isFormattedAs(formattedCode)\n+ }\n+\n+ @ParameterizedTest(name = \"Suppression type: {0}\")\n+ @ValueSource(\n+ strings = [\n+ \"Suppress\",\n+ \"SuppressWarnings\",\n+ ],\n+ )\n+ fun `Given multiple ktlint-disable directives which have to merged into an existing @file Suppress annotation`(annotationName: String) {\n+ val code =\n+ \"\"\"\n+ @file:$annotationName(\"ktlint:standard:bar\")\n+\n+ import bar // ktlint-disable standard:no-wildcard-imports\n+\n+ /* ktlint-disable standard:foo */\n+\n+ val someFoo = foo.TEST\n+ val someBar = bar.TEST\n+\n+ /* ktlint-disable custom:foo */\n+ \"\"\".trimIndent()\n+ val formattedCode =\n+ \"\"\"\n+ @file:$annotationName(\"ktlint:custom:foo\", \"ktlint:standard:bar\", \"ktlint:standard:foo\", \"ktlint:standard:no-wildcard-imports\")\n+\n+ import bar\n+\n+ val someFoo = foo.TEST\n+ val someBar = bar.TEST\n+ \"\"\".trimIndent()\n+ ktlintSuppressionRuleAssertThat(code)\n+ .hasLintViolations(\n+ LintViolation(3, 15, \"Directive 'ktlint-disable' is deprecated. Replace with @Suppress annotation\"),\n+ LintViolation(5, 4, \"Directive 'ktlint-disable' is deprecated. Replace with @Suppress annotation\"),\n+ LintViolation(10, 4, \"Directive 'ktlint-disable' is deprecated. Replace with @Suppress annotation\"),\n+ ).isFormattedAs(formattedCode)\n+ }\n+\n+ @Test\n+ fun `Given a block comment containing a ktlint-disable directive inside an init block`() {\n+ val code =\n+ \"\"\"\n+ class Foo() {\n+ var foo: String\n+ var bar: String\n+\n+ init {\n+ /* ktlint-disable standard:foo */\n+ foo = \"foo\"\n+ /* ktlint-enable standard:foo */\n+ }\n+\n+ init { // ktlint-disable standard:bar\n+ bar = \"bar\"\n+ }\n+ }\n+ \"\"\".trimIndent()\n+ val formattedCode =\n+ \"\"\"\n+ @Suppress(\"ktlint:standard:bar\", \"ktlint:standard:foo\")\n+ class Foo() {\n+ var foo: String\n+ var bar: String\n+\n+ init {\n+ foo = \"foo\"\n+ }\n+\n+ init {\n+ bar = \"bar\"\n+ }\n+ }\n+ \"\"\".trimIndent()\n+ ktlintSuppressionRuleAssertThat(code)\n+ .hasLintViolations(\n+ LintViolation(6, 12, \"Directive 'ktlint-disable' is deprecated. Replace with @Suppress annotation\"),\n+ LintViolation(8, 12, \"Directive 'ktlint-enable' is obsolete after migrating to suppress annotations\"),\n+ LintViolation(11, 15, \"Directive 'ktlint-disable' is deprecated. Replace with @Suppress annotation\"),\n+ ).isFormattedAs(formattedCode)\n+ }\n+\n+ @Test\n+ fun `Given a pair of matching ktlint directives in block comments as siblings in same parent node`() {\n+ val code =\n+ \"\"\"\n+ fun foobar(\n+ /* ktlint-disable standard:foo */\n+ foo: Int,\n+ bar: Int,\n+ /* ktlint-enable standard:foo */\n+ ) {}\n+ \"\"\".trimIndent()\n+ val formattedCode =\n+ \"\"\"\n+ @Suppress(\"ktlint:standard:foo\")\n+ fun foobar(\n+ foo: Int,\n+ bar: Int,\n+ ) {}\n+ \"\"\".trimIndent()\n+ ktlintSuppressionRuleAssertThat(code)\n+ .hasLintViolations(\n+ LintViolation(2, 8, \"Directive 'ktlint-disable' is deprecated. Replace with @Suppress annotation\"),\n+ LintViolation(5, 8, \"Directive 'ktlint-enable' is obsolete after migrating to suppress annotations\"),\n+ ).isFormattedAs(formattedCode)\n+ }\n+\n+ @Nested\n+ inner class `Given ktlint-disable directive in block comment not having a ktlint-enable directive in a sibling in the same parent node` {\n+ @Test\n+ fun `G1iven a ktlint-disable directive root level not related to an declaration or expression then move to @file annotation`() {\n+ val code =\n+ \"\"\"\n+ /* ktlint-disable standard:foo */\n+ \"\"\".trimIndent()\n+ val formattedCode =\n+ \"\"\"\n+ @file:Suppress(\"ktlint:standard:foo\")\n+ \"\"\".trimIndent()\n+ ktlintSuppressionRuleAssertThat(code)\n+ .hasLintViolation(1, 4, \"Directive 'ktlint-disable' is deprecated. Replace with @Suppress annotation\")\n+ .isFormattedAs(formattedCode)\n+ }\n+\n+ @Test\n+ fun `Given ktlint-disable directive in last block comment before class but not having a ktlint-enable directive`() {\n+ val code =\n+ \"\"\"\n+ /* ktlint-disable standard:foo */\n+ class Foo\n+ \"\"\".trimIndent()\n+ val formattedCode =\n+ \"\"\"\n+ @file:Suppress(\"ktlint:standard:foo\")\n+\n+ class Foo\n+ \"\"\".trimIndent()\n+ ktlintSuppressionRuleAssertThat(code)\n+ .hasLintViolation(1, 4, \"Directive 'ktlint-disable' is deprecated. Replace with @Suppress annotation\")\n+ .isFormattedAs(formattedCode)\n+ }\n+\n+ @Test\n+ fun `Given ktlint-disable directive in last block comment before property but not having a ktlint-enable directive`() {\n+ val code =\n+ \"\"\"\n+ /* ktlint-disable standard:foo */\n+ val foo = \"foo\"\n+ \"\"\".trimIndent()\n+ val formattedCode =\n+ \"\"\"\n+ @file:Suppress(\"ktlint:standard:foo\")\n+\n+ val foo = \"foo\"\n+ \"\"\".trimIndent()\n+ ktlintSuppressionRuleAssertThat(code)\n+ .hasLintViolation(1, 4, \"Directive 'ktlint-disable' is deprecated. Replace with @Suppress annotation\")\n+ .isFormattedAs(formattedCode)\n+ }\n+\n+ @Test\n+ fun `Given a pair of matching ktlint directives in block comments but not as siblings in same parent node`() {\n+ val code =\n+ \"\"\"\n+ fun foobar(\n+ /* ktlint-disable standard:foo */\n+ foo: Int,\n+ bar: Int,\n+ ) {\n+ /* ktlint-enable standard:foo */\n+ doSomething()\n+ }\n+ \"\"\".trimIndent()\n+ val formattedCode =\n+ \"\"\"\n+ fun foobar(\n+ /* ktlint-disable standard:foo */\n+ foo: Int,\n+ bar: Int,\n+ ) {\n+ doSomething()\n+ }\n+ \"\"\".trimIndent()\n+ @Suppress(\"ktlint:standard:argument-list-wrapping\", \"ktlint:standard:max-line-length\")\n+ ktlintSuppressionRuleAssertThat(code)\n+ .hasLintViolations(\n+ LintViolation(2, 8, \"Directive 'ktlint-disable' is deprecated. The matching 'ktlint-enable' directive is not found in same scope. Replace with @Suppress annotation\", false),\n+ LintViolation(6, 8, \"Directive 'ktlint-enable' is obsolete after migrating to suppress annotations\"),\n+ ).isFormattedAs(formattedCode)\n+ }\n+ }\n+\n+ @Test\n+ fun `Given ktlint-disable directive on a package statement`() {\n+ val code =\n+ \"\"\"\n+ package foo.foo_bar // ktlint-disable standard:package-name\n+ \"\"\".trimIndent()\n+ val formattedCode =\n+ \"\"\"\n+ @file:Suppress(\"ktlint:standard:package-name\")\n+\n+ package foo.foo_bar\n+ \"\"\".trimIndent()\n+ ktlintSuppressionRuleAssertThat(code)\n+ .hasLintViolation(1, 24, \"Directive 'ktlint-disable' is deprecated. Replace with @Suppress annotation\")\n+ .isFormattedAs(formattedCode)\n+ }\n+\n+ @Test\n+ fun `Given an invalid rule id then ignore it without throwing an exception`() {\n+ val code =\n+ \"\"\"\n+ @file:Suppress(\"ktlint:standard:SOME-INVALID-RULE-ID-1\")\n+\n+ @Suppress(\"ktlint:standard:SOME-INVALID-RULE-ID-2\")\n+ class Foo {\n+ /* ktlint-disable standard:SOME-INVALID-RULE-ID-3 */\n+ fun bar() {\n+ val bar = \"bar\" // ktlint-disable standard:SOME-INVALID-RULE-ID-4\n+ }\n+ /* ktlint-enable standard:SOME-INVALID-RULE-ID-3 */\n+ }\n+ \"\"\".trimIndent()\n+ ktlintSuppressionRuleAssertThat(code)\n+ .hasLintViolations(\n+ LintViolation(1, 24, \"Ktlint rule with id 'ktlint:standard:SOME-INVALID-RULE-ID-1' is unknown or not loaded\", false),\n+ LintViolation(3, 19, \"Ktlint rule with id 'ktlint:standard:SOME-INVALID-RULE-ID-2' is unknown or not loaded\", false),\n+ LintViolation(5, 8, \"Directive 'ktlint-disable' is deprecated. Replace with @Suppress annotation\"),\n+ LintViolation(5, 23, \"Ktlint rule with id 'standard:SOME-INVALID-RULE-ID-3' is unknown or not loaded\", false),\n+ LintViolation(7, 28, \"Directive 'ktlint-disable' is deprecated. Replace with @Suppress annotation\"),\n+ LintViolation(7, 43, \"Ktlint rule with id 'standard:SOME-INVALID-RULE-ID-4' is unknown or not loaded\", false),\n+ LintViolation(9, 8, \"Directive 'ktlint-enable' is obsolete after migrating to suppress annotations\"),\n+ )\n+ }\n+\n+ @Test\n+ fun `Given an unknown ktlint rule id then do not create an empty @Suppress annotation`() {\n+ val code =\n+ \"\"\"\n+ val foo = \"foo\" // ktlint-disable standard:unknown-rule-id\n+ \"\"\".trimIndent()\n+ val formattedCode =\n+ \"\"\"\n+ val foo = \"foo\"\n+ \"\"\".trimIndent()\n+ ktlintSuppressionRuleAssertThat(code)\n+ .hasLintViolations(\n+ LintViolation(1, 20, \"Directive 'ktlint-disable' is deprecated. Replace with @Suppress annotation\"),\n+ LintViolation(1, 35, \"Ktlint rule with id 'standard:unknown-rule-id' is unknown or not loaded\", false),\n+ ).isFormattedAs(formattedCode)\n+ }\n+\n+ @Test\n+ fun `Given a setter with multiple ktlint directives`() {\n+ val code =\n+ \"\"\"\n+ class Foo {\n+ var foo: Int = 1\n+ set(value) { // ktlint-disable standard:foo\n+ field = value // ktlint-disable standard:bar\n+ field = value\n+ }\n+ }\n+ \"\"\".trimIndent()\n+ val formattedCode =\n+ \"\"\"\n+ class Foo {\n+ var foo: Int = 1\n+ @Suppress(\"ktlint:standard:bar\", \"ktlint:standard:foo\")\n+ set(value) {\n+ field = value\n+ field = value\n+ }\n+ }\n+ \"\"\".trimIndent()\n+ ktlintSuppressionRuleAssertThat(code)\n+ .hasLintViolations(\n+ LintViolation(3, 25, \"Directive 'ktlint-disable' is deprecated. Replace with @Suppress annotation\"),\n+ LintViolation(4, 30, \"Directive 'ktlint-disable' is deprecated. Replace with @Suppress annotation\"),\n+ ).isFormattedAs(formattedCode)\n+ }\n+\n+ @Test\n+ fun `Given a primary constructor with multiple ktlint directives`() {\n+ val code =\n+ \"\"\"\n+ class Foo constructor(bar: Bar) {\n+ /* ktlint-disable standard:bar standard:foo */\n+\n+ /* ktlint-enable standard:bar standard:foo */\n+ }\n+ \"\"\".trimIndent()\n+ val formattedCode =\n+ \"\"\"\n+ @Suppress(\"ktlint:standard:bar\", \"ktlint:standard:foo\")\n+ class Foo constructor(bar: Bar) {\n+ }\n+ \"\"\".trimIndent()\n+ ktlintSuppressionRuleAssertThat(code)\n+ .hasLintViolations(\n+ LintViolation(2, 8, \"Directive 'ktlint-disable' is deprecated. Replace with @Suppress annotation\"),\n+ LintViolation(4, 8, \"Directive 'ktlint-enable' is obsolete after migrating to suppress annotations\"),\n+ ).isFormattedAs(formattedCode)\n+ }\n+\n+ @Test\n+ fun `Given a class parameter with multiple ktlint directives`() {\n+ val code =\n+ \"\"\"\n+ class Foo(\n+ /* ktlint-disable standard:bar standard:foo */\n+ val bar: Bar\n+ /* ktlint-enable standard:bar standard:foo */\n+ )\n+ \"\"\".trimIndent()\n+ val formattedCode =\n+ \"\"\"\n+ @Suppress(\"ktlint:standard:bar\", \"ktlint:standard:foo\")\n+ class Foo(\n+ val bar: Bar\n+ )\n+ \"\"\".trimIndent()\n+ ktlintSuppressionRuleAssertThat(code)\n+ .hasLintViolations(\n+ LintViolation(2, 8, \"Directive 'ktlint-disable' is deprecated. Replace with @Suppress annotation\"),\n+ LintViolation(4, 8, \"Directive 'ktlint-enable' is obsolete after migrating to suppress annotations\"),\n+ ).isFormattedAs(formattedCode)\n+ }\n+\n+ @Test\n+ fun `Given a ktlint-disable block directive around a single declaration then place the @Suppress on the declaration`() {\n+ val code =\n+ \"\"\"\n+ class Foobar {\n+ val bar = \"bar\"\n+\n+ /* ktlint-disable standard:bar standard:foo */\n+ fun foo() {}\n+ /* ktlint-enable standard:bar standard:foo */\n+ }\n+ \"\"\".trimIndent()\n+ val formattedCode =\n+ \"\"\"\n+ class Foobar {\n+ val bar = \"bar\"\n+\n+ @Suppress(\"ktlint:standard:bar\", \"ktlint:standard:foo\")\n+ fun foo() {}\n+ }\n+ \"\"\".trimIndent()\n+ ktlintSuppressionRuleAssertThat(code)\n+ .hasLintViolations(\n+ LintViolation(4, 8, \"Directive 'ktlint-disable' is deprecated. Replace with @Suppress annotation\"),\n+ LintViolation(6, 8, \"Directive 'ktlint-enable' is obsolete after migrating to suppress annotations\"),\n+ ).isFormattedAs(formattedCode)\n+ }\n+\n+ @Test\n+ fun `Given a ktlint-disable block directive around multiple declarations then place the @Suppress on the declaration`() {\n+ val code =\n+ \"\"\"\n+ class Foobar {\n+ /* ktlint-disable standard:bar standard:foo */\n+ val bar = \"bar\"\n+\n+ fun foo() {}\n+ /* ktlint-enable standard:bar standard:foo */\n+ }\n+ \"\"\".trimIndent()\n+ val formattedCode =\n+ \"\"\"\n+ @Suppress(\"ktlint:standard:bar\", \"ktlint:standard:foo\")\n+ class Foobar {\n+ val bar = \"bar\"\n+\n+ fun foo() {}\n+ }\n+ \"\"\".trimIndent()\n+ ktlintSuppressionRuleAssertThat(code)\n+ .hasLintViolations(\n+ LintViolation(2, 8, \"Directive 'ktlint-disable' is deprecated. Replace with @Suppress annotation\"),\n+ LintViolation(6, 8, \"Directive 'ktlint-enable' is obsolete after migrating to suppress annotations\"),\n+ ).isFormattedAs(formattedCode)\n+ }\n+\n+ @Test\n+ fun `Given a declaration with a @Suppress annotation using a named argument and a ktlint-disable directive`() {\n+ val code =\n+ \"\"\"\n+ @Suppress(names = [\"unused\"])\n+ val foo = \"foo\" // ktlint-disable standard:foo\n+ \"\"\".trimIndent()\n+ val formattedCode =\n+ \"\"\"\n+ @Suppress(\"ktlint:standard:foo\", \"unused\")\n+ val foo = \"foo\"\n+ \"\"\".trimIndent()\n+ ktlintSuppressionRuleAssertThat(code)\n+ .hasLintViolation(2, 20, \"Directive 'ktlint-disable' is deprecated. Replace with @Suppress annotation\")\n+ .isFormattedAs(formattedCode)\n+ }\n+\n+ @Test\n+ fun `Given a property delegate with a ktlint-disable directive`() {\n+ val code =\n+ \"\"\"\n+ val foo by lazy(LazyThreadSafetyMode.PUBLICATION) { // ktlint-disable standard:foo\n+ // do something\n+ }\n+ \"\"\".trimIndent()\n+ val formattedCode =\n+ \"\"\"\n+ val foo by @Suppress(\"ktlint:standard:foo\")\n+ lazy(LazyThreadSafetyMode.PUBLICATION) {\n+ // do something\n+ }\n+ \"\"\".trimIndent()\n+ ktlintSuppressionRuleAssertThat(code)\n+ .hasLintViolation(1, 56, \"Directive 'ktlint-disable' is deprecated. Replace with @Suppress annotation\")\n+ .isFormattedAs(formattedCode)\n+ }\n+\n+ @Test\n+ fun `Given a nested expression with a ktlint-disable directive`() {\n+ val code =\n+ \"\"\"\n+ val foo =\n+ setOf(\"a\")\n+ .map {\n+ bar(it) // ktlint-disable standard:foo\n+ }\n+ \"\"\".trimIndent()\n+ val formattedCode =\n+ \"\"\"\n+ val foo =\n+ @Suppress(\"ktlint:standard:foo\")\n+ setOf(\"a\")\n+ .map {\n+ bar(it)\n+ }\n+ \"\"\".trimIndent()\n+ ktlintSuppressionRuleAssertThat(code)\n+ .hasLintViolation(4, 24, \"Directive 'ktlint-disable' is deprecated. Replace with @Suppress annotation\")\n+ .isFormattedAs(formattedCode)\n+ }\n+}\n+\n+private class DummyRule(id: String) : Rule(RuleId(id), About())\ndiff --git a/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/AnnotationRuleTest.kt b/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/AnnotationRuleTest.kt\nindex f11f15aa17..d1dd929b5b 100644\n--- a/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/AnnotationRuleTest.kt\n+++ b/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/AnnotationRuleTest.kt\n@@ -253,7 +253,7 @@ class AnnotationRuleTest {\n val bar: Any\n }\n \"\"\".trimIndent()\n- @Suppress(\"ktlint:argument-list-wrapping\", \"ktlint:max-line-length\")\n+ @Suppress(\"ktlint:standard:argument-list-wrapping\", \"ktlint:standard:max-line-length\")\n annotationRuleAssertThat(code)\n .hasLintViolation(3, 9, \"Expected newline after last annotation\")\n .isFormattedAs(formattedCode)\n@@ -406,7 +406,7 @@ class AnnotationRuleTest {\n \n package foo.bar\n \"\"\".trimIndent()\n- @Suppress(\"ktlint:argument-list-wrapping\", \"ktlint:max-line-length\")\n+ @Suppress(\"ktlint:standard:argument-list-wrapping\", \"ktlint:standard:max-line-length\")\n annotationRuleAssertThat(code)\n .hasLintViolations(\n LintViolation(1, 26, \"Expected newline after last annotation\"),\n@@ -740,7 +740,7 @@ class AnnotationRuleTest {\n String\n > = FooBar()\n \"\"\".trimIndent()\n- @Suppress(\"ktlint:argument-list-wrapping\", \"ktlint:max-line-length\")\n+ @Suppress(\"ktlint:standard:argument-list-wrapping\", \"ktlint:standard:max-line-length\")\n annotationRuleAssertThat(code)\n .addAdditionalRuleProvider { IndentationRule() }\n .addAdditionalRuleProvider { WrappingRule() }\ndiff --git a/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/ArgumentListWrappingRuleTest.kt b/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/ArgumentListWrappingRuleTest.kt\nindex 3309c6fdd4..0f92d26ee0 100644\n--- a/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/ArgumentListWrappingRuleTest.kt\n+++ b/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/ArgumentListWrappingRuleTest.kt\n@@ -29,7 +29,7 @@ class ArgumentListWrappingRuleTest {\n c\n )\n \"\"\".trimIndent()\n- @Suppress(\"ktlint:argument-list-wrapping\", \"ktlint:max-line-length\")\n+ @Suppress(\"ktlint:standard:argument-list-wrapping\", \"ktlint:standard:max-line-length\")\n argumentListWrappingRuleAssertThat(code)\n .hasLintViolation(3, 8, \"Argument should be on a separate line (unless all arguments can fit a single line)\")\n .isFormattedAs(formattedCode)\ndiff --git a/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/ClassNamingRuleTest.kt b/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/ClassNamingRuleTest.kt\nindex ceef40e56f..16c79dce52 100644\n--- a/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/ClassNamingRuleTest.kt\n+++ b/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/ClassNamingRuleTest.kt\n@@ -33,7 +33,7 @@ class ClassNamingRuleTest {\n \"\"\"\n class $className\n \"\"\".trimIndent()\n- @Suppress(\"ktlint:argument-list-wrapping\", \"ktlint:max-line-length\")\n+ @Suppress(\"ktlint:standard:argument-list-wrapping\", \"ktlint:standard:max-line-length\")\n classNamingRuleAssertThat(code)\n .hasLintViolationWithoutAutoCorrect(1, 7, \"Class or object name should start with an uppercase letter and use camel case\")\n }\n@@ -46,7 +46,7 @@ class ClassNamingRuleTest {\n \"\"\"\n class `foo`\n \"\"\".trimIndent()\n- @Suppress(\"ktlint:argument-list-wrapping\", \"ktlint:max-line-length\")\n+ @Suppress(\"ktlint:standard:argument-list-wrapping\", \"ktlint:standard:max-line-length\")\n classNamingRuleAssertThat(code)\n .hasLintViolationWithoutAutoCorrect(1, 7, \"Class or object name should start with an uppercase letter and use camel case\")\n }\n@@ -73,7 +73,7 @@ class ClassNamingRuleTest {\n @ParameterizedTest(name = \"Suppression annotation: {0}\")\n @ValueSource(\n strings = [\n- \"ktlint:class-naming\",\n+ \"ktlint:standard:class-naming\",\n \"ClassName\", // IntelliJ IDEA suppression\n ],\n )\n@@ -117,7 +117,7 @@ class ClassNamingRuleTest {\n @ParameterizedTest(name = \"Suppression annotation: {0}\")\n @ValueSource(\n strings = [\n- \"ktlint:class-naming\",\n+ \"ktlint:standard:class-naming\",\n \"ClassName\", // IntelliJ IDEA suppression\n ],\n )\ndiff --git a/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/CommentWrappingRuleTest.kt b/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/CommentWrappingRuleTest.kt\nindex 4ca97cf275..b9716f2ed3 100644\n--- a/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/CommentWrappingRuleTest.kt\n+++ b/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/CommentWrappingRuleTest.kt\n@@ -93,7 +93,7 @@ class CommentWrappingRuleTest {\n * with a newline\n */\n \"\"\".trimIndent()\n- @Suppress(\"ktlint:argument-list-wrapping\", \"ktlint:max-line-length\")\n+ @Suppress(\"ktlint:standard:argument-list-wrapping\", \"ktlint:standard:max-line-length\")\n commentWrappingRuleAssertThat(code)\n .hasLintViolationWithoutAutoCorrect(1, 17, \"A block comment after any other element on the same line must be separated by a new line\")\n }\n@@ -104,7 +104,7 @@ class CommentWrappingRuleTest {\n \"\"\"\n val foo /* some comment */ = \"foo\"\n \"\"\".trimIndent()\n- @Suppress(\"ktlint:argument-list-wrapping\", \"ktlint:max-line-length\")\n+ @Suppress(\"ktlint:standard:argument-list-wrapping\", \"ktlint:standard:max-line-length\")\n commentWrappingRuleAssertThat(code)\n .hasLintViolationWithoutAutoCorrect(1, 9, \"A block comment in between other elements on the same line is disallowed\")\n }\n@@ -117,7 +117,7 @@ class CommentWrappingRuleTest {\n some comment\n */ = \"foo\"\n \"\"\".trimIndent()\n- @Suppress(\"ktlint:argument-list-wrapping\", \"ktlint:max-line-length\")\n+ @Suppress(\"ktlint:standard:argument-list-wrapping\", \"ktlint:standard:max-line-length\")\n commentWrappingRuleAssertThat(code)\n .hasLintViolationWithoutAutoCorrect(1, 9, \"A block comment starting on same line as another element and ending on another line before another element is disallowed\")\n }\ndiff --git a/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/EnumEntryNameCaseRuleTest.kt b/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/EnumEntryNameCaseRuleTest.kt\nindex cbc1ebc757..cecbc0e4f5 100644\n--- a/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/EnumEntryNameCaseRuleTest.kt\n+++ b/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/EnumEntryNameCaseRuleTest.kt\n@@ -29,7 +29,7 @@ class EnumEntryNameCaseRuleTest {\n _FOO\n }\n \"\"\".trimIndent()\n- @Suppress(\"ktlint:argument-list-wrapping\", \"ktlint:max-line-length\")\n+ @Suppress(\"ktlint:standard:argument-list-wrapping\", \"ktlint:standard:max-line-length\")\n enumEntryNameCaseRuleAssertThat(code)\n .hasLintViolationWithoutAutoCorrect(2, 5, \"Enum entry name should be uppercase underscore-separated names like \\\"ENUM_ENTRY\\\" or upper camel-case like \\\"EnumEntry\\\"\")\n }\n@@ -55,7 +55,7 @@ class EnumEntryNameCaseRuleTest {\n Foo_Bar,\n }\n \"\"\".trimIndent()\n- @Suppress(\"ktlint:argument-list-wrapping\", \"ktlint:max-line-length\")\n+ @Suppress(\"ktlint:standard:argument-list-wrapping\", \"ktlint:standard:max-line-length\")\n enumEntryNameCaseRuleAssertThat(code)\n .hasLintViolationsWithoutAutoCorrect(\n LintViolation(2, 5, \"Enum entry name should be uppercase underscore-separated names like \\\"ENUM_ENTRY\\\" or upper camel-case like \\\"EnumEntry\\\"\"),\ndiff --git a/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/FilenameRuleTest.kt b/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/FilenameRuleTest.kt\nindex 8ff0769cc8..c659bc307f 100644\n--- a/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/FilenameRuleTest.kt\n+++ b/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/FilenameRuleTest.kt\n@@ -72,7 +72,7 @@ class FilenameRuleTest {\n ],\n )\n fun `Given a file containing a single declaration of a class type then the filename should match the class name`(code: String) {\n- @Suppress(\"ktlint:argument-list-wrapping\", \"ktlint:max-line-length\")\n+ @Suppress(\"ktlint:standard:argument-list-wrapping\", \"ktlint:standard:max-line-length\")\n fileNameRuleAssertThat(code)\n .asFileWithPath(\"/some/path/$UNEXPECTED_FILE_NAME\")\n .hasLintViolationWithoutAutoCorrect(1, 1, \"File '$UNEXPECTED_FILE_NAME' contains a single class and possibly also extension functions for that class and should be named same after that class 'Foo.kt'\")\n@@ -86,7 +86,7 @@ class FilenameRuleTest {\n ],\n )\n fun `Given a file containing one top level declaration then the file should be named after the identifier`(code: String) {\n- @Suppress(\"ktlint:argument-list-wrapping\", \"ktlint:max-line-length\")\n+ @Suppress(\"ktlint:standard:argument-list-wrapping\", \"ktlint:standard:max-line-length\")\n fileNameRuleAssertThat(code)\n .asFileWithPath(UNEXPECTED_FILE_NAME)\n .hasLintViolationWithoutAutoCorrect(1, 1, \"File '$UNEXPECTED_FILE_NAME' contains a single top level declaration and should be named 'Foo.kt'\")\n@@ -167,7 +167,7 @@ class FilenameRuleTest {\n class Foo\n $otherTopLevelDeclaration\n \"\"\".trimIndent()\n- @Suppress(\"ktlint:argument-list-wrapping\", \"ktlint:max-line-length\")\n+ @Suppress(\"ktlint:standard:argument-list-wrapping\", \"ktlint:standard:max-line-length\")\n fileNameRuleAssertThat(code)\n .asFileWithPath(UNEXPECTED_FILE_NAME)\n .hasLintViolationWithoutAutoCorrect(1, 1, \"File '$UNEXPECTED_FILE_NAME' contains a single class and possibly also extension functions for that class and should be named same after that class 'Foo.kt'\")\ndiff --git a/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/FunctionNamingRuleTest.kt b/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/FunctionNamingRuleTest.kt\nindex ea113c9848..6f8116f8b9 100644\n--- a/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/FunctionNamingRuleTest.kt\n+++ b/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/FunctionNamingRuleTest.kt\n@@ -39,7 +39,7 @@ class FunctionNamingRuleTest {\n \"\"\"\n fun `Some name`() {}\n \"\"\".trimIndent()\n- @Suppress(\"ktlint:argument-list-wrapping\", \"ktlint:max-line-length\")\n+ @Suppress(\"ktlint:standard:argument-list-wrapping\", \"ktlint:standard:max-line-length\")\n functionNamingRuleAssertThat(code)\n .hasLintViolationWithoutAutoCorrect(1, 5, \"Function name should start with a lowercase letter (except factory methods) and use camel case\")\n }\n@@ -75,7 +75,7 @@ class FunctionNamingRuleTest {\n \"\"\"\n fun do_something() {}\n \"\"\".trimIndent()\n- @Suppress(\"ktlint:argument-list-wrapping\", \"ktlint:max-line-length\")\n+ @Suppress(\"ktlint:standard:argument-list-wrapping\", \"ktlint:standard:max-line-length\")\n functionNamingRuleAssertThat(code)\n .hasLintViolationWithoutAutoCorrect(1, 5, \"Function name should start with a lowercase letter (except factory methods) and use camel case\")\n }\n@@ -117,7 +117,7 @@ class FunctionNamingRuleTest {\n \"\"\"\n fun $functionName() = \"foo\"\n \"\"\".trimIndent()\n- @Suppress(\"ktlint:argument-list-wrapping\", \"ktlint:max-line-length\")\n+ @Suppress(\"ktlint:standard:argument-list-wrapping\", \"ktlint:standard:max-line-length\")\n functionNamingRuleAssertThat(code)\n .hasLintViolationWithoutAutoCorrect(1, 5, \"Function name should start with a lowercase letter (except factory methods) and use camel case\")\n }\n@@ -125,7 +125,7 @@ class FunctionNamingRuleTest {\n @ParameterizedTest(name = \"Suppression annotation: {0}\")\n @ValueSource(\n strings = [\n- \"ktlint:function-naming\",\n+ \"ktlint:standard:function-naming\",\n \"FunctionName\", // IntelliJ IDEA suppression\n ],\n )\ndiff --git a/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/FunctionSignatureRuleTest.kt b/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/FunctionSignatureRuleTest.kt\nindex b3eebad07e..138b8cd989 100644\n--- a/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/FunctionSignatureRuleTest.kt\n+++ b/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/FunctionSignatureRuleTest.kt\n@@ -516,6 +516,7 @@ class FunctionSignatureRuleTest {\n inner class CleanUpByRelatedRules {\n @Test\n fun `Given a nullable type with a space before the quest then remove this space`() {\n+ @Suppress(\"ktlint:standard:string-template\")\n val code =\n \"\"\"\n fun String$UNEXPECTED_SPACES?.f1() = \"some-result\"\n@@ -525,7 +526,7 @@ class FunctionSignatureRuleTest {\n fun f5(): String$UNEXPECTED_SPACES? = \"some-result\"\n fun f6(): List = listOf(\"some-result\", null)\n fun f7(): List$UNEXPECTED_SPACES? = null\n- \"\"\".trimIndent() // ktlint-disable string-template\n+ \"\"\".trimIndent()\n val formattedCode =\n \"\"\"\n fun String?.f1() = \"some-result\"\n@@ -608,7 +609,7 @@ class FunctionSignatureRuleTest {\n fun f28(block: (T) -> String) = \"some-result\"\n fun f29(block: (T) -> String) = \"some-result\"\n \"\"\".trimIndent()\n- @Suppress(\"ktlint:argument-list-wrapping\", \"ktlint:max-line-length\")\n+ @Suppress(\"ktlint:standard:argument-list-wrapping\", \"ktlint:standard:max-line-length\")\n functionSignatureWrappingRuleAssertThat(code)\n .addAdditionalRuleProviders(\n { NoMultipleSpacesRule() },\ndiff --git a/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/IfElseBracingRuleTest.kt b/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/IfElseBracingRuleTest.kt\nindex 20606c4fb2..b3fe8f0069 100644\n--- a/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/IfElseBracingRuleTest.kt\n+++ b/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/IfElseBracingRuleTest.kt\n@@ -62,7 +62,7 @@ class IfElseBracingRuleTest {\n }\n }\n \"\"\".trimIndent()\n- @Suppress(\"ktlint:argument-list-wrapping\", \"ktlint:max-line-length\")\n+ @Suppress(\"ktlint:standard:argument-list-wrapping\", \"ktlint:standard:max-line-length\")\n multiLineIfElseRuleAssertThat(code)\n .withEditorConfigOverride(CODE_STYLE_PROPERTY to codeStyle)\n .withEditorConfigOverride(IF_ELSE_BRACING_RULE_ID.createRuleExecutionEditorConfigProperty() to RuleExecution.enabled)\n@@ -138,7 +138,7 @@ class IfElseBracingRuleTest {\n }\n }\n \"\"\".trimIndent()\n- @Suppress(\"ktlint:argument-list-wrapping\", \"ktlint:max-line-length\")\n+ @Suppress(\"ktlint:standard:argument-list-wrapping\", \"ktlint:standard:max-line-length\")\n multiLineIfElseRuleAssertThat(code)\n .withEditorConfigOverride(CODE_STYLE_PROPERTY to ktlint_official)\n .hasLintViolation(4, 12, \"All branches of the if statement should be wrapped between braces if at least one branch is wrapped between braces\")\n@@ -237,7 +237,7 @@ class IfElseBracingRuleTest {\n doSomethingElse2()\n }\n \"\"\".trimIndent()\n- @Suppress(\"ktlint:argument-list-wrapping\", \"ktlint:max-line-length\")\n+ @Suppress(\"ktlint:standard:argument-list-wrapping\", \"ktlint:standard:max-line-length\")\n multiLineIfElseRuleAssertThat(code)\n .withEditorConfigOverride(CODE_STYLE_PROPERTY to ktlint_official)\n .hasLintViolations(\n@@ -259,7 +259,7 @@ class IfElseBracingRuleTest {\n doSomethingElse2()\n }\n \"\"\".trimIndent()\n- @Suppress(\"ktlint:argument-list-wrapping\", \"ktlint:max-line-length\")\n+ @Suppress(\"ktlint:standard:argument-list-wrapping\", \"ktlint:standard:max-line-length\")\n multiLineIfElseRuleAssertThat(code)\n .withEditorConfigOverride(CODE_STYLE_PROPERTY to ktlint_official)\n .hasLintViolations(\n@@ -282,7 +282,7 @@ class IfElseBracingRuleTest {\n }\n }\n \"\"\".trimIndent()\n- @Suppress(\"ktlint:argument-list-wrapping\", \"ktlint:max-line-length\")\n+ @Suppress(\"ktlint:standard:argument-list-wrapping\", \"ktlint:standard:max-line-length\")\n multiLineIfElseRuleAssertThat(code)\n .withEditorConfigOverride(CODE_STYLE_PROPERTY to ktlint_official)\n .hasLintViolations(\n@@ -304,7 +304,7 @@ class IfElseBracingRuleTest {\n doSomethingElse2()\n }\n \"\"\".trimIndent()\n- @Suppress(\"ktlint:argument-list-wrapping\", \"ktlint:max-line-length\")\n+ @Suppress(\"ktlint:standard:argument-list-wrapping\", \"ktlint:standard:max-line-length\")\n multiLineIfElseRuleAssertThat(code)\n .withEditorConfigOverride(CODE_STYLE_PROPERTY to ktlint_official)\n .hasLintViolation(7, 9, \"All branches of the if statement should be wrapped between braces if at least one branch is wrapped between braces\")\n@@ -325,7 +325,7 @@ class IfElseBracingRuleTest {\n }\n }\n \"\"\".trimIndent()\n- @Suppress(\"ktlint:argument-list-wrapping\", \"ktlint:max-line-length\")\n+ @Suppress(\"ktlint:standard:argument-list-wrapping\", \"ktlint:standard:max-line-length\")\n multiLineIfElseRuleAssertThat(code)\n .withEditorConfigOverride(CODE_STYLE_PROPERTY to ktlint_official)\n .hasLintViolation(5, 9, \"All branches of the if statement should be wrapped between braces if at least one branch is wrapped between braces\")\n@@ -346,7 +346,7 @@ class IfElseBracingRuleTest {\n }\n }\n \"\"\".trimIndent()\n- @Suppress(\"ktlint:argument-list-wrapping\", \"ktlint:max-line-length\")\n+ @Suppress(\"ktlint:standard:argument-list-wrapping\", \"ktlint:standard:max-line-length\")\n multiLineIfElseRuleAssertThat(code)\n .withEditorConfigOverride(CODE_STYLE_PROPERTY to ktlint_official)\n .hasLintViolation(3, 9, \"All branches of the if statement should be wrapped between braces if at least one branch is wrapped between braces\")\ndiff --git a/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/IfElseWrappingRuleTest.kt b/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/IfElseWrappingRuleTest.kt\nindex b1b46d65f9..ba4dde057b 100644\n--- a/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/IfElseWrappingRuleTest.kt\n+++ b/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/IfElseWrappingRuleTest.kt\n@@ -190,7 +190,7 @@ class IfElseWrappingRuleTest {\n if (true) { if (false) foo() else bar() }\n }\n \"\"\".trimIndent()\n- @Suppress(\"ktlint:argument-list-wrapping\", \"ktlint:max-line-length\")\n+ @Suppress(\"ktlint:standard:argument-list-wrapping\", \"ktlint:standard:max-line-length\")\n ifElseWrappingRuleAssertThat(code)\n .hasLintViolationWithoutAutoCorrect(2, 15, \"A single line if-statement should be kept simple. The 'THEN' may not be wrapped in a block.\")\n }\n@@ -203,7 +203,7 @@ class IfElseWrappingRuleTest {\n if (true) bar() else { if (false) foo() else bar() }\n }\n \"\"\".trimIndent()\n- @Suppress(\"ktlint:argument-list-wrapping\", \"ktlint:max-line-length\")\n+ @Suppress(\"ktlint:standard:argument-list-wrapping\", \"ktlint:standard:max-line-length\")\n ifElseWrappingRuleAssertThat(code)\n .hasLintViolationWithoutAutoCorrect(2, 26, \"A single line if-statement should be kept simple. The 'ELSE' may not be wrapped in a block.\")\n }\n@@ -217,7 +217,7 @@ class IfElseWrappingRuleTest {\n } else {\n }\n \"\"\".trimIndent()\n- @Suppress(\"ktlint:argument-list-wrapping\", \"ktlint:max-line-length\")\n+ @Suppress(\"ktlint:standard:argument-list-wrapping\", \"ktlint:standard:max-line-length\")\n ifElseWrappingRuleAssertThat(code).hasNoLintViolations()\n }\n \n@@ -235,7 +235,7 @@ class IfElseWrappingRuleTest {\n )\n }\n \"\"\".trimIndent()\n- @Suppress(\"ktlint:argument-list-wrapping\", \"ktlint:max-line-length\")\n+ @Suppress(\"ktlint:standard:argument-list-wrapping\", \"ktlint:standard:max-line-length\")\n ifElseWrappingRuleAssertThat(code).hasNoLintViolations()\n }\n }\ndiff --git a/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/IndentationRuleTest.kt b/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/IndentationRuleTest.kt\nindex 5e816c0b2f..e7bed23575 100644\n--- a/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/IndentationRuleTest.kt\n+++ b/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/IndentationRuleTest.kt\n@@ -3204,7 +3204,7 @@ internal class IndentationRuleTest {\n ${TAB}line2\n $MULTILINE_STRING_QUOTE.trimIndent()\n \"\"\".trimIndent()\n- @Suppress(\"ktlint:argument-list-wrapping\", \"ktlint:max-line-length\")\n+ @Suppress(\"ktlint:standard:argument-list-wrapping\", \"ktlint:standard:max-line-length\")\n indentationRuleAssertThat(code)\n .hasLintViolationWithoutAutoCorrect(1, 11, \"Indentation of multiline string should not contain both tab(s) and space(s)\")\n }\n@@ -4238,17 +4238,16 @@ internal class IndentationRuleTest {\n @Nested\n inner class `Issue 631 - Given some suppression directive in the middle of a file` {\n @Test\n- fun `Issue 631 - Given some code for which indentation is disabled with ktlint-disable-enable-block then do not fix indentation of that block only`() {\n+ fun `Issue 631 - Given some code for which indentation is disabled with ktlint-suppression then do not fix indentation of that block only`() {\n val code =\n \"\"\"\n val fooWithIndentationFixing1: String =\n \"foo\" +\n \"bar\"\n- // ktlint-disable indent\n+ @Suppress(\"ktlint:standard:indent\")\n val fooWithIndentationFixingSuppressed: String =\n \"foo\" +\n \"bar\"\n- // ktlint-enable indent\n val fooWithIndentationFixing2: String =\n \"foo\" +\n \"bar\"\n@@ -4263,7 +4262,7 @@ internal class IndentationRuleTest {\n val fooWithIndentationFixing1: String =\n \"foo\" +\n \"bar\"\n- @Suppress(\"ktlint:indent\")\n+ @Suppress(\"ktlint:standard:indent\")\n val fooWithIndentationFixingSuppressed: String =\n \"foo\" +\n \"bar\"\n@@ -4672,13 +4671,13 @@ internal class IndentationRuleTest {\n }\n \n @Test\n- fun `Issue 1644 - Given multiple nested brackets and some of them have ktlint-disable`() {\n+ fun `Issue 1644 - Given multiple nested brackets and some of them have EOL comments`() {\n val code =\n \"\"\"\n fun fooBar() {\n fun foo() {\n // some code\n- } // ktlint-disable indent\n+ } // some comment\n \n fun bar() {\n // some code\ndiff --git a/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/KdocWrappingRuleTest.kt b/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/KdocWrappingRuleTest.kt\nindex f6a6080b4c..9f79e596b9 100644\n--- a/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/KdocWrappingRuleTest.kt\n+++ b/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/KdocWrappingRuleTest.kt\n@@ -64,7 +64,7 @@ class KdocWrappingRuleTest {\n * with a newline\n */\n \"\"\".trimIndent()\n- @Suppress(\"ktlint:argument-list-wrapping\", \"ktlint:max-line-length\")\n+ @Suppress(\"ktlint:standard:argument-list-wrapping\", \"ktlint:standard:max-line-length\")\n kdocWrappingRuleAssertThat(code)\n .hasLintViolationWithoutAutoCorrect(1, 17, \"A KDoc comment after any other element on the same line must be separated by a new line\")\n }\n@@ -87,7 +87,7 @@ class KdocWrappingRuleTest {\n some KDoc comment\n */ = \"foo\"\n \"\"\".trimIndent()\n- @Suppress(\"ktlint:argument-list-wrapping\", \"ktlint:max-line-length\")\n+ @Suppress(\"ktlint:standard:argument-list-wrapping\", \"ktlint:standard:max-line-length\")\n kdocWrappingRuleAssertThat(code)\n .hasLintViolationWithoutAutoCorrect(1, 9, \"A KDoc comment starting on same line as another element and ending on another line before another element is disallowed\")\n }\ndiff --git a/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/MaxLineLengthRuleTest.kt b/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/MaxLineLengthRuleTest.kt\nindex 470cb74703..5d51ebb8fd 100644\n--- a/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/MaxLineLengthRuleTest.kt\n+++ b/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/MaxLineLengthRuleTest.kt\n@@ -105,37 +105,23 @@ class MaxLineLengthRuleTest {\n \n @Nested\n inner class `Given some error suppression` {\n- @Test\n- fun `Given some code followed by a ktlint-disable directive which causes the line length to be exceeded then do not return a lint error for that line`() {\n- val code =\n- \"\"\"\n- // $MAX_LINE_LENGTH_MARKER $EOL_CHAR\n- val bar = \"bar\" // ktlint-disable some-rule-id\n- \"\"\".trimIndent()\n- maxLineLengthRuleAssertThat(code)\n- .setMaxLineLength()\n- .hasNoLintViolations()\n- }\n-\n @Test\n fun `Given code that is wrapped into a ktlint-disable block then do no return lint errors for lines in this block`() {\n val code =\n \"\"\"\n- // $MAX_LINE_LENGTH_MARKER $EOL_CHAR\n+ // $MAX_LINE_LENGTH_MARKER $EOL_CHAR\n fun foo() {\n- println(\"teeeeeeeeeeeeeeeeeeeext\")\n- /* ktlint-disable max-line-length */\n- println(\"teeeeeeeeeeeeeeeeeeeext\")\n- println(\"teeeeeeeeeeeeeeeeeeeext\")\n- /* ktlint-enable max-line-length */\n- println(\"teeeeeeeeeeeeeeeeeeeext\")\n+ println(\"teeeeeeeeeeeeeeeeeeeeeeeeeeeeeeext\")\n+ @Suppress(\"ktlint:standard:max-line-length\")\n+ println(\"teeeeeeeeeeeeeeeeeeeeeeeeeeeeeeext\")\n+ println(\"teeeeeeeeeeeeeeeeeeeeeeeeeeeeeeext\")\n }\n \"\"\".trimIndent()\n maxLineLengthRuleAssertThat(code)\n .setMaxLineLength()\n .hasLintViolationsWithoutAutoCorrect(\n- LintViolation(3, 1, \"Exceeded max line length (37)\"),\n- LintViolation(8, 1, \"Exceeded max line length (37)\"),\n+ LintViolation(3, 1, \"Exceeded max line length (48)\"),\n+ LintViolation(6, 1, \"Exceeded max line length (48)\"),\n )\n }\n }\ndiff --git a/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/NoConsecutiveCommentsRuleTest.kt b/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/NoConsecutiveCommentsRuleTest.kt\nindex 6574988f3a..aeeb62142f 100644\n--- a/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/NoConsecutiveCommentsRuleTest.kt\n+++ b/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/NoConsecutiveCommentsRuleTest.kt\n@@ -52,7 +52,7 @@ class NoConsecutiveCommentsRuleTest {\n /** KDoc 1 */\n /* Block comment 2 */\n \"\"\".trimIndent()\n- @Suppress(\"ktlint:argument-list-wrapping\", \"ktlint:max-line-length\")\n+ @Suppress(\"ktlint:standard:argument-list-wrapping\", \"ktlint:standard:max-line-length\")\n noConsecutiveBlankLinesRuleAssertThat(code)\n .withEditorConfigOverride(CODE_STYLE_PROPERTY to codeStyle)\n .withEditorConfigOverride(NO_CONSECUTIVE_COMMENTS_RULE_ID.createRuleExecutionEditorConfigProperty() to RuleExecution.enabled)\n@@ -118,7 +118,7 @@ class NoConsecutiveCommentsRuleTest {\n /** KDoc */\n /* Block comment */\n \"\"\".trimIndent()\n- @Suppress(\"ktlint:argument-list-wrapping\", \"ktlint:max-line-length\")\n+ @Suppress(\"ktlint:standard:argument-list-wrapping\", \"ktlint:standard:max-line-length\")\n noConsecutiveBlankLinesRuleAssertThat(code)\n .withEditorConfigOverride(CODE_STYLE_PROPERTY to ktlint_official)\n .hasLintViolationWithoutAutoCorrect(2, 1, \"a block comment may not be preceded by a KDoc. Reversed order is allowed though when separated by a newline.\")\n@@ -159,7 +159,7 @@ class NoConsecutiveCommentsRuleTest {\n /** KDoc */\n // EOL comment\n \"\"\".trimIndent()\n- @Suppress(\"ktlint:argument-list-wrapping\", \"ktlint:max-line-length\")\n+ @Suppress(\"ktlint:standard:argument-list-wrapping\", \"ktlint:standard:max-line-length\")\n noConsecutiveBlankLinesRuleAssertThat(code)\n .withEditorConfigOverride(CODE_STYLE_PROPERTY to ktlint_official)\n .hasLintViolationWithoutAutoCorrect(2, 1, \"an EOL comment may not be preceded by a KDoc. Reversed order is allowed though when separated by a newline.\")\n@@ -200,7 +200,7 @@ class NoConsecutiveCommentsRuleTest {\n // EOL comment\n /* Block comment */\n \"\"\".trimIndent()\n- @Suppress(\"ktlint:argument-list-wrapping\", \"ktlint:max-line-length\")\n+ @Suppress(\"ktlint:standard:argument-list-wrapping\", \"ktlint:standard:max-line-length\")\n noConsecutiveBlankLinesRuleAssertThat(code)\n .withEditorConfigOverride(CODE_STYLE_PROPERTY to ktlint_official)\n .hasLintViolationWithoutAutoCorrect(2, 1, \"a block comment may not be preceded by an EOL comment unless separated by a blank line\")\n@@ -226,7 +226,7 @@ class NoConsecutiveCommentsRuleTest {\n /* Block comment */\n // EOL comment\n \"\"\".trimIndent()\n- @Suppress(\"ktlint:argument-list-wrapping\", \"ktlint:max-line-length\")\n+ @Suppress(\"ktlint:standard:argument-list-wrapping\", \"ktlint:standard:max-line-length\")\n noConsecutiveBlankLinesRuleAssertThat(code)\n .withEditorConfigOverride(CODE_STYLE_PROPERTY to ktlint_official)\n .hasLintViolationWithoutAutoCorrect(2, 1, \"an EOL comment may not be preceded by a block comment unless separated by a blank line\")\ndiff --git a/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/NoSingleLineBlockCommentRuleTest.kt b/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/NoSingleLineBlockCommentRuleTest.kt\nindex 68eefbd98b..ec88d2c7c6 100644\n--- a/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/NoSingleLineBlockCommentRuleTest.kt\n+++ b/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/NoSingleLineBlockCommentRuleTest.kt\n@@ -91,7 +91,7 @@ class NoSingleLineBlockCommentRuleTest {\n \"\"\"\n val foo = \"foo\" // Some comment\n \"\"\".trimIndent()\n- @Suppress(\"ktlint:argument-list-wrapping\", \"ktlint:max-line-length\")\n+ @Suppress(\"ktlint:standard:argument-list-wrapping\", \"ktlint:standard:max-line-length\")\n noSingleLineBlockCommentRuleAssertThat(code)\n .hasLintViolation(1, 16, \"Replace the block comment with an EOL comment\")\n .isFormattedAs(formattedCode)\n@@ -107,7 +107,7 @@ class NoSingleLineBlockCommentRuleTest {\n \"\"\"\n fun foo() = \"foo\" // Some comment\n \"\"\".trimIndent()\n- @Suppress(\"ktlint:argument-list-wrapping\", \"ktlint:max-line-length\")\n+ @Suppress(\"ktlint:standard:argument-list-wrapping\", \"ktlint:standard:max-line-length\")\n noSingleLineBlockCommentRuleAssertThat(code)\n .hasLintViolation(1, 19, \"Replace the block comment with an EOL comment\")\n .isFormattedAs(formattedCode)\n@@ -163,17 +163,4 @@ class NoSingleLineBlockCommentRuleTest {\n .withEditorConfigOverride(CODE_STYLE_PROPERTY to CodeStyleValue.ktlint_official)\n .hasNoLintViolations()\n }\n-\n- @Test\n- fun `Given single line block comments to disable or enable ktlint then do not reformat`() {\n- val code =\n- \"\"\"\n- /* ktlint-disable foo-rule-id bar-rule-id */\n- val foo = \"foo\"\n- /* ktlint-enable foo-rule-id bar-rule-id */\n- \"\"\".trimIndent()\n- noSingleLineBlockCommentRuleAssertThat(code)\n- .withEditorConfigOverride(CODE_STYLE_PROPERTY to CodeStyleValue.ktlint_official)\n- .hasNoLintViolations()\n- }\n }\ndiff --git a/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/PackageNameRuleTest.kt b/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/PackageNameRuleTest.kt\nindex 508e17eb7a..8f59022693 100644\n--- a/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/PackageNameRuleTest.kt\n+++ b/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/PackageNameRuleTest.kt\n@@ -67,7 +67,7 @@ class PackageNameRuleTest {\n @ParameterizedTest(name = \"Suppression annotation: {0}\")\n @ValueSource(\n strings = [\n- \"ktlint:package-name\",\n+ \"ktlint:standard:package-name\",\n \"PackageName\", // IntelliJ IDEA suppression\n ],\n )\n@@ -80,15 +80,6 @@ class PackageNameRuleTest {\n packageNameRuleAssertThat(code).hasNoLintViolations()\n }\n \n- @Test\n- fun `Given a package name containing an forbidden character and the rule is suppressed via ktlint directive in comment then do not emit`() {\n- val code =\n- \"\"\"\n- package foo.foo_bar // ktlint-disable package-name\n- \"\"\".trimIndent()\n- packageNameRuleAssertThat(code).hasNoLintViolations()\n- }\n-\n @Test\n fun `Issue 1757 - Given a package name containing diacritics then do no report a violation`() {\n val code =\ndiff --git a/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/ParameterListSpacingRuleTest.kt b/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/ParameterListSpacingRuleTest.kt\nindex ff59f97677..ec6b2788ae 100644\n--- a/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/ParameterListSpacingRuleTest.kt\n+++ b/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/ParameterListSpacingRuleTest.kt\n@@ -48,12 +48,12 @@ class ParameterListSpacingRuleTest {\n }\n \n @Test\n- fun `Given a function signature without parameters but containing an comment (for example to disable a ktlint rule) in the parameter list then do not reformat`() {\n+ fun `Given a function signature without parameters but containing an EOL comment in the parameter list then do not reformat`() {\n val code =\n \"\"\"\n- data class Foo @JvmOverloads constructor( // ktlint-disable annotation\n+ data class Foo @JvmOverloads constructor( // some comment\n )\n- @JvmOverloads fun foo1( // ktlint-disable annotation\n+ @JvmOverloads fun foo1( // some comment\n )\n fun foo2(\n // some comment\n@@ -69,7 +69,7 @@ class ParameterListSpacingRuleTest {\n fun `Given a function signature without parameters but containing an EOL comment not preceded by a whitespace then avoid conflict with comment spacing rule`() {\n val code =\n \"\"\"\n- data class Foo @JvmOverloads constructor(// ktlint-disable annotation\n+ data class Foo @JvmOverloads constructor(// some comment\n )\n \"\"\".trimIndent()\n parameterListSpacingRuleAssertThat(code)\n@@ -331,10 +331,11 @@ class ParameterListSpacingRuleTest {\n \n @Test\n fun `Given a function signature with multiple parameters and at least one space before the comma separating the parameters then reformat`() {\n+ @Suppress(\"ktlint:standard:string-template\")\n val code =\n \"\"\"\n fun foo(a: Any$TOO_MANY_SPACES, b: Any) = \"some-result\"\n- \"\"\".trimIndent() // ktlint-disable string-template\n+ \"\"\".trimIndent()\n val formattedCode =\n \"\"\"\n fun foo(a: Any, b: Any) = \"some-result\"\n@@ -346,11 +347,12 @@ class ParameterListSpacingRuleTest {\n \n @Test\n fun `Given a function signature with multiple parameters and at least one newline before the comma separating the parameters then reformat`() {\n+ @Suppress(\"ktlint:standard:string-template\")\n val code =\n \"\"\"\n fun foo(a: Any\n , b: Any) = \"some-result\"\n- \"\"\".trimIndent() // ktlint-disable string-template\n+ \"\"\".trimIndent()\n val formattedCode =\n \"\"\"\n fun foo(a: Any, b: Any) = \"some-result\"\n@@ -377,10 +379,11 @@ class ParameterListSpacingRuleTest {\n \n @Test\n fun `Given a function signature with multiple parameters and too many spaces after the comma separating the parameters then reformat`() {\n+ @Suppress(\"ktlint:standard:string-template\")\n val code =\n \"\"\"\n fun foo(a: Any,${TOO_MANY_SPACES}b: Any) = \"some-result\"\n- \"\"\".trimIndent() // ktlint-disable string-template\n+ \"\"\".trimIndent()\n val formattedCode =\n \"\"\"\n fun foo(a: Any, b: Any) = \"some-result\"\n@@ -392,13 +395,14 @@ class ParameterListSpacingRuleTest {\n \n @Test\n fun `Given a function signature with multiple parameters and a newline after the comma separating the parameters then do not reformat`() {\n+ @Suppress(\"ktlint:standard:string-template\")\n val code =\n \"\"\"\n fun foo(\n a: Any,\n b: Any\n ) = \"some-result\"\n- \"\"\".trimIndent() // ktlint-disable string-template\n+ \"\"\".trimIndent()\n parameterListSpacingRuleAssertThat(code).hasNoLintViolations()\n }\n \ndiff --git a/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/ParameterListWrappingRuleTest.kt b/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/ParameterListWrappingRuleTest.kt\nindex e8926d274e..94aac3ea93 100644\n--- a/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/ParameterListWrappingRuleTest.kt\n+++ b/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/ParameterListWrappingRuleTest.kt\n@@ -150,7 +150,7 @@ class ParameterListWrappingRuleTest {\n c: Any\n )\n \"\"\".trimIndent()\n- @Suppress(\"ktlint:argument-list-wrapping\", \"ktlint:max-line-length\")\n+ @Suppress(\"ktlint:standard:argument-list-wrapping\", \"ktlint:standard:max-line-length\")\n parameterListWrappingRuleAssertThat(code)\n .hasLintViolation(3, 13, \"Parameter should start on a newline\")\n .isFormattedAs(formattedCode)\n@@ -311,7 +311,7 @@ class ParameterListWrappingRuleTest {\n }\n }\n \"\"\".trimIndent()\n- @Suppress(\"ktlint:argument-list-wrapping\", \"ktlint:max-line-length\")\n+ @Suppress(\"ktlint:standard:argument-list-wrapping\", \"ktlint:standard:max-line-length\")\n parameterListWrappingRuleAssertThat(code)\n .hasLintViolation(2, 11, \"Parameter should start on a newline\")\n .isFormattedAs(formattedCode)\ndiff --git a/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/PropertyNamingRuleTest.kt b/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/PropertyNamingRuleTest.kt\nindex bc0271b805..1fbf6136f9 100644\n--- a/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/PropertyNamingRuleTest.kt\n+++ b/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/PropertyNamingRuleTest.kt\n@@ -43,7 +43,7 @@ class PropertyNamingRuleTest {\n const val FOO_BAR_2 = \"foo-bar-2\"\n const val \u0178\u00c8\u0160_TH\u00ceS_IS_ALLOWED_123 = \"Yes this is allowed\"\n \"\"\".trimIndent()\n- @Suppress(\"ktlint:argument-list-wrapping\", \"ktlint:max-line-length\")\n+ @Suppress(\"ktlint:standard:argument-list-wrapping\", \"ktlint:standard:max-line-length\")\n propertyNamingRuleAssertThat(code)\n .hasLintViolationWithoutAutoCorrect(1, 11, \"Property name should use the screaming snake case notation when the value can not be changed\")\n }\n@@ -55,7 +55,7 @@ class PropertyNamingRuleTest {\n val foo = Foo()\n val FOO_BAR = FooBar()\n \"\"\".trimIndent()\n- @Suppress(\"ktlint:argument-list-wrapping\", \"ktlint:max-line-length\")\n+ @Suppress(\"ktlint:standard:argument-list-wrapping\", \"ktlint:standard:max-line-length\")\n propertyNamingRuleAssertThat(code)\n .hasLintViolationWithoutAutoCorrect(1, 5, \"Property name should use the screaming snake case notation when the value can not be changed\")\n }\n@@ -71,7 +71,7 @@ class PropertyNamingRuleTest {\n }\n }\n \"\"\".trimIndent()\n- @Suppress(\"ktlint:argument-list-wrapping\", \"ktlint:max-line-length\")\n+ @Suppress(\"ktlint:standard:argument-list-wrapping\", \"ktlint:standard:max-line-length\")\n propertyNamingRuleAssertThat(code)\n .hasLintViolationWithoutAutoCorrect(3, 13, \"Property name should use the screaming snake case notation when the value can not be changed\")\n }\n@@ -161,7 +161,7 @@ class PropertyNamingRuleTest {\n @ParameterizedTest(name = \"Suppression annotation: {0}\")\n @ValueSource(\n strings = [\n- \"ktlint:property-naming\",\n+ \"ktlint:standard:property-naming\",\n \"PropertyName\", // IntelliJ IDEA suppression\n ],\n )\ndiff --git a/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/importordering/ImportOrderingRuleAsciiTest.kt b/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/importordering/ImportOrderingRuleAsciiTest.kt\nindex b5015142fc..469cd7b536 100644\n--- a/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/importordering/ImportOrderingRuleAsciiTest.kt\n+++ b/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/importordering/ImportOrderingRuleAsciiTest.kt\n@@ -121,7 +121,7 @@ class ImportOrderingRuleAsciiTest {\n import android.app.Activity\n import android.view.ViewGroup\n \"\"\".trimIndent()\n- @Suppress(\"ktlint:argument-list-wrapping\", \"ktlint:max-line-length\")\n+ @Suppress(\"ktlint:standard:argument-list-wrapping\", \"ktlint:standard:max-line-length\")\n importOrderingRuleAssertThat(code)\n .withEditorConfigOverride(ASCII_IMPORT_ORDERING)\n .hasLintViolationWithoutAutoCorrect(1, 1, \"Imports must be ordered in lexicographic order without any empty lines in-between -- no autocorrection due to comments in the import list\")\n@@ -136,7 +136,7 @@ class ImportOrderingRuleAsciiTest {\n import android.app.Activity\n import android.view.ViewGroup\n \"\"\".trimIndent()\n- @Suppress(\"ktlint:argument-list-wrapping\", \"ktlint:max-line-length\")\n+ @Suppress(\"ktlint:standard:argument-list-wrapping\", \"ktlint:standard:max-line-length\")\n importOrderingRuleAssertThat(code)\n .withEditorConfigOverride(ASCII_IMPORT_ORDERING)\n .hasLintViolationWithoutAutoCorrect(1, 1, \"Imports must be ordered in lexicographic order without any empty lines in-between -- no autocorrection due to comments in the import list\")\ndiff --git a/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/importordering/ImportOrderingRuleIdeaTest.kt b/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/importordering/ImportOrderingRuleIdeaTest.kt\nindex 2447bee4bf..1270f32bc7 100644\n--- a/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/importordering/ImportOrderingRuleIdeaTest.kt\n+++ b/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/importordering/ImportOrderingRuleIdeaTest.kt\n@@ -38,7 +38,7 @@ class ImportOrderingRuleIdeaTest {\n import android.content.Context as Ctx\n import androidx.fragment.app.Fragment as F\n \"\"\".trimIndent()\n- @Suppress(\"ktlint:argument-list-wrapping\", \"ktlint:max-line-length\")\n+ @Suppress(\"ktlint:standard:argument-list-wrapping\", \"ktlint:standard:max-line-length\")\n importOrderingRuleAssertThat(code)\n .withEditorConfigOverride(IDEA_DEFAULT_IMPORT_ORDERING)\n .hasLintViolation(1, 1, \"Imports must be ordered in lexicographic order without any empty lines in-between with \\\"java\\\", \\\"javax\\\", \\\"kotlin\\\" and aliases in the end\")\n@@ -109,7 +109,7 @@ class ImportOrderingRuleIdeaTest {\n import android.view.ViewGroup\n import java.util.List\n \"\"\".trimIndent()\n- @Suppress(\"ktlint:argument-list-wrapping\", \"ktlint:max-line-length\")\n+ @Suppress(\"ktlint:standard:argument-list-wrapping\", \"ktlint:standard:max-line-length\")\n importOrderingRuleAssertThat(code)\n .withEditorConfigOverride(IDEA_DEFAULT_IMPORT_ORDERING)\n .hasLintViolation(1, 1, \"Imports must be ordered in lexicographic order without any empty lines in-between with \\\"java\\\", \\\"javax\\\", \\\"kotlin\\\" and aliases in the end\")\n@@ -146,7 +146,7 @@ class ImportOrderingRuleIdeaTest {\n import android.content.Context as Ctx\n import androidx.fragment.app.Fragment as F // comment 3\n \"\"\".trimIndent()\n- @Suppress(\"ktlint:argument-list-wrapping\", \"ktlint:max-line-length\")\n+ @Suppress(\"ktlint:standard:argument-list-wrapping\", \"ktlint:standard:max-line-length\")\n importOrderingRuleAssertThat(code)\n .withEditorConfigOverride(IDEA_DEFAULT_IMPORT_ORDERING)\n .hasLintViolation(1, 1, \"Imports must be ordered in lexicographic order without any empty lines in-between with \\\"java\\\", \\\"javax\\\", \\\"kotlin\\\" and aliases in the end\")\ndiff --git a/ktlint-test/src/main/kotlin/com/pinterest/ktlint/test/KtlintDocumentationTest.kt b/ktlint-test/src/main/kotlin/com/pinterest/ktlint/test/KtlintDocumentationTest.kt\nnew file mode 100644\nindex 0000000000..b59050a7ce\n--- /dev/null\n+++ b/ktlint-test/src/main/kotlin/com/pinterest/ktlint/test/KtlintDocumentationTest.kt\n@@ -0,0 +1,11 @@\n+package com.pinterest.ktlint.test\n+\n+import org.junit.jupiter.api.Test\n+\n+/**\n+ * Mark a unit test as a unit test for an example in the Ktlint documentation. For now the purpose is only to indicate that the code of the\n+ * test is also used in the documentation. A future possible use it that the code samples in the documentation are extracted from the unit\n+ * test directly which then will ensure that the code samples in the documentation actually provide the documented results.\n+ */\n+@Test\n+public annotation class KtlintDocumentationTest\n", "problem_statement": "Drop support for ktlint-enable / ktlint-disable directive\nThe directives below can be used to suppress ktlint rules:\r\n```\r\nval foo = \"foo\" // ktlint-disable\r\n\r\n/* ktlint-disable */\r\nval foo = \"foo\"\r\n/* ktlint-enable */\r\n```\r\n\r\nThe usage of `Suppress` and `SuppressWarning` annotation however is more native and should be the only way starting from `1.0` version:\r\n```\r\n@Suppress(\"ktlint\")\r\nval foo = \"foo\"\r\n```\r\n\r\nIdeally, a rule is added which helps in autocorrecting the old directives to annotations. If this is implemented, take care that this rule itself should not be suppressed even in case for a line, block or file *all* annotations are suppressed.\n", "hints_text": "Using [Github Code Search](https://github.com/search?type=code&auto_enroll=true&q=ktlint-disable+language%3AKotlin) some insight can be collected in how the old directives are used. Unfortunately, the total number of search result is currently limited to 100 results. By excluding based on repository, some more insights can be collected but this is also limited. In summer 2023 a new search API is expected which should be able to return all search results.\r\n\r\nInsights sofar:\r\n\r\nIf a single construct is surrounded by a block directive, it should be replaced by an annotation on that single construct:\r\n```\r\n /* ktlint-disable max-line-length */\r\n private const val URI_REGEX = \"^(?:(?![^:@]+:[^:@/]*@)([^:/?#.]+):)?(?://)?((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:/?#]*)(?::(\\\\d*))?)(((/(?:[^?#](?![^?#/]*\\\\.[^?#/.]+(?:[?#]|$)))*/?)?([^?#/]*))(?:\\\\?([^#]*))?(?:#(.*))?)\"\r\n\r\n /* ktlint-enable max-line-length */\r\n```\r\n\r\nHowever if the directive block contains multiple statements, it can not be simply replaced with a Suppress on the first (nor on all statements). Moving the Suppress to an outer construct is not always equivalent to current situation:\r\n```\r\n @Test\r\n fun testParseStringForHybridFileParcelable() {\r\n /* ktlint-disable max-line-length */\r\n // ls\r\n val lsLines = arrayOf(\r\n \"-rwxr-x--- 1 root shell 29431 2009-01-01 08:00 init.rc\",\r\n \"lrw-r--r-- 1 root root 15 2009-01-01 08:00 product -> /system/product\",\r\n \"drwxr-xr-x 17 root root 4096 1970-05-19 08:40 system\",\r\n \"-r--r--r-- 1 root root 10 1970-01-13 07:32 cpu_variant:arm\",\r\n \"lrwxrwxrwx 1 root root 0 2022-10-05 15:39 ac -> ../../devices/platform/GFSH0001:00/power_supply/ac\",\r\n \"lrwxrwxrwx 1 root root 0 2022-10-05 00:16 usb -> ../../devices/platform/soc/c440000.qcom,spmi/spmi-0/spmi0-02/c440000.qcom,spmi:qcom,pm8150b@2:qcom,qpnp-smb5/power_supply/usb\"\r\n )\r\n\r\n // stat with old toybox or busybox\r\n // val a1 = \"-rwxr-x--- 1 shell root 512 2009-01-01 08:00:00.000000000 `init.rc'\"\r\n // val b1 = \"lrw-r--r-- 1 root root 512 2009-01-01 08:00:00.000000000 `product' -> `/system/product'\"\r\n // val c1 = \"drwxr-xr-x 17 root root 512 1970-05-19 08:40:27.269999949 `system'\"\r\n\r\n // stat with new toybox\r\n val statLines = arrayOf(\r\n \"-rwxr-x--- 1 shell root 512 1230796800 `init.rc'\",\r\n \"lrw-r--r-- 1 root root 512 1230796800 `product' -> `/system/product'\",\r\n \"drwxr-xr-x 17 root root 512 11922027 `system'\",\r\n \"-r--r--r-- 1 root root 512 1035141 `cpu_variant:arm'\",\r\n \"lrwxrwxrwx 1 root root 512 1664955558 /sys/class/power_supply/ac -> '../../devices/platform/GFSH0001:00/power_supply/ac'\",\r\n \"lrwxrwxrwx 1 root root 512 1664956626 /sys/class/power_supply/usb -> '../../devices/platform/soc/c440000.qcom,spmi/spmi-0/spmi0-02/c440000.qcom,spmi:qcom,pm8150b@2:qcom,qpnp-smb5/power_supply/usb'\"\r\n )\r\n /* ktlint-enable max-line-length */\r\n\r\n ....\r\n }\r\n```\r\n\r\nIn example below, the block directive should be replaced with a file-annotation *or* the annotation must be interpreted as being relevant for the entire import list (but what if the annotation is not placed just before the first import?):\r\n```\r\n/* ktlint-disable import-ordering */\r\nimport android.app.Notification\r\n```\r\n\r\nIn case below, the same EOL directive is repeated multiple times, but not on all lines. Usage of the block directive would have been a better choice in this example. But this is similar to one of problems mentioned before:\r\n```\r\n val result = CharArray(16)\r\n result[ 0] = HEX_DIGIT_CHARS[(this shr 60 and 0xf).toInt()] // ktlint-disable no-multi-spaces\r\n result[ 1] = HEX_DIGIT_CHARS[(this shr 56 and 0xf).toInt()] // ktlint-disable no-multi-spaces\r\n result[ 2] = HEX_DIGIT_CHARS[(this shr 52 and 0xf).toInt()] // ktlint-disable no-multi-spaces\r\n result[ 3] = HEX_DIGIT_CHARS[(this shr 48 and 0xf).toInt()] // ktlint-disable no-multi-spaces\r\n result[ 4] = HEX_DIGIT_CHARS[(this shr 44 and 0xf).toInt()] // ktlint-disable no-multi-spaces\r\n result[ 5] = HEX_DIGIT_CHARS[(this shr 40 and 0xf).toInt()] // ktlint-disable no-multi-spaces\r\n result[ 6] = HEX_DIGIT_CHARS[(this shr 36 and 0xf).toInt()] // ktlint-disable no-multi-spaces\r\n result[ 7] = HEX_DIGIT_CHARS[(this shr 32 and 0xf).toInt()] // ktlint-disable no-multi-spaces\r\n result[ 8] = HEX_DIGIT_CHARS[(this shr 28 and 0xf).toInt()] // ktlint-disable no-multi-spaces\r\n result[ 9] = HEX_DIGIT_CHARS[(this shr 24 and 0xf).toInt()] // ktlint-disable no-multi-spaces\r\n result[10] = HEX_DIGIT_CHARS[(this shr 20 and 0xf).toInt()]\r\n result[11] = HEX_DIGIT_CHARS[(this shr 16 and 0xf).toInt()]\r\n result[12] = HEX_DIGIT_CHARS[(this shr 12 and 0xf).toInt()]\r\n result[13] = HEX_DIGIT_CHARS[(this shr 8 and 0xf).toInt()] // ktlint-disable no-multi-spaces\r\n result[14] = HEX_DIGIT_CHARS[(this shr 4 and 0xf).toInt()] // ktlint-disable no-multi-spaces\r\n result[15] = HEX_DIGIT_CHARS[(this and 0xf).toInt()] // ktlint-disable no-multi-spaces\r\n```\r\n\r\nReferences to old `experimental` rule set should be replaced with `standard`:\r\n```\r\n /* ktlint-disable experimental:argument-list-wrapping */\r\n fixture.getSut(replacements = mapOf(Replacement.FileInputStream.STRING))\r\n```\r\n\r\nIn example below, the block directive should be replace with a file annotation:\r\n```\r\n/* ktlint-disable */\r\n@file:Suppress(\"PackageName\", \"TopLevelName\")\r\n```", "created_at": "2023-06-05T19:31:38Z", "version": "0.49", "FAIL_TO_PASS": [ "gradle_test_execution" ], "PASS_TO_PASS": [], "ERROR_TO_PASS": [], "environment_setup_commit": "410d8849874f4d3600f9d4572e0850adccce4f2d" }, { "repo": "pinterest/ktlint", "pull_number": 2097, "instance_id": "pinterest__ktlint-2097", "issue_numbers": [ "2095" ], "base_commit": "410d8849874f4d3600f9d4572e0850adccce4f2d", "patch": "diff --git a/CHANGELOG.md b/CHANGELOG.md\nindex 594b130ee0..ad5cf178e4 100644\n--- a/CHANGELOG.md\n+++ b/CHANGELOG.md\n@@ -54,6 +54,7 @@ At this point in time, it is not yet decided what the next steps will be. Ktlint\n * Ignore property with name `serialVersionUID` in `property-naming` ([#2045](https://github.com/pinterest/ktlint/issues/2045))\n * Prevent incorrect reporting of violations in case a nullable function type reference exceeds the maximum line length `parameter-list-wrapping` ([#1324](https://github.com/pinterest/ktlint/issues/1324)) \n * Prevent false negative on `else` branch when body contains only chained calls or binary expression ([#2057](https://github.com/pinterest/ktlint/issues/2057))\n+* Fix indent when property value is wrapped to next line ([#2095](https://github.com/pinterest/ktlint/issues/2095)) \n \n ### Changed\n \ndiff --git a/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/PropertyWrappingRule.kt b/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/PropertyWrappingRule.kt\nindex 88f3afdd43..2ffdb330c1 100644\n--- a/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/PropertyWrappingRule.kt\n+++ b/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/PropertyWrappingRule.kt\n@@ -146,7 +146,7 @@ public class PropertyWrappingRule :\n )\n LOGGER.trace { \"$line: \" + ((if (!autoCorrect) \"would have \" else \"\") + \"inserted newline before ${node.text}\") }\n if (autoCorrect) {\n- node.upsertWhitespaceBeforeMe(node.indent())\n+ node.upsertWhitespaceBeforeMe(indentConfig.childIndentOf(node))\n }\n }\n \n", "test_patch": "diff --git a/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/PropertyWrappingRuleTest.kt b/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/PropertyWrappingRuleTest.kt\nindex 8cadc91bd3..52535a0d16 100644\n--- a/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/PropertyWrappingRuleTest.kt\n+++ b/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/PropertyWrappingRuleTest.kt\n@@ -24,7 +24,6 @@ internal class PropertyWrappingRuleTest {\n \"\"\".trimIndent()\n propertyWrappingRuleAssertThat(code)\n .setMaxLineLength()\n- .addAdditionalRuleProvider { IndentationRule() }\n .hasLintViolation(2, 34, \"Missing newline after \\\":\\\"\")\n .isFormattedAs(formattedCode)\n }\n@@ -46,7 +45,6 @@ internal class PropertyWrappingRuleTest {\n \"\"\".trimIndent()\n propertyWrappingRuleAssertThat(code)\n .setMaxLineLength()\n- .addAdditionalRuleProvider { IndentationRule() }\n .hasLintViolation(2, 30, \"Missing newline before \\\"TypeWithALongName\\\"\")\n .isFormattedAs(formattedCode)\n }\n@@ -69,7 +67,6 @@ internal class PropertyWrappingRuleTest {\n \"\"\".trimIndent()\n propertyWrappingRuleAssertThat(code)\n .setMaxLineLength()\n- .addAdditionalRuleProvider { IndentationRule() }\n .hasLintViolations(\n LintViolation(2, 50, \"Missing newline after \\\"=\\\"\"),\n LintViolation(3, 49, \"Missing newline before \\\"TypeWithALongName(123)\\\"\"),\n@@ -93,7 +90,6 @@ internal class PropertyWrappingRuleTest {\n \"\"\".trimIndent()\n propertyWrappingRuleAssertThat(code)\n .setMaxLineLength()\n- .addAdditionalRuleProvider { IndentationRule() }\n .hasLintViolation(2, 50, \"Missing newline before \\\"TypeWithALongName(123)\\\"\")\n .isFormattedAs(formattedCode)\n }\n", "problem_statement": "Fix indent when property value is wrapped to next line\n\r\n\r\n## Expected Behavior\r\nAutoformatting should not reformat below line to incorrect state\r\n```\r\nprivate val deferredMessageQueueSubscription = DeferredMessageQueueSubscription(uri = ServiceBusUri(\"deferredQueueTestUri\"))\r\n```\r\n\r\n## Observed Behavior\r\nAutoformatting moves `DeferredMessageQueueSubscription(uri = ServiceBusUri(\"deferredQueueTestUri\"))` to the next line and as the results it looks like this:\r\n```\r\n private val deferredMessageQueueSubscription = \r\n DeferredMessageQueueSubscription(uri = ServiceBusUri(\"deferredQueueTestUri\"))\r\n```\r\n\r\n## Steps to Reproduce\r\nAutoformatting should allow to reproduce this. My Detekt config:\r\n```\r\nformatting:\r\n excludes: [ '**/build/**' ]\r\n MaximumLineLength:\r\n active: false\r\n NoBlankLineBeforeRbrace:\r\n active: false\r\n Indentation:\r\n active: false\r\n ArgumentListWrapping:\r\n active: false\r\n MultiLineIfElse:\r\n active: false\r\n```\r\n\r\n## Your Environment\r\n* Version of ktlint used: 0.49.1\r\n* Name and version (or code for custom task) of integration used: Detekt 1.23.0. Related issue https://github.com/detekt/detekt/issues/6223\r\n* Version of Gradle: 7.3.3\r\n* Kotlin version 1.8.21\r\n\r\n\n", "hints_text": "", "created_at": "2023-06-28T19:53:01Z", "version": "0.49", "FAIL_TO_PASS": [ "gradle_test_execution" ], "PASS_TO_PASS": [], "ERROR_TO_PASS": [], "environment_setup_commit": "410d8849874f4d3600f9d4572e0850adccce4f2d" }, { "repo": "pinterest/ktlint", "pull_number": 1944, "instance_id": "pinterest__ktlint-1944", "issue_numbers": [ "1942" ], "base_commit": "542da50fc2e641af7282dc29f82bbf432c1135d7", "patch": "diff --git a/CHANGELOG.md b/CHANGELOG.md\nindex e86c1d9467..534063da33 100644\n--- a/CHANGELOG.md\n+++ b/CHANGELOG.md\n@@ -61,11 +61,15 @@ The `.editorconfig` properties `disabled_rules` and `ktlint_disabled_rules` are\n \n #### 'Ktlint Official` code style and renaming of existing code styles\n \n-A new code style with name `ktlint_offical` has been added. This code style combines the best elements from the Kotlin Coding conventions (https://kotlinlang.org/docs/coding-conventions.html) and Android's Kotlin styleguide (https://developer.android.com/kotlin/style-guide). This codestyle also provides additional formatting on topics which are not (explicitly) mentioned in the before mentioned styleguides. But do note that this code style sometimes formats code in a way which is not accepted by the default code formatters in IntelliJ IDEA and Android Studio. The formatters of those editors produce nicely formatted code in the vast majority of cases. But in a number of edge cases, the formatting contains bugs which are waiting to be fixed for several years. The new code style formats code in a way which is compatible with the default formatting of the editors whenever possible. When using this codestyle, it is best to disable (e.g. not use) code formatting in the editor. In the long run, this code style becomes the default code style provided by KtLint.\n+A new code style `ktlint_official` is introduced. This code style is work in progress but will become the default code style in the `1.0` release. Please try out the new code style and provide your feedback via the [issue tracker](https://github.com/pinterest/ktlint/issues).\n \n-The `official` code style has been renamed to `intellij_idea`. Code formatted with this code style aims to be compatible with default formatter of IntelliJ IDEA. This code style is based on Kotlin Coding conventions (https://kotlinlang.org/docs/coding-conventions.html). If `.editorconfig` property `ktlint_code_style` has been set to then do not forget to change the value of that property to `intellij_idea`. When not set, this is still the default code style of ktlint. Note that in the long run, the default code style is changed to `ktlint_official`.\n+This `ktlint_official` code style combines the best elements from the [Kotlin Coding conventions](https://kotlinlang.org/docs/coding-conventions.html) and [Android's Kotlin styleguide](https://developer.android.com/kotlin/style-guide). This code style also provides additional formatting on topics which are not (explicitly) mentioned in those conventions and style guide. But do note that this code style sometimes formats code in a way which is not accepted by the default code formatters in IntelliJ IDEA and Android Studio. The formatters of those editors produce nicely formatted code in the vast majority of cases. But in a number of edge cases, the formatting contains bugs which are waiting to be fixed for several years. The new code style formats code in a way which is compatible with the default formatting of the editors whenever possible. When using this codestyle, it is best to disable (e.g. not use) code formatting in the editor.\n \n-Code style `android` has been renamed to `android_studio`. Code formatted with this code style aims to be compatible with default formatter of Android Studio. This code style is based on Android's Kotlin styleguide (https://developer.android.com/kotlin/style-guide). If `.editorconfig` property `ktlint_code_style` has been set to then do not forget to change the value of that property to `android_studio`.\n+The existing code styles have been renamed to make more clear what the basis of the code style is.\n+\n+The `official` code style has been renamed to `intellij_idea`. Code formatted with this code style aims to be compatible with default formatter of IntelliJ IDEA. This code style is based on [Kotlin Coding conventions](https://kotlinlang.org/docs/coding-conventions.html). If `.editorconfig` property `ktlint_code_style` has been set to `android` then do not forget to change the value of that property to `intellij_idea`. When not set, this is still the default code style of ktlint `0.49`. Note that the default code style will be changed to `ktlint_official` in the `1.0` release.\n+\n+Code style `android` has been renamed to `android_studio`. Code formatted with this code style aims to be compatible with default formatter of Android Studio. This code style is based on [Android's Kotlin styleguide](https://developer.android.com/kotlin/style-guide). If `.editorconfig` property `ktlint_code_style` has been set to `android` then do not forget to change the value of that property to `android_studio`.\n \n #### Package restructuring and class relocation\n \n@@ -258,16 +262,18 @@ if (node.isRoot()) {\n \n ### Added\n \n-* Add new experimental rule `no-empty-first-line-in-class-body` for `ktlint_official` code style. This rule disallows a class to start with a blank line. This rule can also be run for other code styles, but then it needs to be enabled explicitly.\n-* Add new experimental rule `if-else-bracing` for `ktlint_official` code style. This rules enforces consistent usage of braces in all branches of a single if, if-else or if-else-if statement. This rule can also be run for other code styles, but then it needs to be enabled explicitly.\n-* Add new experimental rule `no-consecutive-comments` for `ktlint_official` code style. This rule disallows consecutive comments except EOL comments. This rule can also be run for other code styles, but then it needs to be enabled explicitly.\n-* Add new experimental rule `try-catch-finally-spacing` for `ktlint_official` code style. This rule enforces consistent spacing in try-catch, try-finally and try-catch-finally statement. This rule can also be run for other code styles, but then it needs to be enabled explicitly.\n+* Add new code style `ktlint_offical`. The code style is work in progress and should be considered a preview. It is intended to become the default code style in the next release. Please try it out and give your feedback. See [code styles](https://pinterest.github.io/ktlint/rules/code-styles/) for more information. The following rules have been added to the `ktlint_official` code style (the rules can also be run for other code styles when enabled explicitly):\n+ * Add new experimental rule `no-empty-first-line-in-class-body`. This rule disallows a class to start with a blank line.\n+ * Add new experimental rule `if-else-bracing`. This rules enforces consistent usage of braces in all branches of a single if, if-else or if-else-if statement.\n+ * Add new experimental rule `no-consecutive-comments`. This rule disallows consecutive comments except EOL comments (see [examples](See https://pinterest.github.io/ktlint/rules/experimental/#disallow-consecutive-comments)).\n+ * Add new experimental rule `try-catch-finally-spacing`. This rule enforces consistent spacing in try-catch, try-finally and try-catch-finally statement. This rule can also be run for other code styles, but then it needs to be enabled explicitly.\n+ * Add new experimental rule `no-blank-line-in-list`. This rule disallows blank lines to be used in super type lists, type argument lists, type constraint lists, type parameter lists, value argument lists, and value parameter lists. ([#1224](https://github.com/pinterest/ktlint/issues/1224))\n+ * Add new experimental rule `multiline-expression-wrapping`. This forces a multiline expression as value in an assignment to start on a separate line. ([#1217](https://github.com/pinterest/ktlint/issues/1217))\n+ * Add new experimental rule `string-template-indent`. This forces multiline string templates which are post-fixed with `.trimIndent()` to be formatted consistently. The opening and closing `\"\"\"` are placed on separate lines and the indentation of the content of the template is aligned with the `\"\"\"`. ([#925](https://github.com/pinterest/ktlint/issues/925))\n+ * Add new experimental rule `if-else-wrapping`. This enforces that a single line if-statement is kept simple. A single line if-statement may contain no more than one else-branch. The branches a single line if-statement may not be wrapped in a block. ([#812](https://github.com/pinterest/ktlint/issues/812))\n * Wrap the type or value of a function or class parameter in case the maximum line length is exceeded `parameter-wrapping` ([#1846](https://github.com/pinterest/ktlint/pull/1846))\n * Wrap the type or value of a property in case the maximum line length is exceeded `property-wrapping` ([#1846](https://github.com/pinterest/ktlint/pull/1846))\n * Recognize Kotlin Script when linting and formatting code from `stdin` with KtLint CLI ([#1832](https://github.com/pinterest/ktlint/issues/1832))\n-* Add new experimental rule `no-blank-line-in-list` for `ktlint_official` code style. This rule disallows blank lines to be used in super type lists, type argument lists, type constraint lists, type parameter lists, value argument lists, and value parameter lists. This rule can also be run for other code styles, but then it needs to be enabled explicitly. ([#1224](https://github.com/pinterest/ktlint/issues/1224))\n-* Add new experimental rule `multiline-expression-wrapping` for `ktlint_official` code style. This forces a multiline expression as value in an assignment to start on a separate line. This rule can also be run for other code styles, but then it needs to be enabled explicitly. ([#1217](https://github.com/pinterest/ktlint/issues/1217))\n-* Add new experimental rule `string-template-indent` for `ktlint_official` code style. This forces multiline string templates which are post-fixed with `.trimIndent()` to be formatted consistently. The opening and closing `\"\"\"` are placed on separate lines and the indentation of the content of the template is aligned with the `\"\"\"`. This rule can also be run for other code styles, but then it needs to be enabled explicitly. ([#925](https://github.com/pinterest/ktlint/issues/925))\n * Support Bill of Materials (BOM), now you can integrate Ktlint in your `build.gradle` like:\n ```kotlin\n dependencies {\n@@ -278,7 +284,6 @@ if (node.isRoot()) {\n ...\n }\n ```\n-* Add new experimental rule `if-else-wrapping` for `ktlint_official` code style. This enforces that a single line if-statement is kept simple. A single line if-statement may contain no more than one else-branch. The branches a single line if-statement may not be wrapped in a block. This rule can also be run for other code styles, but then it needs to be enabled explicitly. ([#812](https://github.com/pinterest/ktlint/issues/812))\n * Add new experimental rule `enum-wrapping` for all code styles. An enum should either be a single line, or each enum entry should be defined on a separate line. ([#1903](https://github.com/pinterest/ktlint/issues/1903))\n \n ### Removed\n@@ -330,6 +335,8 @@ if (node.isRoot()) {\n * Update Kotlin development version to `1.8.20` and Kotlin version to `1.8.20`.\n * Revert to matrix build to speed up build, especially for the Windows related build ([#1787](https://github.com/pinterest/ktlint/pull/1787))\n * For the new code style `ktlint_official`, do not allow wildcard imports `java.util` and `kotlinx.android.synthetic` by default. Important: `.editorconfig` property `ij_kotlin_packages_to_use_import_on_demand` needs to be set to value `unset` in order to enforce IntelliJ IDEA default formatter to not generate wildcard imports `no-wildcard-imports` ([#1797](https://github.com/pinterest/ktlint/issues/1797))\n+* Convert a single line block comment to an EOL comment if not preceded or followed by another code element on the same line `comment-wrapping` ([#1941](https://github.com/pinterest/ktlint/issues/1941))\n+* Ignore a block comment inside a single line block `comment-wrapping` ([#1942](https://github.com/pinterest/ktlint/issues/1942))\n \n ## [0.48.2] - 2023-01-21\n \ndiff --git a/build-logic/src/main/kotlin/ktlint-kotlin-common.gradle.kts b/build-logic/src/main/kotlin/ktlint-kotlin-common.gradle.kts\nindex 5bb9faf2b2..c612c0a9dd 100644\n--- a/build-logic/src/main/kotlin/ktlint-kotlin-common.gradle.kts\n+++ b/build-logic/src/main/kotlin/ktlint-kotlin-common.gradle.kts\n@@ -31,12 +31,13 @@ tasks.withType().configureEach {\n logger.warn(\"Skipping tests for task '$name' as system property 'skipTests=$skipTests'\")\n }\n \n- maxParallelForks = if (System.getenv(\"CI\") != null) {\n- Runtime.getRuntime().availableProcessors()\n- } else {\n- // https://docs.gradle.org/8.0/userguide/performance.html#execute_tests_in_parallel\n- (Runtime.getRuntime().availableProcessors() / 2).takeIf { it > 0 } ?: 1\n- }\n+ maxParallelForks =\n+ if (System.getenv(\"CI\") != null) {\n+ Runtime.getRuntime().availableProcessors()\n+ } else {\n+ // https://docs.gradle.org/8.0/userguide/performance.html#execute_tests_in_parallel\n+ (Runtime.getRuntime().availableProcessors() / 2).takeIf { it > 0 } ?: 1\n+ }\n \n if (JavaVersion.current().isCompatibleWith(JavaVersion.VERSION_16)) {\n // https://docs.gradle.org/7.5/userguide/upgrading_version_7.html#removes_implicit_add_opens_for_test_workers\ndiff --git a/build.gradle.kts b/build.gradle.kts\nindex 21032208b8..ed20fdeb1d 100644\n--- a/build.gradle.kts\n+++ b/build.gradle.kts\n@@ -43,6 +43,7 @@ tasks.register(\"ktlintFormat\") {\n }\n \n tasks.wrapper {\n- distributionSha256Sum = URL(\"$distributionUrl.sha256\")\n- .openStream().use { it.reader().readText().trim() }\n+ distributionSha256Sum =\n+ URL(\"$distributionUrl.sha256\")\n+ .openStream().use { it.reader().readText().trim() }\n }\ndiff --git a/docs/index.md b/docs/index.md\nindex 67389cc599..85e6cecc62 100644\n--- a/docs/index.md\n+++ b/docs/index.md\n@@ -18,7 +18,7 @@\n ## Features\n \n - **No configuration required** \n- `ktlint` aims to capture the [official Kotlin coding conventions](https://kotlinlang.org/docs/reference/coding-conventions.html) and [Android Kotlin Style Guide](https://android.github.io/kotlin-guides/style.html). In some aspects `ktlint` is a bit more strict[*](https://github.com/pinterest/ktlint/issues/284#issuecomment-425177186).\n+ `ktlint` aims to capture the [Kotlin coding conventions](https://kotlinlang.org/docs/reference/coding-conventions.html) and [Android Kotlin Style Guide](https://android.github.io/kotlin-guides/style.html). In some aspects `ktlint` is a bit more strict[*](https://github.com/pinterest/ktlint/issues/284#issuecomment-425177186).\n - **Rule sets** \n `ktlint` offers a `standard` rule set. Next to this, it is easy to provide [custom rule sets](api/custom-rule-set/).\n - **.editorconfig** \ndiff --git a/docs/rules/code-styles.md b/docs/rules/code-styles.md\nnew file mode 100644\nindex 0000000000..bf41a58463\n--- /dev/null\n+++ b/docs/rules/code-styles.md\n@@ -0,0 +1,17 @@\n+In ktlint `0.49` the new code style `ktlint_official` is introduced. This code style is work in progress but will become the default code style in the `1.0` release. Please try out the new code style and provide your feedback via the [issue tracker](https://github.com/pinterest/ktlint/issues).\n+\n+```ini\n+[*.{kt,kts}]\n+ktlint_code_style = ktlint_official\n+```\n+\n+This `ktlint_official` code style combines the best elements from the [Kotlin Coding conventions](https://kotlinlang.org/docs/coding-conventions.html) and [Android's Kotlin styleguide](https://developer.android.com/kotlin/style-guide). This code style also provides additional formatting on topics which are not (explicitly) mentioned in those conventions and style guide.\n+\n+!!! note\n+ Be aware that this code style in some cases formats code in a way which is not accepted by the default code formatters in IntelliJ IDEA and Android Studio. The formatters of those editors produce nicely formatted code in the vast majority of cases. But in a number of edge cases, the formatting contains bugs which are waiting to be fixed for several years. The new code style formats code in a way which is compatible with the default formatting of the editors whenever possible. When using this codestyle, it is best to disable (e.g. not use) code formatting in the editor.\n+\n+The existing code styles have been renamed to make more clear what the basis of the code style is.\n+\n+* The `official` code style has been renamed to `intellij_idea`. Code formatted with this code style aims to be compatible with default formatter of IntelliJ IDEA. This code style is based on [Kotlin Coding conventions](https://kotlinlang.org/docs/coding-conventions.html). If `.editorconfig` property `ktlint_code_style` has been set to `official` then do not forget to change the value of that property to `intellij_idea`. When not set, this is still the default code style of ktlint `0.49`. Be aware that the default code style will be changed to `ktlint_official` in the `1.0` release.\n+\n+* Code style `android` has been renamed to `android_studio`. Code formatted with this code style aims to be compatible with default formatter of Android Studio. This code style is based on [Android's Kotlin styleguide](https://developer.android.com/kotlin/style-guide). If `.editorconfig` property `ktlint_code_style` has been set to `android` then do not forget to change the value of that property to `android_studio`.\ndiff --git a/docs/rules/configuration-ktlint.md b/docs/rules/configuration-ktlint.md\nindex 1084faf6fb..891d08843a 100644\n--- a/docs/rules/configuration-ktlint.md\n+++ b/docs/rules/configuration-ktlint.md\n@@ -6,13 +6,16 @@ Ktlint uses a limited set of `.editorconfig` properties for additional configura\n \n ## Code style\n \n-By default, the `offical` Kotlin code style is applied. Alternatively, the code style can be set to `android`.\n+By default, the `intellij_idea` Kotlin code style is applied. Alternatively, the code style can be set to `ktlint_official` or `android`.\n \n ```ini\n [*.{kt,kts}]\n-ktlint_code_style = official\n+ktlint_code_style = ktlint_official\n ```\n \n+!!! note\n+ The default code style will be changed to `ktlint_official` in the `1.0` version of ktlint.\n+\n ## Disabled rules\n \n !!! note\n@@ -175,7 +178,7 @@ This setting only takes effect when rule `no-wildcard-imports` is enabled.\n \n ## Indent size & style\n \n-By default, indenting is done with 4 spaces per indent level in `official` Kotlin code style while a single tab is used by default in the `android` code style.\n+By default, indenting is done with 4 spaces per indent level. Code style `android_studio` uses a tab per indent level.\n \n ```ini\n [*.{kt,kts}]\ndiff --git a/docs/rules/experimental.md b/docs/rules/experimental.md\nindex dd6873a4c4..7aa9f1dd3a 100644\n--- a/docs/rules/experimental.md\n+++ b/docs/rules/experimental.md\n@@ -50,7 +50,12 @@ Rule id: `no-empty-first-line-in-class-body`\n \n ## Disallow consecutive comments\n \n-Disallow consecutive comments (EOL comments, block comments or KDoc) except EOL comments. Comments need to be separated by at least one code element.\n+Consecutive comments are disallowed in following cases:\n+- Any mix of a consecutive kdoc, a block comment or an EOL comment unless separated by a blank line in between\n+- Consecutive KDocs (even when separated by a blank line)\n+- Consecutive block comments (even when separated by a blank line)\n+\n+Consecutive EOL comments are always allowed as they are often used instead of a block comment.\n \n === \"[:material-heart:](#) Ktlint\"\n \n@@ -58,16 +63,36 @@ Disallow consecutive comments (EOL comments, block comments or KDoc) except EOL\n // An EOL comment\n // may be followed by another EOL comment\n val foo = \"foo\"\n+\n+ // Different comment types (including KDoc) may be consecutive ..\n+\n+ /*\n+ * ... but do need to be separated by a blank line ...\n+ */\n+\n+ /**\n+ * ... but a KDoc can not be followed by an EOL or a block comment or another KDoc\n+ */\n+ fun bar() = \"bar\"\n+\n ```\n \n === \"[:material-heart:](#) Disallowed\"\n \n ```kotlin\n- // An EOL comment\n- /* followed by a block comment */\n- /** or a KDoc */\n- // is not allowed\n+ /*\n+ * Block comments can not be consecutive ...\n+ */\n+ /*\n+ * ... even not when separated by a new line.\n+ */\n val bar = \"bar\" \n+\n+ /**\n+ * A KDoc can not be followed by a block comment or an EOL comment or another KDOC\n+ */\n+\n+ // ... even not when separated by a new line.\n ```\n \n Rule id: `no-consecutive-comments`\ndiff --git a/docs/rules/standard.md b/docs/rules/standard.md\nindex d0653e8e63..12ff505919 100644\n--- a/docs/rules/standard.md\n+++ b/docs/rules/standard.md\n@@ -875,6 +875,7 @@ A block comment should start and end on a line that does not contain any other e\n /* Some comment 1 */\n val foo1 = \"foo1\"\n val foo2 = \"foo\" // Some comment\n+ val foo3 = { /* no-op */ } \n ```\n === \"[:material-heart-off-outline:](#) Disallowed\"\n \ndiff --git a/ktlint-cli/src/main/kotlin/com/pinterest/ktlint/cli/internal/KtlintCommandLine.kt b/ktlint-cli/src/main/kotlin/com/pinterest/ktlint/cli/internal/KtlintCommandLine.kt\nindex 743b9112d0..8360f72981 100644\n--- a/ktlint-cli/src/main/kotlin/com/pinterest/ktlint/cli/internal/KtlintCommandLine.kt\n+++ b/ktlint-cli/src/main/kotlin/com/pinterest/ktlint/cli/internal/KtlintCommandLine.kt\n@@ -381,12 +381,13 @@ internal class KtlintCommandLine {\n \n // Do not convert to \"val\" as the function depends on PicoCli options which are not fully instantiated until the \"run\" method is started\n internal fun configureLogger() {\n- logger = KotlinLogging\n- .logger {}\n- .setDefaultLoggerModifier { logger ->\n- (logger.underlyingLogger as Logger).level = minLogLevel\n- }\n- .initKtLintKLogger()\n+ logger =\n+ KotlinLogging\n+ .logger {}\n+ .setDefaultLoggerModifier { logger ->\n+ (logger.underlyingLogger as Logger).level = minLogLevel\n+ }\n+ .initKtLintKLogger()\n }\n \n private fun assertStdinAndPatternsFromStdinOptionsMutuallyExclusive() {\n@@ -411,11 +412,12 @@ internal class KtlintCommandLine {\n .map { file ->\n val fileName = file.toPath().absolutePathString()\n Callable {\n- fileName to process(\n- ktLintRuleEngine = ktLintRuleEngine,\n- code = Code.fromFile(file),\n- baselineLintErrors = lintErrorsPerFile.getOrDefault(fileName, emptyList()),\n- )\n+ fileName to\n+ process(\n+ ktLintRuleEngine = ktLintRuleEngine,\n+ code = Code.fromFile(file),\n+ baselineLintErrors = lintErrorsPerFile.getOrDefault(fileName, emptyList()),\n+ )\n }\n }.parallel({ (fileName, errList) -> report(Paths.get(fileName).relativeRoute, errList, reporter) })\n }\n@@ -590,20 +592,15 @@ internal class KtlintCommandLine {\n status = KOTLIN_PARSE_EXCEPTION,\n )\n is KtLintRuleException -> {\n- val codeSource =\n- if (code.isStdIn) {\n- \"code\"\n- } else {\n- \"file '${code.fileName}'\"\n- }\n- logger.debug(\"Internal Error (${e.ruleId}) in $codeSource at position '${e.line}:${e.col}\", e)\n+ logger.debug(\"Internal Error (${e.ruleId}) in ${code.fileNameOrStdin()} at position '${e.line}:${e.col}\", e)\n KtlintCliError(\n line = e.line,\n col = e.col,\n ruleId = \"\",\n detail =\n- \"Internal Error (rule '${e.ruleId}') in $codeSource at position '${e.line}:${e.col}. Please create a ticket \" +\n- \"at https://github.com/pinterest/ktlint/issues and provide the source code that triggered an error.\\n\" +\n+ \"Internal Error (rule '${e.ruleId}') in ${code.fileNameOrStdin()} at position '${e.line}:${e.col}. Please \" +\n+ \"create a ticket at https://github.com/pinterest/ktlint/issues and provide the source code that \" +\n+ \"triggered an error.\\n\" +\n e.stackTraceToString(),\n status = KTLINT_RULE_ENGINE_EXCEPTION,\n )\ndiff --git a/ktlint-rule-engine/src/main/kotlin/com/pinterest/ktlint/rule/engine/api/Code.kt b/ktlint-rule-engine/src/main/kotlin/com/pinterest/ktlint/rule/engine/api/Code.kt\nindex 69b347a7fb..98f113c34a 100644\n--- a/ktlint-rule-engine/src/main/kotlin/com/pinterest/ktlint/rule/engine/api/Code.kt\n+++ b/ktlint-rule-engine/src/main/kotlin/com/pinterest/ktlint/rule/engine/api/Code.kt\n@@ -1,5 +1,6 @@\n package com.pinterest.ktlint.rule.engine.api\n \n+import com.pinterest.ktlint.rule.engine.api.KtLintRuleEngine.Companion.STDIN_FILE\n import org.jetbrains.kotlin.konan.file.file\n import java.io.File\n import java.nio.file.Path\n@@ -15,6 +16,13 @@ public class Code private constructor(\n public val script: Boolean,\n public val isStdIn: Boolean,\n ) {\n+ public fun fileNameOrStdin(): String =\n+ if (isStdIn) {\n+ STDIN_FILE\n+ } else {\n+ fileName.orEmpty()\n+ }\n+\n public companion object {\n /**\n * Create [Code] from a [file] containing valid Kotlin code or script. The '.editorconfig' files on the path to [file] are taken\ndiff --git a/ktlint-rule-engine/src/main/kotlin/com/pinterest/ktlint/rule/engine/api/KtLintRuleEngine.kt b/ktlint-rule-engine/src/main/kotlin/com/pinterest/ktlint/rule/engine/api/KtLintRuleEngine.kt\nindex db30d6517f..5f01c9142e 100644\n--- a/ktlint-rule-engine/src/main/kotlin/com/pinterest/ktlint/rule/engine/api/KtLintRuleEngine.kt\n+++ b/ktlint-rule-engine/src/main/kotlin/com/pinterest/ktlint/rule/engine/api/KtLintRuleEngine.kt\n@@ -89,7 +89,7 @@ public class KtLintRuleEngine(\n code: Code,\n callback: (LintError) -> Unit = { },\n ) {\n- LOGGER.debug { \"Starting with linting file '${code.fileName}'\" }\n+ LOGGER.debug { \"Starting with linting file '${code.fileNameOrStdin()}'\" }\n \n val ruleExecutionContext = createRuleExecutionContext(this, code)\n val errors = mutableListOf()\n@@ -107,7 +107,7 @@ public class KtLintRuleEngine(\n .sortedWith { l, r -> if (l.line != r.line) l.line - r.line else l.col - r.col }\n .forEach { e -> callback(e) }\n \n- LOGGER.debug { \"Finished with linting file '${code.fileName}'\" }\n+ LOGGER.debug { \"Finished with linting file '${code.fileNameOrStdin()}'\" }\n }\n \n /**\n@@ -121,7 +121,7 @@ public class KtLintRuleEngine(\n code: Code,\n callback: (LintError, Boolean) -> Unit = { _, _ -> },\n ): String {\n- LOGGER.debug { \"Starting with formatting file '${code.fileName}'\" }\n+ LOGGER.debug { \"Starting with formatting file '${code.fileNameOrStdin()}'\" }\n \n val hasUTF8BOM = code.content.startsWith(UTF8_BOM)\n val ruleExecutionContext = createRuleExecutionContext(this, code)\n@@ -193,7 +193,7 @@ public class KtLintRuleEngine(\n } else {\n formattedCode\n }.also {\n- LOGGER.debug(\"Finished with formatting file '${code.fileName}'\")\n+ LOGGER.debug(\"Finished with formatting file '${code.fileNameOrStdin()}'\")\n }\n }\n \ndiff --git a/ktlint-rule-engine/src/main/kotlin/com/pinterest/ktlint/rule/engine/internal/RuleExecutionContext.kt b/ktlint-rule-engine/src/main/kotlin/com/pinterest/ktlint/rule/engine/internal/RuleExecutionContext.kt\nindex 88e0bdf226..3edcea80e9 100644\n--- a/ktlint-rule-engine/src/main/kotlin/com/pinterest/ktlint/rule/engine/internal/RuleExecutionContext.kt\n+++ b/ktlint-rule-engine/src/main/kotlin/com/pinterest/ktlint/rule/engine/internal/RuleExecutionContext.kt\n@@ -66,7 +66,7 @@ internal class RuleExecutionContext private constructor(\n e.col,\n e.rule.ruleId.value,\n \"\"\"\n- Rule '${e.rule.ruleId.value}' throws exception in file '${code.fileName}' at position (${e.line}:${e.col})\n+ Rule '${e.rule.ruleId.value}' throws exception in file '${code.fileNameOrStdin()}' at position (${e.line}:${e.col})\n Rule maintainer: ${e.rule.about.maintainer}\n Issue tracker : ${e.rule.about.issueTrackerUrl}\n Repository : ${e.rule.about.repositoryUrl}\ndiff --git a/ktlint-rule-engine/src/main/kotlin/com/pinterest/ktlint/rule/engine/internal/rulefilter/RunAfterRuleFilter.kt b/ktlint-rule-engine/src/main/kotlin/com/pinterest/ktlint/rule/engine/internal/rulefilter/RunAfterRuleFilter.kt\nindex 56dd55c782..1271978c37 100644\n--- a/ktlint-rule-engine/src/main/kotlin/com/pinterest/ktlint/rule/engine/internal/rulefilter/RunAfterRuleFilter.kt\n+++ b/ktlint-rule-engine/src/main/kotlin/com/pinterest/ktlint/rule/engine/internal/rulefilter/RunAfterRuleFilter.kt\n@@ -123,10 +123,6 @@ internal class RunAfterRuleFilter : RuleFilter {\n }\n \n runAfterRule.mode == ONLY_WHEN_RUN_AFTER_RULE_IS_LOADED_AND_ENABLED -> {\n- LOGGER.warn {\n- \"Skipping rule with id '${ruleProvider.ruleId.value}' as it requires that the rule with id \" +\n- \"'${runAfterRule.ruleId.value}' is loaded. However, no rule with this id is loaded.\"\n- }\n requiredButMissingRuleIds.add(\n RunAfterRuleRequiredButNotLoaded(\n ruleProvider.ruleId,\ndiff --git a/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/AnnotationRule.kt b/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/AnnotationRule.kt\nindex 7dbe0f6a16..9433678983 100644\n--- a/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/AnnotationRule.kt\n+++ b/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/AnnotationRule.kt\n@@ -3,7 +3,6 @@ package com.pinterest.ktlint.ruleset.standard.rules\n import com.pinterest.ktlint.rule.engine.core.api.ElementType.ANNOTATED_EXPRESSION\n import com.pinterest.ktlint.rule.engine.core.api.ElementType.ANNOTATION\n import com.pinterest.ktlint.rule.engine.core.api.ElementType.ANNOTATION_ENTRY\n-import com.pinterest.ktlint.rule.engine.core.api.ElementType.BLOCK\n import com.pinterest.ktlint.rule.engine.core.api.ElementType.CONSTRUCTOR_KEYWORD\n import com.pinterest.ktlint.rule.engine.core.api.ElementType.FILE_ANNOTATION_LIST\n import com.pinterest.ktlint.rule.engine.core.api.ElementType.GT\n@@ -31,7 +30,6 @@ import com.pinterest.ktlint.rule.engine.core.api.isWhiteSpaceWithNewline\n import com.pinterest.ktlint.rule.engine.core.api.lastChildLeafOrSelf\n import com.pinterest.ktlint.rule.engine.core.api.nextCodeLeaf\n import com.pinterest.ktlint.rule.engine.core.api.nextCodeSibling\n-import com.pinterest.ktlint.rule.engine.core.api.nextSibling\n import com.pinterest.ktlint.rule.engine.core.api.prevLeaf\n import com.pinterest.ktlint.rule.engine.core.api.upsertWhitespaceAfterMe\n import com.pinterest.ktlint.rule.engine.core.api.upsertWhitespaceBeforeMe\n@@ -94,10 +92,11 @@ public class AnnotationRule :\n \n override fun beforeFirstNode(editorConfig: EditorConfig) {\n codeStyle = editorConfig[CODE_STYLE_PROPERTY]\n- indentConfig = IndentConfig(\n- indentStyle = editorConfig[INDENT_STYLE_PROPERTY],\n- tabWidth = editorConfig[INDENT_SIZE_PROPERTY],\n- )\n+ indentConfig =\n+ IndentConfig(\n+ indentStyle = editorConfig[INDENT_STYLE_PROPERTY],\n+ tabWidth = editorConfig[INDENT_SIZE_PROPERTY],\n+ )\n }\n \n override fun beforeVisitChildNodes(\n@@ -189,15 +188,15 @@ public class AnnotationRule :\n \n node\n .takeIf { it.elementType == ANNOTATED_EXPRESSION }\n- ?.treeParent\n- ?.takeIf { it.elementType == BLOCK }\n- ?.nextSibling()\n- ?.let { nextSibling ->\n+ ?.lastChildLeafOrSelf()\n+ ?.nextCodeLeaf()\n+ ?.prevLeaf()\n+ ?.let { leaf ->\n // Let the indentation rule determine the exact indentation and only report and fix when the line needs to be wrapped\n- if (!nextSibling.textContains('\\n')) {\n- emit(nextSibling.startOffset, \"Expected newline\", true)\n+ if (!leaf.textContains('\\n')) {\n+ emit(leaf.startOffset, \"Expected newline\", true)\n if (autoCorrect) {\n- nextSibling.upsertWhitespaceBeforeMe(node.indent())\n+ leaf.upsertWhitespaceBeforeMe(node.indent())\n }\n }\n }\ndiff --git a/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/ArgumentListWrappingRule.kt b/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/ArgumentListWrappingRule.kt\nindex 55e8ce2d22..02e2043f4d 100644\n--- a/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/ArgumentListWrappingRule.kt\n+++ b/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/ArgumentListWrappingRule.kt\n@@ -61,10 +61,11 @@ public class ArgumentListWrappingRule :\n private var maxLineLength = MAX_LINE_LENGTH_PROPERTY.defaultValue\n \n override fun beforeFirstNode(editorConfig: EditorConfig) {\n- editorConfigIndent = IndentConfig(\n- indentStyle = editorConfig[INDENT_STYLE_PROPERTY],\n- tabWidth = editorConfig[INDENT_SIZE_PROPERTY],\n- )\n+ editorConfigIndent =\n+ IndentConfig(\n+ indentStyle = editorConfig[INDENT_STYLE_PROPERTY],\n+ tabWidth = editorConfig[INDENT_SIZE_PROPERTY],\n+ )\n maxLineLength = editorConfig[MAX_LINE_LENGTH_PROPERTY]\n }\n \ndiff --git a/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/ChainWrappingRule.kt b/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/ChainWrappingRule.kt\nindex c5809c767a..1560b134a2 100644\n--- a/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/ChainWrappingRule.kt\n+++ b/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/ChainWrappingRule.kt\n@@ -57,10 +57,11 @@ public class ChainWrappingRule :\n private var indentConfig = DEFAULT_INDENT_CONFIG\n \n override fun beforeFirstNode(editorConfig: EditorConfig) {\n- indentConfig = IndentConfig(\n- indentStyle = editorConfig[INDENT_STYLE_PROPERTY],\n- tabWidth = editorConfig[INDENT_SIZE_PROPERTY],\n- )\n+ indentConfig =\n+ IndentConfig(\n+ indentStyle = editorConfig[INDENT_STYLE_PROPERTY],\n+ tabWidth = editorConfig[INDENT_SIZE_PROPERTY],\n+ )\n }\n \n override fun beforeVisitChildNodes(\ndiff --git a/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/CommentWrappingRule.kt b/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/CommentWrappingRule.kt\nindex 49da940c45..d08f75668d 100644\n--- a/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/CommentWrappingRule.kt\n+++ b/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/CommentWrappingRule.kt\n@@ -2,12 +2,17 @@ package com.pinterest.ktlint.ruleset.standard.rules\n \n import com.pinterest.ktlint.rule.engine.core.api.ElementType.BLOCK_COMMENT\n import com.pinterest.ktlint.rule.engine.core.api.ElementType.EOL_COMMENT\n-import com.pinterest.ktlint.rule.engine.core.api.ElementType.WHITE_SPACE\n+import com.pinterest.ktlint.rule.engine.core.api.ElementType.LBRACE\n+import com.pinterest.ktlint.rule.engine.core.api.ElementType.RBRACE\n import com.pinterest.ktlint.rule.engine.core.api.RuleId\n import com.pinterest.ktlint.rule.engine.core.api.editorconfig.INDENT_SIZE_PROPERTY\n import com.pinterest.ktlint.rule.engine.core.api.editorconfig.INDENT_STYLE_PROPERTY\n+import com.pinterest.ktlint.rule.engine.core.api.firstChildLeafOrSelf\n import com.pinterest.ktlint.rule.engine.core.api.hasNewLineInClosedRange\n import com.pinterest.ktlint.rule.engine.core.api.indent\n+import com.pinterest.ktlint.rule.engine.core.api.isWhiteSpace\n+import com.pinterest.ktlint.rule.engine.core.api.isWhiteSpaceWithNewline\n+import com.pinterest.ktlint.rule.engine.core.api.lastChildLeafOrSelf\n import com.pinterest.ktlint.rule.engine.core.api.nextLeaf\n import com.pinterest.ktlint.rule.engine.core.api.prevLeaf\n import com.pinterest.ktlint.rule.engine.core.api.upsertWhitespaceBeforeMe\n@@ -15,6 +20,7 @@ import com.pinterest.ktlint.ruleset.standard.StandardRule\n import org.jetbrains.kotlin.com.intellij.lang.ASTNode\n import org.jetbrains.kotlin.com.intellij.psi.impl.source.tree.LeafPsiElement\n import org.jetbrains.kotlin.com.intellij.psi.impl.source.tree.PsiCommentImpl\n+import org.jetbrains.kotlin.psi.psiUtil.leaves\n \n /**\n * Checks external wrapping of block comments. Wrapping inside the comment is not altered. A block comment following another element on the\n@@ -35,19 +41,34 @@ public class CommentWrappingRule :\n emit: (offset: Int, errorMessage: String, canBeAutoCorrected: Boolean) -> Unit,\n ) {\n if (node.elementType == BLOCK_COMMENT) {\n- val nonIndentLeafOnSameLinePrecedingBlockComment =\n+ val beforeBlockComment =\n node\n- .prevLeaf()\n- ?.takeIf { isNonIndentLeafOnSameLine(it) }\n- val nonIndentLeafOnSameLineFollowingBlockComment =\n+ .leaves(false)\n+ .takeWhile { it.isWhiteSpace() && !it.textContains('\\n') }\n+ .firstOrNull()\n+ ?: node.firstChildLeafOrSelf()\n+ val afterBlockComment =\n node\n- .nextLeaf()\n- ?.takeIf { isNonIndentLeafOnSameLine(it) }\n+ .leaves()\n+ .takeWhile { it.isWhiteSpace() && !it.textContains('\\n') }\n+ .firstOrNull()\n+ ?: node.lastChildLeafOrSelf()\n \n- if (nonIndentLeafOnSameLinePrecedingBlockComment != null &&\n- nonIndentLeafOnSameLineFollowingBlockComment != null\n+ if (!node.textContains('\\n') &&\n+ !node.isKtlintSuppressionDirective() &&\n+ beforeBlockComment.prevLeaf().isWhitespaceWithNewlineOrNull() &&\n+ afterBlockComment.nextLeaf().isWhitespaceWithNewlineOrNull()\n ) {\n- if (hasNewLineInClosedRange(nonIndentLeafOnSameLinePrecedingBlockComment, nonIndentLeafOnSameLineFollowingBlockComment)) {\n+ emit(node.startOffset, \"A single line block comment must be replaced with an EOL comment\", true)\n+ if (autoCorrect) {\n+ node.replaceWithEndOfLineComment()\n+ }\n+ }\n+\n+ if (!beforeBlockComment.prevLeaf().isWhitespaceWithNewlineOrNull() &&\n+ !afterBlockComment.nextLeaf().isWhitespaceWithNewlineOrNull()\n+ ) {\n+ if (hasNewLineInClosedRange(beforeBlockComment, afterBlockComment)) {\n // Do not try to fix constructs like below:\n // val foo = \"foo\" /*\n // some comment\n@@ -58,48 +79,57 @@ public class CommentWrappingRule :\n \"disallowed\",\n false,\n )\n+ } else if (beforeBlockComment.prevLeaf()?.elementType == LBRACE &&\n+ afterBlockComment.nextLeaf()?.elementType == RBRACE\n+ ) {\n+ // Allow single line blocks containing a block comment\n+ // val foo = { /* no-op */ }\n+ return\n } else {\n // Do not try to fix constructs like below:\n // val foo /* some comment */ = \"foo\"\n- emit(\n- node.startOffset,\n- \"A block comment in between other elements on the same line is disallowed\",\n- false,\n- )\n+ emit(node.startOffset, \"A block comment in between other elements on the same line is disallowed\", false)\n }\n return\n }\n \n- nonIndentLeafOnSameLinePrecedingBlockComment\n- ?.precedesBlockCommentOnSameLine(node, emit, autoCorrect)\n-\n- nonIndentLeafOnSameLineFollowingBlockComment\n- ?.followsBlockCommentOnSameLine(node, emit, autoCorrect)\n- }\n- }\n+ beforeBlockComment\n+ .prevLeaf()\n+ .takeIf { !it.isWhitespaceWithNewlineOrNull() }\n+ ?.let {\n+ if (node.textContains('\\n')) {\n+ // It can not be autocorrected as it might depend on the situation and code style what is preferred.\n+ emit(\n+ node.startOffset,\n+ \"A block comment after any other element on the same line must be separated by a new line\",\n+ false,\n+ )\n+ } else {\n+ emit(\n+ node.startOffset,\n+ \"A single line block comment after a code element on the same line must be replaced with an EOL comment\",\n+ true,\n+ )\n+ if (autoCorrect) {\n+ node.upsertWhitespaceBeforeMe(\" \")\n+ node.replaceWithEndOfLineComment()\n+ }\n+ }\n+ }\n \n- private fun ASTNode.precedesBlockCommentOnSameLine(\n- blockCommentNode: ASTNode,\n- emit: (offset: Int, errorMessage: String, canBeAutoCorrected: Boolean) -> Unit,\n- autoCorrect: Boolean,\n- ) {\n- val leafAfterBlockComment = blockCommentNode.nextLeaf()\n- if (!blockCommentNode.textContains('\\n') && leafAfterBlockComment.isLastElementOnLine()) {\n- emit(\n- startOffset,\n- \"A single line block comment after a code element on the same line must be replaced with an EOL comment\",\n- true,\n- )\n- if (autoCorrect) {\n- blockCommentNode.replaceWithEndOfLineComment()\n- }\n- } else {\n- // It can not be autocorrected as it might depend on the situation and code style what is preferred.\n- emit(\n- blockCommentNode.startOffset,\n- \"A block comment after any other element on the same line must be separated by a new line\",\n- false,\n- )\n+ afterBlockComment\n+ .nextLeaf()\n+ .takeIf { !it.isWhitespaceWithNewlineOrNull() }\n+ ?.let { nextLeaf ->\n+ emit(\n+ nextLeaf.startOffset,\n+ \"A block comment may not be followed by any other element on that same line\",\n+ true,\n+ )\n+ if (autoCorrect) {\n+ nextLeaf.upsertWhitespaceBeforeMe(node.indent())\n+ }\n+ }\n }\n }\n \n@@ -110,20 +140,17 @@ public class CommentWrappingRule :\n rawRemove()\n }\n \n- private fun ASTNode.followsBlockCommentOnSameLine(\n- blockCommentNode: ASTNode,\n- emit: (offset: Int, errorMessage: String, canBeAutoCorrected: Boolean) -> Unit,\n- autoCorrect: Boolean,\n- ) {\n- emit(startOffset, \"A block comment may not be followed by any other element on that same line\", true)\n- if (autoCorrect) {\n- this.upsertWhitespaceBeforeMe(blockCommentNode.indent())\n- }\n- }\n-\n- private fun isNonIndentLeafOnSameLine(it: ASTNode) = it.elementType != WHITE_SPACE || !it.textContains('\\n')\n+ private fun ASTNode?.isWhitespaceWithNewlineOrNull() = this == null || this.isWhiteSpaceWithNewline()\n \n- private fun ASTNode?.isLastElementOnLine() = this == null || (elementType == WHITE_SPACE && textContains('\\n'))\n+ // TODO: Remove when ktlint suppression directive in comments are no longer supported\n+ private fun ASTNode?.isKtlintSuppressionDirective() =\n+ this\n+ ?.text\n+ ?.removePrefix(\"/*\")\n+ ?.removeSuffix(\"*/\")\n+ ?.trim()\n+ ?.let { it.startsWith(\"ktlint-enable\") || it.startsWith(\"ktlint-disable\") }\n+ ?: false\n }\n \n public val COMMENT_WRAPPING_RULE_ID: RuleId = CommentWrappingRule().ruleId\ndiff --git a/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/ContextReceiverWrappingRule.kt b/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/ContextReceiverWrappingRule.kt\nindex 4966641856..d8243bf38b 100644\n--- a/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/ContextReceiverWrappingRule.kt\n+++ b/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/ContextReceiverWrappingRule.kt\n@@ -48,10 +48,11 @@ public class ContextReceiverWrappingRule :\n private var maxLineLength = MAX_LINE_LENGTH_PROPERTY.defaultValue\n \n override fun beforeFirstNode(editorConfig: EditorConfig) {\n- indentConfig = IndentConfig(\n- indentStyle = editorConfig[INDENT_STYLE_PROPERTY],\n- tabWidth = editorConfig[INDENT_SIZE_PROPERTY],\n- )\n+ indentConfig =\n+ IndentConfig(\n+ indentStyle = editorConfig[INDENT_STYLE_PROPERTY],\n+ tabWidth = editorConfig[INDENT_SIZE_PROPERTY],\n+ )\n maxLineLength = editorConfig[MAX_LINE_LENGTH_PROPERTY]\n }\n \ndiff --git a/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/EnumWrappingRule.kt b/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/EnumWrappingRule.kt\nindex 48bec3a9fc..0a03345a44 100644\n--- a/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/EnumWrappingRule.kt\n+++ b/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/EnumWrappingRule.kt\n@@ -42,10 +42,11 @@ public class EnumWrappingRule :\n private var indentConfig = IndentConfig.DEFAULT_INDENT_CONFIG\n \n override fun beforeFirstNode(editorConfig: EditorConfig) {\n- indentConfig = IndentConfig(\n- indentStyle = editorConfig[INDENT_STYLE_PROPERTY],\n- tabWidth = editorConfig[INDENT_SIZE_PROPERTY],\n- )\n+ indentConfig =\n+ IndentConfig(\n+ indentStyle = editorConfig[INDENT_STYLE_PROPERTY],\n+ tabWidth = editorConfig[INDENT_SIZE_PROPERTY],\n+ )\n }\n \n override fun beforeVisitChildNodes(\ndiff --git a/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/FunctionSignatureRule.kt b/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/FunctionSignatureRule.kt\nindex 4b2eb8a844..35af2368b5 100644\n--- a/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/FunctionSignatureRule.kt\n+++ b/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/FunctionSignatureRule.kt\n@@ -76,14 +76,13 @@ public class FunctionSignatureRule :\n \n override fun beforeFirstNode(editorConfig: EditorConfig) {\n codeStyle = editorConfig[CODE_STYLE_PROPERTY]\n- functionSignatureWrappingMinimumParameters = editorConfig[\n- FORCE_MULTILINE_WHEN_PARAMETER_COUNT_GREATER_OR_EQUAL_THAN_PROPERTY,\n- ]\n+ functionSignatureWrappingMinimumParameters = editorConfig[FORCE_MULTILINE_WHEN_PARAMETER_COUNT_GREATER_OR_EQUAL_THAN_PROPERTY]\n functionBodyExpressionWrapping = editorConfig[FUNCTION_BODY_EXPRESSION_WRAPPING_PROPERTY]\n- indentConfig = IndentConfig(\n- indentStyle = editorConfig[INDENT_STYLE_PROPERTY],\n- tabWidth = editorConfig[INDENT_SIZE_PROPERTY],\n- )\n+ indentConfig =\n+ IndentConfig(\n+ indentStyle = editorConfig[INDENT_STYLE_PROPERTY],\n+ tabWidth = editorConfig[INDENT_SIZE_PROPERTY],\n+ )\n maxLineLength = editorConfig[MAX_LINE_LENGTH_PROPERTY]\n }\n \n@@ -275,14 +274,15 @@ public class FunctionSignatureRule :\n .children()\n .firstOrNull { it.elementType == VALUE_PARAMETER }\n \n- whiteSpaceCorrection += if (firstParameterInList == null) {\n- // handle empty parameter list\n- fixWhiteSpacesInEmptyValueParameterList(node, emit, autoCorrect, dryRun)\n- } else {\n- fixWhiteSpacesBeforeFirstParameterInValueParameterList(node, emit, autoCorrect, multiline, dryRun) +\n- fixWhiteSpacesBetweenParametersInValueParameterList(node, emit, autoCorrect, multiline, dryRun) +\n- fixWhiteSpaceBeforeClosingParenthesis(node, emit, autoCorrect, multiline, dryRun)\n- }\n+ whiteSpaceCorrection +=\n+ if (firstParameterInList == null) {\n+ // handle empty parameter list\n+ fixWhiteSpacesInEmptyValueParameterList(node, emit, autoCorrect, dryRun)\n+ } else {\n+ fixWhiteSpacesBeforeFirstParameterInValueParameterList(node, emit, autoCorrect, multiline, dryRun) +\n+ fixWhiteSpacesBetweenParametersInValueParameterList(node, emit, autoCorrect, multiline, dryRun) +\n+ fixWhiteSpaceBeforeClosingParenthesis(node, emit, autoCorrect, multiline, dryRun)\n+ }\n \n return whiteSpaceCorrection\n }\ndiff --git a/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/IfElseBracingRule.kt b/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/IfElseBracingRule.kt\nindex 765c62c1ed..83aaf36752 100644\n--- a/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/IfElseBracingRule.kt\n+++ b/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/IfElseBracingRule.kt\n@@ -45,10 +45,11 @@ public class IfElseBracingRule :\n private var indentConfig = IndentConfig.DEFAULT_INDENT_CONFIG\n \n override fun beforeFirstNode(editorConfig: EditorConfig) {\n- indentConfig = IndentConfig(\n- indentStyle = editorConfig[INDENT_STYLE_PROPERTY],\n- tabWidth = editorConfig[INDENT_SIZE_PROPERTY],\n- )\n+ indentConfig =\n+ IndentConfig(\n+ indentStyle = editorConfig[INDENT_STYLE_PROPERTY],\n+ tabWidth = editorConfig[INDENT_SIZE_PROPERTY],\n+ )\n }\n \n override fun beforeVisitChildNodes(\ndiff --git a/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/IfElseWrappingRule.kt b/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/IfElseWrappingRule.kt\nindex e20ed2b62b..9fe2288275 100644\n--- a/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/IfElseWrappingRule.kt\n+++ b/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/IfElseWrappingRule.kt\n@@ -46,10 +46,11 @@ public class IfElseWrappingRule :\n private var indentConfig = IndentConfig.DEFAULT_INDENT_CONFIG\n \n override fun beforeFirstNode(editorConfig: EditorConfig) {\n- indentConfig = IndentConfig(\n- indentStyle = editorConfig[INDENT_STYLE_PROPERTY],\n- tabWidth = editorConfig[INDENT_SIZE_PROPERTY],\n- )\n+ indentConfig =\n+ IndentConfig(\n+ indentStyle = editorConfig[INDENT_STYLE_PROPERTY],\n+ tabWidth = editorConfig[INDENT_SIZE_PROPERTY],\n+ )\n }\n \n override fun beforeVisitChildNodes(\ndiff --git a/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/IndentationRule.kt b/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/IndentationRule.kt\nindex b91c6b6bb2..81142c414f 100644\n--- a/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/IndentationRule.kt\n+++ b/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/IndentationRule.kt\n@@ -55,6 +55,7 @@ import com.pinterest.ktlint.rule.engine.core.api.ElementType.RBRACE\n import com.pinterest.ktlint.rule.engine.core.api.ElementType.RBRACKET\n import com.pinterest.ktlint.rule.engine.core.api.ElementType.REFERENCE_EXPRESSION\n import com.pinterest.ktlint.rule.engine.core.api.ElementType.REGULAR_STRING_PART\n+import com.pinterest.ktlint.rule.engine.core.api.ElementType.RETURN_KEYWORD\n import com.pinterest.ktlint.rule.engine.core.api.ElementType.RPAR\n import com.pinterest.ktlint.rule.engine.core.api.ElementType.SAFE_ACCESS_EXPRESSION\n import com.pinterest.ktlint.rule.engine.core.api.ElementType.SECONDARY_CONSTRUCTOR\n@@ -93,6 +94,7 @@ import com.pinterest.ktlint.rule.engine.core.api.editorconfig.EditorConfig\n import com.pinterest.ktlint.rule.engine.core.api.editorconfig.INDENT_SIZE_PROPERTY\n import com.pinterest.ktlint.rule.engine.core.api.editorconfig.INDENT_STYLE_PROPERTY\n import com.pinterest.ktlint.rule.engine.core.api.firstChildLeafOrSelf\n+import com.pinterest.ktlint.rule.engine.core.api.indent\n import com.pinterest.ktlint.rule.engine.core.api.isPartOfComment\n import com.pinterest.ktlint.rule.engine.core.api.isRoot\n import com.pinterest.ktlint.rule.engine.core.api.isWhiteSpace\n@@ -105,6 +107,7 @@ import com.pinterest.ktlint.rule.engine.core.api.nextLeaf\n import com.pinterest.ktlint.rule.engine.core.api.nextSibling\n import com.pinterest.ktlint.rule.engine.core.api.parent\n import com.pinterest.ktlint.rule.engine.core.api.prevCodeLeaf\n+import com.pinterest.ktlint.rule.engine.core.api.prevCodeSibling\n import com.pinterest.ktlint.rule.engine.core.api.prevLeaf\n import com.pinterest.ktlint.rule.engine.core.api.prevSibling\n import com.pinterest.ktlint.ruleset.standard.StandardRule\n@@ -157,10 +160,11 @@ public class IndentationRule :\n \n override fun beforeFirstNode(editorConfig: EditorConfig) {\n codeStyle = editorConfig[CODE_STYLE_PROPERTY]\n- indentConfig = IndentConfig(\n- indentStyle = editorConfig[INDENT_STYLE_PROPERTY],\n- tabWidth = editorConfig[INDENT_SIZE_PROPERTY],\n- )\n+ indentConfig =\n+ IndentConfig(\n+ indentStyle = editorConfig[INDENT_STYLE_PROPERTY],\n+ tabWidth = editorConfig[INDENT_SIZE_PROPERTY],\n+ )\n if (indentConfig.disabled) {\n stopTraversalOfAST()\n }\n@@ -280,6 +284,8 @@ public class IndentationRule :\n fromAstNode = node.treeParent,\n toAstNode = node.treeParent.treeParent.lastChildLeafOrSelf(),\n )\n+ } else if (node.prevCodeSibling().isElvisOperator()) {\n+ startIndentContext(node)\n } else if (node.treeParent.elementType in CHAINABLE_EXPRESSION) {\n // Multiple dot qualified expressions and/or safe expression on the same line should not increase the indent level\n } else {\n@@ -376,10 +382,11 @@ public class IndentationRule :\n node\n .findChildByType(ELSE)\n ?.let { fromAstNode ->\n- nextToAstNode = startIndentContext(\n- fromAstNode = fromAstNode,\n- toAstNode = nextToAstNode,\n- ).prevCodeLeaf()\n+ nextToAstNode =\n+ startIndentContext(\n+ fromAstNode = fromAstNode,\n+ toAstNode = nextToAstNode,\n+ ).prevCodeLeaf()\n }\n \n node\n@@ -387,20 +394,22 @@ public class IndentationRule :\n ?.lastChildLeafOrSelf()\n ?.nextLeaf()\n ?.let { nodeAfterThenBlock ->\n- nextToAstNode = startIndentContext(\n- fromAstNode = nodeAfterThenBlock,\n- toAstNode = nextToAstNode,\n- childIndent = \"\",\n- ).prevCodeLeaf()\n+ nextToAstNode =\n+ startIndentContext(\n+ fromAstNode = nodeAfterThenBlock,\n+ toAstNode = nextToAstNode,\n+ childIndent = \"\",\n+ ).prevCodeLeaf()\n }\n node\n .findChildByType(RPAR)\n ?.nextCodeLeaf()\n ?.let { nodeAfterConditionBlock ->\n- nextToAstNode = startIndentContext(\n- fromAstNode = nodeAfterConditionBlock,\n- toAstNode = nextToAstNode,\n- ).prevCodeLeaf()\n+ nextToAstNode =\n+ startIndentContext(\n+ fromAstNode = nodeAfterConditionBlock,\n+ toAstNode = nextToAstNode,\n+ ).prevCodeLeaf()\n }\n startIndentContext(\n fromAstNode = node,\n@@ -489,10 +498,11 @@ public class IndentationRule :\n node\n .findChildByType(EQ)\n ?.let { fromAstNode ->\n- nextToAstNode = startIndentContext(\n- fromAstNode = fromAstNode,\n- toAstNode = nextToAstNode,\n- ).prevCodeLeaf()\n+ nextToAstNode =\n+ startIndentContext(\n+ fromAstNode = fromAstNode,\n+ toAstNode = nextToAstNode,\n+ ).prevCodeLeaf()\n }\n \n if (codeStyle == ktlint_official) {\n@@ -504,10 +514,11 @@ public class IndentationRule :\n node\n .findChildByType(COLON)\n ?.let { fromAstNode ->\n- nextToAstNode = startIndentContext(\n- fromAstNode = fromAstNode,\n- toAstNode = nextToAstNode,\n- ).prevCodeLeaf()\n+ nextToAstNode =\n+ startIndentContext(\n+ fromAstNode = fromAstNode,\n+ toAstNode = nextToAstNode,\n+ ).prevCodeLeaf()\n }\n }\n \n@@ -537,19 +548,21 @@ public class IndentationRule :\n node.findChildByType(EQ)\n ?: node.findChildByType(BLOCK)\n eqOrBlock?.let {\n- nextToAstNode = startIndentContext(\n- fromAstNode = eqOrBlock,\n- toAstNode = nextToAstNode,\n- ).prevCodeLeaf()\n+ nextToAstNode =\n+ startIndentContext(\n+ fromAstNode = eqOrBlock,\n+ toAstNode = nextToAstNode,\n+ ).prevCodeLeaf()\n }\n \n node\n .findChildByType(TYPE_REFERENCE)\n ?.let { typeReference ->\n- nextToAstNode = startIndentContext(\n- fromAstNode = typeReference.getPrecedingLeadingCommentsAndWhitespaces(),\n- toAstNode = nextToAstNode,\n- ).prevCodeLeaf()\n+ nextToAstNode =\n+ startIndentContext(\n+ fromAstNode = typeReference.getPrecedingLeadingCommentsAndWhitespaces(),\n+ toAstNode = nextToAstNode,\n+ ).prevCodeLeaf()\n }\n \n // Leading annotations and comments should be indented at same level as function itself\n@@ -573,27 +586,30 @@ public class IndentationRule :\n require(\n typeConstraintList.elementType == TYPE_CONSTRAINT_LIST,\n ) { \"Code sibling after WHERE in CLASS is not a TYPE_CONSTRAINT_LIST\" }\n- nextToAstNode = startIndentContext(\n- fromAstNode = where.getPrecedingLeadingCommentsAndWhitespaces(),\n- toAstNode = typeConstraintList.lastChildLeafOrSelf(),\n- ).prevCodeLeaf()\n+ nextToAstNode =\n+ startIndentContext(\n+ fromAstNode = where.getPrecedingLeadingCommentsAndWhitespaces(),\n+ toAstNode = typeConstraintList.lastChildLeafOrSelf(),\n+ ).prevCodeLeaf()\n }\n \n val primaryConstructor = node.findChildByType(PRIMARY_CONSTRUCTOR)\n if (codeStyle == ktlint_official && primaryConstructor != null) {\n // Indent both constructor and super type list\n- nextToAstNode = startIndentContext(\n- fromAstNode = primaryConstructor.getPrecedingLeadingCommentsAndWhitespaces(),\n- toAstNode = nextToAstNode,\n- ).prevCodeLeaf()\n+ nextToAstNode =\n+ startIndentContext(\n+ fromAstNode = primaryConstructor.getPrecedingLeadingCommentsAndWhitespaces(),\n+ toAstNode = nextToAstNode,\n+ ).prevCodeLeaf()\n } else {\n node\n .findChildByType(SUPER_TYPE_LIST)\n ?.let { superTypeList ->\n- nextToAstNode = startIndentContext(\n- fromAstNode = superTypeList.getPrecedingLeadingCommentsAndWhitespaces(),\n- toAstNode = superTypeList.lastChildLeafOrSelf(),\n- ).prevCodeLeaf()\n+ nextToAstNode =\n+ startIndentContext(\n+ fromAstNode = superTypeList.getPrecedingLeadingCommentsAndWhitespaces(),\n+ toAstNode = superTypeList.lastChildLeafOrSelf(),\n+ ).prevCodeLeaf()\n }\n }\n \n@@ -611,10 +627,11 @@ public class IndentationRule :\n node\n .findChildByType(SUPER_TYPE_LIST)\n ?.let { superTypeList ->\n- nextToAstNode = startIndentContext(\n- fromAstNode = superTypeList.getPrecedingLeadingCommentsAndWhitespaces(),\n- toAstNode = superTypeList.lastChildLeafOrSelf(),\n- ).prevCodeLeaf()\n+ nextToAstNode =\n+ startIndentContext(\n+ fromAstNode = superTypeList.getPrecedingLeadingCommentsAndWhitespaces(),\n+ toAstNode = superTypeList.lastChildLeafOrSelf(),\n+ ).prevCodeLeaf()\n }\n \n // Leading annotations and comments should be indented at same level as class itself\n@@ -658,11 +675,12 @@ public class IndentationRule :\n node\n .findChildByType(LPAR)\n ?.let { lpar ->\n- nextToASTNode = startIndentContext(\n- fromAstNode = lpar,\n- toAstNode = node.findChildByType(RPAR)!!,\n- lastChildIndent = \"\",\n- ).prevCodeLeaf()\n+ nextToASTNode =\n+ startIndentContext(\n+ fromAstNode = lpar,\n+ toAstNode = node.findChildByType(RPAR)!!,\n+ lastChildIndent = \"\",\n+ ).prevCodeLeaf()\n }\n startIndentContext(\n fromAstNode = node,\n@@ -720,10 +738,11 @@ public class IndentationRule :\n node\n .findChildByType(EQ)\n ?.let { fromAstNode ->\n- nextToASTNode = startIndentContext(\n- fromAstNode = fromAstNode,\n- toAstNode = node.lastChildLeafOrSelf(),\n- ).prevCodeLeaf()\n+ nextToASTNode =\n+ startIndentContext(\n+ fromAstNode = fromAstNode,\n+ toAstNode = node.lastChildLeafOrSelf(),\n+ ).prevCodeLeaf()\n }\n // No indent on preceding annotations and comments\n startIndentContext(\n@@ -775,11 +794,12 @@ public class IndentationRule :\n node\n .findChildByType(RPAR)\n ?.let { fromAstNode ->\n- nextToAstNode = startIndentContext(\n- fromAstNode = fromAstNode,\n- toAstNode = nextToAstNode,\n- childIndent = \"\",\n- ).prevCodeLeaf()\n+ nextToAstNode =\n+ startIndentContext(\n+ fromAstNode = fromAstNode,\n+ toAstNode = nextToAstNode,\n+ childIndent = \"\",\n+ ).prevCodeLeaf()\n }\n startIndentContext(\n fromAstNode = node,\n@@ -793,10 +813,11 @@ public class IndentationRule :\n node\n .findChildByType(EQ)\n ?.let { eq ->\n- nextToAstNode = startIndentContext(\n- fromAstNode = eq,\n- toAstNode = nextToAstNode,\n- ).prevCodeLeaf()\n+ nextToAstNode =\n+ startIndentContext(\n+ fromAstNode = eq,\n+ toAstNode = nextToAstNode,\n+ ).prevCodeLeaf()\n }\n \n node\n@@ -816,21 +837,23 @@ public class IndentationRule :\n node\n .findChildByType(FINALLY)\n ?.let { finally ->\n- nextToAstNode = startIndentContext(\n- fromAstNode = finally,\n- toAstNode = nextToAstNode,\n- childIndent = \"\",\n- ).prevCodeLeaf()\n+ nextToAstNode =\n+ startIndentContext(\n+ fromAstNode = finally,\n+ toAstNode = nextToAstNode,\n+ childIndent = \"\",\n+ ).prevCodeLeaf()\n }\n \n node\n .findChildByType(CATCH)\n ?.let { catch ->\n- nextToAstNode = startIndentContext(\n- fromAstNode = catch,\n- toAstNode = nextToAstNode,\n- childIndent = \"\",\n- ).prevCodeLeaf()\n+ nextToAstNode =\n+ startIndentContext(\n+ fromAstNode = catch,\n+ toAstNode = nextToAstNode,\n+ childIndent = \"\",\n+ ).prevCodeLeaf()\n }\n \n startIndentContext(\n@@ -1065,6 +1088,11 @@ public class IndentationRule :\n stringTemplateIndenter.visitClosingQuotes(currentIndent(), node.treeParent, autoCorrect, emit)\n }\n \n+ private fun ASTNode?.isElvisOperator() =\n+ this != null &&\n+ elementType == OPERATION_REFERENCE &&\n+ firstChildNode.elementType == ELVIS\n+\n private fun ASTNode.acceptableTrailingSpaces(): String {\n require(elementType == WHITE_SPACE)\n val acceptableTrailingSpaces =\n@@ -1213,8 +1241,29 @@ private class StringTemplateIndenter(private val indentConfig: IndentConfig) {\n }\n \n val prefixLength = node.getCommonPrefixLength()\n+ val prevLeaf = node.prevLeaf()\n val correctedExpectedIndent =\n- if (node.prevLeaf()?.text == \"\\n\") {\n+ if (node.isRawStringLiteralReturnInFunctionBodyBlock()) {\n+ // Allow:\n+ // fun foo(): String {\n+ // return \"\"\"\n+ // some text\n+ // \"\"\".trimIndent\n+ // }\n+ node\n+ .indent(false)\n+ .plus(indentConfig.indent)\n+ } else if (node.isRawStringLiteralFunctionBodyExpression()) {\n+ // Allow:\n+ // fun foo(\n+ // bar: String\n+ // ) = \"\"\"\n+ // $bar\n+ // \"\"\".trimIndent\n+ node\n+ .indent(false)\n+ .plus(indentConfig.indent)\n+ } else if (prevLeaf?.text == \"\\n\") {\n // In case the opening quotes are placed at the start of the line, then the closing quotes\n // should have no indent as well.\n \"\"\n@@ -1277,6 +1326,16 @@ private class StringTemplateIndenter(private val indentConfig: IndentConfig) {\n }\n }\n \n+ private fun ASTNode.isRawStringLiteralFunctionBodyExpression() =\n+ (prevLeaf()?.elementType != WHITE_SPACE || prevLeaf()?.text == \" \") &&\n+ FUN ==\n+ prevCodeLeaf()\n+ .takeIf { it?.elementType == EQ }\n+ ?.treeParent\n+ ?.elementType\n+\n+ private fun ASTNode.isRawStringLiteralReturnInFunctionBodyBlock() = RETURN_KEYWORD == prevCodeLeaf()?.elementType\n+\n /**\n * Get the length of the indent which is shared by all lines inside the string template except for the indent of\n * the closing quotes.\ndiff --git a/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/MultiLineIfElseRule.kt b/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/MultiLineIfElseRule.kt\nindex 3fe1e6aee9..35c6745cfb 100644\n--- a/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/MultiLineIfElseRule.kt\n+++ b/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/MultiLineIfElseRule.kt\n@@ -43,10 +43,11 @@ public class MultiLineIfElseRule :\n private var indentConfig = IndentConfig.DEFAULT_INDENT_CONFIG\n \n override fun beforeFirstNode(editorConfig: EditorConfig) {\n- indentConfig = IndentConfig(\n- indentStyle = editorConfig[INDENT_STYLE_PROPERTY],\n- tabWidth = editorConfig[INDENT_SIZE_PROPERTY],\n- )\n+ indentConfig =\n+ IndentConfig(\n+ indentStyle = editorConfig[INDENT_STYLE_PROPERTY],\n+ tabWidth = editorConfig[INDENT_SIZE_PROPERTY],\n+ )\n }\n \n override fun beforeVisitChildNodes(\ndiff --git a/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/MultilineExpressionWrapping.kt b/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/MultilineExpressionWrapping.kt\nindex 7da4fa6ddf..186cced277 100644\n--- a/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/MultilineExpressionWrapping.kt\n+++ b/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/MultilineExpressionWrapping.kt\n@@ -14,6 +14,7 @@ import com.pinterest.ktlint.rule.engine.core.api.ElementType.FUN\n import com.pinterest.ktlint.rule.engine.core.api.ElementType.IF\n import com.pinterest.ktlint.rule.engine.core.api.ElementType.IS_EXPRESSION\n import com.pinterest.ktlint.rule.engine.core.api.ElementType.OBJECT_LITERAL\n+import com.pinterest.ktlint.rule.engine.core.api.ElementType.OPERATION_REFERENCE\n import com.pinterest.ktlint.rule.engine.core.api.ElementType.PREFIX_EXPRESSION\n import com.pinterest.ktlint.rule.engine.core.api.ElementType.REFERENCE_EXPRESSION\n import com.pinterest.ktlint.rule.engine.core.api.ElementType.RPAR\n@@ -31,8 +32,8 @@ import com.pinterest.ktlint.rule.engine.core.api.editorconfig.INDENT_STYLE_PROPE\n import com.pinterest.ktlint.rule.engine.core.api.firstChildLeafOrSelf\n import com.pinterest.ktlint.rule.engine.core.api.indent\n import com.pinterest.ktlint.rule.engine.core.api.isPartOfComment\n-import com.pinterest.ktlint.rule.engine.core.api.isWhiteSpace\n import com.pinterest.ktlint.rule.engine.core.api.isWhiteSpaceWithNewline\n+import com.pinterest.ktlint.rule.engine.core.api.isWhiteSpaceWithoutNewline\n import com.pinterest.ktlint.rule.engine.core.api.lastChildLeafOrSelf\n import com.pinterest.ktlint.rule.engine.core.api.leavesIncludingSelf\n import com.pinterest.ktlint.rule.engine.core.api.nextLeaf\n@@ -60,10 +61,11 @@ public class MultilineExpressionWrapping :\n private var indentConfig = DEFAULT_INDENT_CONFIG\n \n override fun beforeFirstNode(editorConfig: EditorConfig) {\n- indentConfig = IndentConfig(\n- indentStyle = editorConfig[INDENT_STYLE_PROPERTY],\n- tabWidth = editorConfig[INDENT_SIZE_PROPERTY],\n- )\n+ indentConfig =\n+ IndentConfig(\n+ indentStyle = editorConfig[INDENT_STYLE_PROPERTY],\n+ tabWidth = editorConfig[INDENT_SIZE_PROPERTY],\n+ )\n }\n \n override fun beforeVisitChildNodes(\n@@ -72,7 +74,7 @@ public class MultilineExpressionWrapping :\n emit: (offset: Int, errorMessage: String, canBeAutoCorrected: Boolean) -> Unit,\n ) {\n if (node.elementType in CHAINABLE_EXPRESSION &&\n- node.treeParent.elementType !in CHAINABLE_EXPRESSION\n+ (node.treeParent.elementType !in CHAINABLE_EXPRESSION || node.isRightHandSideOfBinaryExpression())\n ) {\n visitExpression(node, emit, autoCorrect)\n }\n@@ -103,7 +105,8 @@ public class MultilineExpressionWrapping :\n )\n node\n .lastChildLeafOrSelf()\n- .nextLeaf { !it.isWhiteSpace() && it.elementType != COMMA }\n+ .nextLeaf { !it.isWhiteSpaceWithoutNewline() && !it.isPartOfComment() && it.elementType != COMMA }\n+ ?.takeIf { !it.isWhiteSpaceWithNewline() }\n ?.upsertWhitespaceBeforeMe(node.treeParent.indent())\n }\n }\n@@ -132,13 +135,19 @@ public class MultilineExpressionWrapping :\n private fun ASTNode.isValueInAnAssignment() =\n null !=\n prevCodeSibling()\n- ?.takeIf { it.elementType == EQ }\n+ ?.takeIf { it.elementType == EQ || it.elementType == OPERATION_REFERENCE }\n+ ?.takeUnless { it.isElvisOperator() }\n ?.takeUnless {\n it.closingParenthesisOfFunctionOrNull()\n ?.prevLeaf()\n .isWhiteSpaceWithNewline()\n }\n \n+ private fun ASTNode?.isElvisOperator() =\n+ this != null &&\n+ elementType == OPERATION_REFERENCE &&\n+ firstChildNode.elementType == ElementType.ELVIS\n+\n private fun ASTNode.closingParenthesisOfFunctionOrNull() =\n takeIf { treeParent.elementType == FUN }\n ?.prevCodeLeaf()\n@@ -160,6 +169,11 @@ public class MultilineExpressionWrapping :\n \n private fun ASTNode.isAfterArrow() = prevCodeLeaf()?.elementType == ARROW\n \n+ private fun ASTNode.isRightHandSideOfBinaryExpression() =\n+ null !=\n+ takeIf { it.treeParent.elementType == BINARY_EXPRESSION }\n+ .takeIf { it?.prevCodeSibling()?.elementType == OPERATION_REFERENCE }\n+\n private companion object {\n // Based on https://kotlinlang.org/spec/expressions.html#expressions\n val CHAINABLE_EXPRESSION =\ndiff --git a/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/NoConsecutiveCommentsRule.kt b/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/NoConsecutiveCommentsRule.kt\nindex 4a8dc31ea4..660946e9a5 100644\n--- a/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/NoConsecutiveCommentsRule.kt\n+++ b/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/NoConsecutiveCommentsRule.kt\n@@ -11,6 +11,14 @@ import com.pinterest.ktlint.rule.engine.core.api.prevLeaf\n import com.pinterest.ktlint.ruleset.standard.StandardRule\n import org.jetbrains.kotlin.com.intellij.lang.ASTNode\n \n+/**\n+ * Consecutive comments should be disallowed in following cases:\n+ * - Any mix of a consecutive kdoc, a block comment or an EOL comment unless separated by a blank line in between\n+ * - Consecutive KDocs (even when separated by a blank line)\n+ * - Consecutive block comments (even when separated by a blank line)\n+ *\n+ * Consecutive EOL comments are always allowed as they are often used instead of a block comment.\n+ */\n public class NoConsecutiveCommentsRule :\n StandardRule(\"no-consecutive-comments\"),\n Rule.Experimental,\n@@ -20,21 +28,91 @@ public class NoConsecutiveCommentsRule :\n autoCorrect: Boolean,\n emit: (offset: Int, errorMessage: String, canBeAutoCorrected: Boolean) -> Unit,\n ) {\n- if (node.isStartOfComment()) {\n- node\n- .prevLeaf { !it.isWhiteSpace() }\n- ?.takeIf { previousNonWhiteSpace -> previousNonWhiteSpace.isEndOfComment() }\n- ?.takeUnless { previousNonWhiteSpace ->\n- // In is not uncommon that consecutive EOL comments are used instead of a block comment\n- previousNonWhiteSpace.elementType == EOL_COMMENT && node.elementType == EOL_COMMENT\n- }?.let { previousNonWhiteSpace ->\n- emit(\n- node.startOffset,\n- \"${node.commentType()} may not be preceded by ${previousNonWhiteSpace.commentType()}\",\n- false,\n- )\n+ node\n+ .takeIf { it.isStartOfComment() }\n+ ?.prevLeaf { !it.isWhiteSpace() }\n+ ?.takeIf { previousNonWhiteSpace -> previousNonWhiteSpace.isEndOfComment() }\n+ ?.let { previousComment ->\n+ when {\n+ previousComment.elementType == KDOC_END && node.elementType == KDOC_START -> {\n+ // Disallow consecutive KDocs (even when separated by a blank line):\n+ // /**\n+ // * KDoc 1\n+ // */\n+ //\n+ // /**\n+ // * KDoc 2\n+ // */\n+ // Disallow block and eol comments preceded by a KDOC (even when separated by a blank line):\n+ // /**\n+ // * KDoc 1\n+ // */\n+ //\n+ // //\n+ emit(\n+ node.startOffset,\n+ \"${node.commentType()} may not be preceded by ${previousComment.commentType()}\",\n+ false,\n+ )\n+ true\n+ }\n+\n+ previousComment.elementType == KDOC_END && node.elementType != KDOC_START -> {\n+ // Disallow block and eol comments preceded by a KDOC (even when separated by a blank line):\n+ // /**\n+ // * KDoc 1\n+ // */\n+ //\n+ // //\n+ emit(\n+ node.startOffset,\n+ \"${node.commentType()} may not be preceded by ${previousComment.commentType()}. Reversed order is allowed \" +\n+ \"though when separated by a newline.\",\n+ false,\n+ )\n+ true\n+ }\n+\n+ previousComment.elementType == BLOCK_COMMENT && node.elementType == BLOCK_COMMENT -> {\n+ // Disallow consecutive block comments (even when separated by a blank line):\n+ // /*\n+ // * Block comment 1\n+ // */\n+ //\n+ // /**\n+ // * Block comment 2\n+ // */\n+ emit(\n+ node.startOffset,\n+ \"${node.commentType()} may not be preceded by ${previousComment.commentType()}\",\n+ false,\n+ )\n+ }\n+\n+ previousComment.elementType == EOL_COMMENT && node.elementType == EOL_COMMENT -> {\n+ // Allow consecutive EOL-comments:\n+ // // EOL-comment 1\n+ // // EOL-comment 2\n+ false\n+ }\n+\n+ previousComment.elementType != node.elementType && node.prevLeaf().takeIf { it.isWhiteSpace() }?.text.orEmpty()\n+ .count { it == '\\n' } > 1 -> {\n+ // Allow different element types when separated by a blank line\n+ false\n+ }\n+\n+ else -> {\n+ emit(\n+ node.startOffset,\n+ \"${node.commentType()} may not be preceded by ${previousComment.commentType()} unless separated by a blank \" +\n+ \"line\",\n+ false,\n+ )\n+ }\n }\n- }\n+ }\n+ ?: false\n }\n \n private fun ASTNode?.isStartOfComment() =\ndiff --git a/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/NoEmptyFirstLineInClassBodyRule.kt b/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/NoEmptyFirstLineInClassBodyRule.kt\nindex 08e8f2ae70..02e9108a87 100644\n--- a/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/NoEmptyFirstLineInClassBodyRule.kt\n+++ b/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/NoEmptyFirstLineInClassBodyRule.kt\n@@ -28,10 +28,11 @@ public class NoEmptyFirstLineInClassBodyRule :\n private var indentConfig = IndentConfig.DEFAULT_INDENT_CONFIG\n \n override fun beforeFirstNode(editorConfig: EditorConfig) {\n- indentConfig = IndentConfig(\n- indentStyle = editorConfig[INDENT_STYLE_PROPERTY],\n- tabWidth = editorConfig[INDENT_SIZE_PROPERTY],\n- )\n+ indentConfig =\n+ IndentConfig(\n+ indentStyle = editorConfig[INDENT_STYLE_PROPERTY],\n+ tabWidth = editorConfig[INDENT_SIZE_PROPERTY],\n+ )\n }\n \n override fun beforeVisitChildNodes(\ndiff --git a/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/ParameterListSpacingRule.kt b/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/ParameterListSpacingRule.kt\nindex 23b114c87b..a16bd83ac5 100644\n--- a/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/ParameterListSpacingRule.kt\n+++ b/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/ParameterListSpacingRule.kt\n@@ -4,6 +4,7 @@ import com.pinterest.ktlint.rule.engine.core.api.ElementType.ANNOTATION_ENTRY\n import com.pinterest.ktlint.rule.engine.core.api.ElementType.COLON\n import com.pinterest.ktlint.rule.engine.core.api.ElementType.COMMA\n import com.pinterest.ktlint.rule.engine.core.api.ElementType.MODIFIER_LIST\n+import com.pinterest.ktlint.rule.engine.core.api.ElementType.TYPE_REFERENCE\n import com.pinterest.ktlint.rule.engine.core.api.ElementType.VALUE_PARAMETER\n import com.pinterest.ktlint.rule.engine.core.api.ElementType.VALUE_PARAMETER_LIST\n import com.pinterest.ktlint.rule.engine.core.api.ElementType.WHITE_SPACE\n@@ -190,8 +191,18 @@ public class ParameterListSpacingRule :\n .let { whiteSpaceAfterColon ->\n if (whiteSpaceAfterColon == null) {\n addMissingWhiteSpaceAfterMe(colonNode, emit, autoCorrect)\n- } else if (whiteSpaceAfterColon.isIndent() || whiteSpaceAfterColon.isNotSingleSpace()) {\n- replaceWithSingleSpace(whiteSpaceAfterColon, emit, autoCorrect)\n+ } else {\n+ if (node.isTypeReferenceWithModifierList() && whiteSpaceAfterColon.isIndent()) {\n+ // Allow the type to be wrapped to the next line when it has a modifier:\n+ // data class Foo(\n+ // val bar:\n+ // @FooBar(\"foobar\")\n+ // Bar,\n+ // )\n+ Unit\n+ } else if (whiteSpaceAfterColon.isNotSingleSpace()) {\n+ replaceWithSingleSpace(whiteSpaceAfterColon, emit, autoCorrect)\n+ }\n }\n }\n }\n@@ -253,6 +264,12 @@ public class ParameterListSpacingRule :\n }\n }\n }\n+\n+ private fun ASTNode?.isTypeReferenceWithModifierList() =\n+ null !=\n+ this\n+ ?.findChildByType(TYPE_REFERENCE)\n+ ?.findChildByType(MODIFIER_LIST)\n }\n \n public val PARAMETER_LIST_SPACING_RULE_ID: RuleId = ParameterListSpacingRule().ruleId\ndiff --git a/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/ParameterListWrappingRule.kt b/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/ParameterListWrappingRule.kt\nindex fc45fa3ca6..840d0c48c1 100644\n--- a/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/ParameterListWrappingRule.kt\n+++ b/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/ParameterListWrappingRule.kt\n@@ -52,10 +52,11 @@ public class ParameterListWrappingRule :\n override fun beforeFirstNode(editorConfig: EditorConfig) {\n codeStyle = editorConfig[CODE_STYLE_PROPERTY]\n maxLineLength = editorConfig[MAX_LINE_LENGTH_PROPERTY]\n- indentConfig = IndentConfig(\n- indentStyle = editorConfig[INDENT_STYLE_PROPERTY],\n- tabWidth = editorConfig[INDENT_SIZE_PROPERTY],\n- )\n+ indentConfig =\n+ IndentConfig(\n+ indentStyle = editorConfig[INDENT_STYLE_PROPERTY],\n+ tabWidth = editorConfig[INDENT_SIZE_PROPERTY],\n+ )\n if (indentConfig.disabled) {\n stopTraversalOfAST()\n }\ndiff --git a/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/ParameterWrappingRule.kt b/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/ParameterWrappingRule.kt\nindex 530f53ebc8..e61640ceff 100644\n--- a/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/ParameterWrappingRule.kt\n+++ b/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/ParameterWrappingRule.kt\n@@ -55,10 +55,11 @@ public class ParameterWrappingRule :\n \n override fun beforeFirstNode(editorConfig: EditorConfig) {\n line = 1\n- indentConfig = IndentConfig(\n- indentStyle = editorConfig[INDENT_STYLE_PROPERTY],\n- tabWidth = editorConfig[INDENT_SIZE_PROPERTY],\n- )\n+ indentConfig =\n+ IndentConfig(\n+ indentStyle = editorConfig[INDENT_STYLE_PROPERTY],\n+ tabWidth = editorConfig[INDENT_SIZE_PROPERTY],\n+ )\n maxLineLength = editorConfig[MAX_LINE_LENGTH_PROPERTY]\n }\n \ndiff --git a/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/PropertyWrappingRule.kt b/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/PropertyWrappingRule.kt\nindex 227ec7e31b..9660b9391b 100644\n--- a/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/PropertyWrappingRule.kt\n+++ b/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/PropertyWrappingRule.kt\n@@ -53,10 +53,11 @@ public class PropertyWrappingRule :\n \n override fun beforeFirstNode(editorConfig: EditorConfig) {\n line = 1\n- indentConfig = IndentConfig(\n- indentStyle = editorConfig[INDENT_STYLE_PROPERTY],\n- tabWidth = editorConfig[INDENT_SIZE_PROPERTY],\n- )\n+ indentConfig =\n+ IndentConfig(\n+ indentStyle = editorConfig[INDENT_STYLE_PROPERTY],\n+ tabWidth = editorConfig[INDENT_SIZE_PROPERTY],\n+ )\n maxLineLength = editorConfig[MAX_LINE_LENGTH_PROPERTY]\n }\n \ndiff --git a/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/TryCatchFinallySpacingRule.kt b/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/TryCatchFinallySpacingRule.kt\nindex f4aa7e89de..5539075dd4 100644\n--- a/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/TryCatchFinallySpacingRule.kt\n+++ b/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/TryCatchFinallySpacingRule.kt\n@@ -40,10 +40,11 @@ public class TryCatchFinallySpacingRule :\n private var indentConfig = DEFAULT_INDENT_CONFIG\n \n override fun beforeFirstNode(editorConfig: EditorConfig) {\n- indentConfig = IndentConfig(\n- indentStyle = editorConfig[INDENT_STYLE_PROPERTY],\n- tabWidth = editorConfig[INDENT_SIZE_PROPERTY],\n- )\n+ indentConfig =\n+ IndentConfig(\n+ indentStyle = editorConfig[INDENT_STYLE_PROPERTY],\n+ tabWidth = editorConfig[INDENT_SIZE_PROPERTY],\n+ )\n }\n \n override fun beforeVisitChildNodes(\ndiff --git a/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/TypeArgumentListSpacingRule.kt b/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/TypeArgumentListSpacingRule.kt\nindex 7cef327593..3254060451 100644\n--- a/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/TypeArgumentListSpacingRule.kt\n+++ b/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/TypeArgumentListSpacingRule.kt\n@@ -37,10 +37,11 @@ public class TypeArgumentListSpacingRule :\n private var indentConfig = IndentConfig.DEFAULT_INDENT_CONFIG\n \n override fun beforeFirstNode(editorConfig: EditorConfig) {\n- indentConfig = IndentConfig(\n- indentStyle = editorConfig[INDENT_STYLE_PROPERTY],\n- tabWidth = editorConfig[INDENT_SIZE_PROPERTY],\n- )\n+ indentConfig =\n+ IndentConfig(\n+ indentStyle = editorConfig[INDENT_STYLE_PROPERTY],\n+ tabWidth = editorConfig[INDENT_SIZE_PROPERTY],\n+ )\n }\n \n override fun beforeVisitChildNodes(\ndiff --git a/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/TypeParameterListSpacingRule.kt b/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/TypeParameterListSpacingRule.kt\nindex 776315edd2..982636b515 100644\n--- a/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/TypeParameterListSpacingRule.kt\n+++ b/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/TypeParameterListSpacingRule.kt\n@@ -44,10 +44,11 @@ public class TypeParameterListSpacingRule :\n private var indentConfig = IndentConfig.DEFAULT_INDENT_CONFIG\n \n override fun beforeFirstNode(editorConfig: EditorConfig) {\n- indentConfig = IndentConfig(\n- indentStyle = editorConfig[INDENT_STYLE_PROPERTY],\n- tabWidth = editorConfig[INDENT_SIZE_PROPERTY],\n- )\n+ indentConfig =\n+ IndentConfig(\n+ indentStyle = editorConfig[INDENT_STYLE_PROPERTY],\n+ tabWidth = editorConfig[INDENT_SIZE_PROPERTY],\n+ )\n }\n \n override fun beforeVisitChildNodes(\n@@ -87,11 +88,21 @@ public class TypeParameterListSpacingRule :\n ?.takeIf { it.elementType == WHITE_SPACE && it.nextCodeSibling()?.elementType == PRIMARY_CONSTRUCTOR }\n ?.let { whiteSpace ->\n if (whiteSpace.nextCodeSibling()?.findChildByType(CONSTRUCTOR_KEYWORD) != null) {\n- // Single space expect before (modifier list of) constructor\n+ // Single space or newline expected before (modifier list of) constructor\n // class Bar constructor(...)\n // class Bar actual constructor(...)\n // class Bar @SomeAnnotation constructor(...)\n- singleSpaceExpected(whiteSpace, autoCorrect, emit)\n+ if (whiteSpace.text != \" \" && whiteSpace.text != node.indent().plus(indentConfig.indent)) {\n+ emit(\n+ whiteSpace.startOffset,\n+ \"Expected a single space or newline (with indent)\",\n+ true,\n+ )\n+ if (autoCorrect) {\n+ // If line is to be wrapped this should have been done by other rules before running this rule\n+ whiteSpace.upsertWhitespaceBeforeMe(\" \")\n+ }\n+ }\n } else {\n visitWhitespace(whiteSpace, autoCorrect, emit)\n }\ndiff --git a/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/WrappingRule.kt b/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/WrappingRule.kt\nindex d4bdd6eaeb..7dd875e546 100644\n--- a/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/WrappingRule.kt\n+++ b/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/WrappingRule.kt\n@@ -114,10 +114,11 @@ public class WrappingRule :\n \n override fun beforeFirstNode(editorConfig: EditorConfig) {\n line = 1\n- indentConfig = IndentConfig(\n- indentStyle = editorConfig[INDENT_STYLE_PROPERTY],\n- tabWidth = editorConfig[INDENT_SIZE_PROPERTY],\n- )\n+ indentConfig =\n+ IndentConfig(\n+ indentStyle = editorConfig[INDENT_STYLE_PROPERTY],\n+ tabWidth = editorConfig[INDENT_SIZE_PROPERTY],\n+ )\n maxLineLength = editorConfig[MAX_LINE_LENGTH_PROPERTY]\n }\n \ndiff --git a/mkdocs.yml b/mkdocs.yml\nindex a1860280f3..27b0cba4e6 100644\n--- a/mkdocs.yml\n+++ b/mkdocs.yml\n@@ -38,6 +38,7 @@ nav:\n # - API: install/api.md TODO: properly document\n - Snapshot build: install/snapshot-build.md\n - Rules:\n+ - Code styles: rules/code-styles.md\n - Standard rules: rules/standard.md\n - Experimental rules: rules/experimental.md\n - Dependencies: rules/dependencies.md\n", "test_patch": "diff --git a/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/AnnotationRuleTest.kt b/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/AnnotationRuleTest.kt\nindex c7d12357c7..f11f15aa17 100644\n--- a/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/AnnotationRuleTest.kt\n+++ b/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/AnnotationRuleTest.kt\n@@ -957,4 +957,18 @@ class AnnotationRuleTest {\n LintViolation(5, 44, \"Expected newline\"),\n ).isFormattedAs(formattedCode)\n }\n+\n+ @Test\n+ fun `Given a try-finally containing an annotated expression`() {\n+ val code =\n+ \"\"\"\n+ val foo = try {\n+ @Bar(\"bar\")\n+ bar()\n+ } finally {\n+ // something\n+ }\n+ \"\"\".trimIndent()\n+ annotationRuleAssertThat(code).hasNoLintViolations()\n+ }\n }\ndiff --git a/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/ClassNamingRuleTest.kt b/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/ClassNamingRuleTest.kt\nindex 59bbfbd5c7..ceef40e56f 100644\n--- a/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/ClassNamingRuleTest.kt\n+++ b/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/ClassNamingRuleTest.kt\n@@ -33,12 +33,9 @@ class ClassNamingRuleTest {\n \"\"\"\n class $className\n \"\"\".trimIndent()\n+ @Suppress(\"ktlint:argument-list-wrapping\", \"ktlint:max-line-length\")\n classNamingRuleAssertThat(code)\n- .hasLintViolationWithoutAutoCorrect(\n- 1,\n- 7,\n- \"Class or object name should start with an uppercase letter and use camel case\",\n- )\n+ .hasLintViolationWithoutAutoCorrect(1, 7, \"Class or object name should start with an uppercase letter and use camel case\")\n }\n \n @Nested\n@@ -49,12 +46,9 @@ class ClassNamingRuleTest {\n \"\"\"\n class `foo`\n \"\"\".trimIndent()\n+ @Suppress(\"ktlint:argument-list-wrapping\", \"ktlint:max-line-length\")\n classNamingRuleAssertThat(code)\n- .hasLintViolationWithoutAutoCorrect(\n- 1,\n- 7,\n- \"Class or object name should start with an uppercase letter and use camel case\",\n- )\n+ .hasLintViolationWithoutAutoCorrect(1, 7, \"Class or object name should start with an uppercase letter and use camel case\")\n }\n \n @Test\ndiff --git a/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/CommentWrappingRuleTest.kt b/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/CommentWrappingRuleTest.kt\nindex c89e598371..6ee2f51716 100644\n--- a/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/CommentWrappingRuleTest.kt\n+++ b/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/CommentWrappingRuleTest.kt\n@@ -1,19 +1,32 @@\n package com.pinterest.ktlint.ruleset.standard.rules\n \n+import com.pinterest.ktlint.rule.engine.core.api.editorconfig.CODE_STYLE_PROPERTY\n+import com.pinterest.ktlint.rule.engine.core.api.editorconfig.CodeStyleValue.ktlint_official\n import com.pinterest.ktlint.test.KtLintAssertThat.Companion.assertThatRule\n-import com.pinterest.ktlint.test.LintViolation\n+import org.junit.jupiter.api.Nested\n import org.junit.jupiter.api.Test\n \n class CommentWrappingRuleTest {\n private val commentWrappingRuleAssertThat = assertThatRule { CommentWrappingRule() }\n \n @Test\n- fun `Given a single line block comment that start starts and end on a separate line then do not reformat`() {\n+ fun `Given a single line block comment then replace it with an EOL comment`() {\n val code =\n \"\"\"\n- /* Some comment */\n+ fun bar() {\n+ /* Some comment */\n+ }\n \"\"\".trimIndent()\n- commentWrappingRuleAssertThat(code).hasNoLintViolations()\n+ val formattedCode =\n+ \"\"\"\n+ fun bar() {\n+ // Some comment\n+ }\n+ \"\"\".trimIndent()\n+ commentWrappingRuleAssertThat(code)\n+ .withEditorConfigOverride(CODE_STYLE_PROPERTY to ktlint_official)\n+ .hasLintViolation(2, 5, \"A single line block comment must be replaced with an EOL comment\")\n+ .isFormattedAs(formattedCode)\n }\n \n @Test\n@@ -27,33 +40,138 @@ class CommentWrappingRuleTest {\n commentWrappingRuleAssertThat(code).hasNoLintViolations()\n }\n \n- @Test\n- fun `Given a block comment followed by a code element on the same line as the block comment ended then split the elements with a new line`() {\n- val code =\n- \"\"\"\n- /* Some comment 1 */ val foo1 = \"foo1\"\n- /* Some comment 2 */val foo2 = \"foo2\"\n- /* Some comment 3 */ fun foo3() = \"foo3\"\n- /* Some comment 4 */fun foo4() = \"foo4\"\n- \"\"\".trimIndent()\n- val formattedCode =\n- \"\"\"\n- /* Some comment 1 */\n- val foo1 = \"foo1\"\n- /* Some comment 2 */\n- val foo2 = \"foo2\"\n- /* Some comment 3 */\n- fun foo3() = \"foo3\"\n- /* Some comment 4 */\n- fun foo4() = \"foo4\"\n- \"\"\".trimIndent()\n- commentWrappingRuleAssertThat(code)\n- .hasLintViolations(\n- LintViolation(1, 21, \"A block comment may not be followed by any other element on that same line\"),\n- LintViolation(2, 21, \"A block comment may not be followed by any other element on that same line\"),\n- LintViolation(3, 21, \"A block comment may not be followed by any other element on that same line\"),\n- LintViolation(4, 21, \"A block comment may not be followed by any other element on that same line\"),\n- ).isFormattedAs(formattedCode)\n+ @Nested\n+ inner class `Given a block comment followed by a code element on the same line` {\n+ @Test\n+ fun `Given a comment followed by a property and separated with space`() {\n+ val code =\n+ \"\"\"\n+ /* Some comment */ val foo = \"foo\"\n+ \"\"\".trimIndent()\n+ val formattedCode =\n+ \"\"\"\n+ /* Some comment */\n+ val foo = \"foo\"\n+ \"\"\".trimIndent()\n+ commentWrappingRuleAssertThat(code)\n+ .hasLintViolation(1, 20, \"A block comment may not be followed by any other element on that same line\")\n+ .isFormattedAs(formattedCode)\n+ }\n+\n+ @Test\n+ fun `Given a comment followed by a property but not separated with space`() {\n+ val code =\n+ \"\"\"\n+ /* Some comment */val foo = \"foo\"\n+ \"\"\".trimIndent()\n+ val formattedCode =\n+ \"\"\"\n+ /* Some comment */\n+ val foo = \"foo\"\n+ \"\"\".trimIndent()\n+ commentWrappingRuleAssertThat(code)\n+ .hasLintViolation(1, 19, \"A block comment may not be followed by any other element on that same line\")\n+ .isFormattedAs(formattedCode)\n+ }\n+\n+ @Test\n+ fun `Given a comment followed by a function and separated with space`() {\n+ val code =\n+ \"\"\"\n+ /* Some comment */ fun foo() = \"foo\"\n+ \"\"\".trimIndent()\n+ val formattedCode =\n+ \"\"\"\n+ /* Some comment */\n+ fun foo() = \"foo\"\n+ \"\"\".trimIndent()\n+ commentWrappingRuleAssertThat(code)\n+ .hasLintViolation(1, 20, \"A block comment may not be followed by any other element on that same line\")\n+ .isFormattedAs(formattedCode)\n+ }\n+\n+ @Test\n+ fun `Given a comment followed by a function but not separated with space`() {\n+ val code =\n+ \"\"\"\n+ /* Some comment */fun foo() = \"foo\"\n+ \"\"\".trimIndent()\n+ val formattedCode =\n+ \"\"\"\n+ /* Some comment */\n+ fun foo() = \"foo\"\n+ \"\"\".trimIndent()\n+ commentWrappingRuleAssertThat(code)\n+ .hasLintViolation(1, 19, \"A block comment may not be followed by any other element on that same line\")\n+ .isFormattedAs(formattedCode)\n+ }\n+ }\n+\n+ @Nested\n+ inner class `Given some code code followed by a block comment on the same line` {\n+ @Test\n+ fun `Given a comment followed by a property and separated with space`() {\n+ val code =\n+ \"\"\"\n+ val foo = \"foo\" /* Some comment */\n+ \"\"\".trimIndent()\n+ val formattedCode =\n+ \"\"\"\n+ val foo = \"foo\" // Some comment\n+ \"\"\".trimIndent()\n+ @Suppress(\"ktlint:argument-list-wrapping\", \"ktlint:max-line-length\")\n+ commentWrappingRuleAssertThat(code)\n+ .hasLintViolation(1, 17, \"A single line block comment after a code element on the same line must be replaced with an EOL comment\")\n+ .isFormattedAs(formattedCode)\n+ }\n+\n+ @Test\n+ fun `Given a comment followed by a property but not separated with space`() {\n+ val code =\n+ \"\"\"\n+ val foo = \"foo\"/* Some comment */\n+ \"\"\".trimIndent()\n+ val formattedCode =\n+ \"\"\"\n+ val foo = \"foo\" // Some comment\n+ \"\"\".trimIndent()\n+ @Suppress(\"ktlint:argument-list-wrapping\", \"ktlint:max-line-length\")\n+ commentWrappingRuleAssertThat(code)\n+ .hasLintViolation(1, 16, \"A single line block comment after a code element on the same line must be replaced with an EOL comment\")\n+ .isFormattedAs(formattedCode)\n+ }\n+\n+ @Test\n+ fun `Given a comment followed by a function and separated with space`() {\n+ val code =\n+ \"\"\"\n+ fun foo() = \"foo\" /* Some comment */\n+ \"\"\".trimIndent()\n+ val formattedCode =\n+ \"\"\"\n+ fun foo() = \"foo\" // Some comment\n+ \"\"\".trimIndent()\n+ @Suppress(\"ktlint:argument-list-wrapping\", \"ktlint:max-line-length\")\n+ commentWrappingRuleAssertThat(code)\n+ .hasLintViolation(1, 19, \"A single line block comment after a code element on the same line must be replaced with an EOL comment\")\n+ .isFormattedAs(formattedCode)\n+ }\n+\n+ @Test\n+ fun `Given a comment followed by a function but not separated with space`() {\n+ val code =\n+ \"\"\"\n+ fun foo() = \"foo\"/* Some comment */\n+ \"\"\".trimIndent()\n+ val formattedCode =\n+ \"\"\"\n+ fun foo() = \"foo\" // Some comment\n+ \"\"\".trimIndent()\n+ @Suppress(\"ktlint:argument-list-wrapping\", \"ktlint:max-line-length\")\n+ commentWrappingRuleAssertThat(code)\n+ .hasLintViolation(1, 18, \"A single line block comment after a code element on the same line must be replaced with an EOL comment\")\n+ .isFormattedAs(formattedCode)\n+ }\n }\n \n @Test\n@@ -64,12 +182,9 @@ class CommentWrappingRuleTest {\n * with a newline\n */\n \"\"\".trimIndent()\n+ @Suppress(\"ktlint:argument-list-wrapping\", \"ktlint:max-line-length\")\n commentWrappingRuleAssertThat(code)\n- .hasLintViolationWithoutAutoCorrect(\n- 1,\n- 17,\n- \"A block comment after any other element on the same line must be separated by a new line\",\n- )\n+ .hasLintViolationWithoutAutoCorrect(1, 17, \"A block comment after any other element on the same line must be separated by a new line\")\n }\n \n @Test\n@@ -84,7 +199,7 @@ class CommentWrappingRuleTest {\n \"\"\".trimIndent()\n @Suppress(\"ktlint:argument-list-wrapping\", \"ktlint:max-line-length\")\n commentWrappingRuleAssertThat(code)\n- .hasLintViolation(1, 16, \"A single line block comment after a code element on the same line must be replaced with an EOL comment\")\n+ .hasLintViolation(1, 17, \"A single line block comment after a code element on the same line must be replaced with an EOL comment\")\n .isFormattedAs(formattedCode)\n }\n \n@@ -94,12 +209,9 @@ class CommentWrappingRuleTest {\n \"\"\"\n val foo /* some comment */ = \"foo\"\n \"\"\".trimIndent()\n+ @Suppress(\"ktlint:argument-list-wrapping\", \"ktlint:max-line-length\")\n commentWrappingRuleAssertThat(code)\n- .hasLintViolationWithoutAutoCorrect(\n- 1,\n- 9,\n- \"A block comment in between other elements on the same line is disallowed\",\n- )\n+ .hasLintViolationWithoutAutoCorrect(1, 9, \"A block comment in between other elements on the same line is disallowed\")\n }\n \n @Test\n@@ -110,12 +222,9 @@ class CommentWrappingRuleTest {\n some comment\n */ = \"foo\"\n \"\"\".trimIndent()\n+ @Suppress(\"ktlint:argument-list-wrapping\", \"ktlint:max-line-length\")\n commentWrappingRuleAssertThat(code)\n- .hasLintViolationWithoutAutoCorrect(\n- 1,\n- 9,\n- \"A block comment starting on same line as another element and ending on another line before another element is disallowed\",\n- )\n+ .hasLintViolationWithoutAutoCorrect(1, 9, \"A block comment starting on same line as another element and ending on another line before another element is disallowed\")\n }\n \n @Test\n@@ -134,7 +243,31 @@ class CommentWrappingRuleTest {\n }\n \"\"\".trimIndent()\n commentWrappingRuleAssertThat(code)\n- .hasLintViolation(2, 23, \"A block comment may not be followed by any other element on that same line\")\n+ .hasLintViolation(2, 24, \"A block comment may not be followed by any other element on that same line\")\n .isFormattedAs(formattedCode)\n }\n+\n+ @Test\n+ fun `Given a single line block containing a block comment then do not reformat`() {\n+ val code =\n+ \"\"\"\n+ val foo = { /* no-op */ }\n+ \"\"\".trimIndent()\n+ commentWrappingRuleAssertThat(code)\n+ .withEditorConfigOverride(CODE_STYLE_PROPERTY to ktlint_official)\n+ .hasNoLintViolations()\n+ }\n+\n+ @Test\n+ fun `Given single line block comments to disable or enable ktlint then do not reformat`() {\n+ val code =\n+ \"\"\"\n+ /* ktlint-disable foo-rule-id bar-rule-id */\n+ val foo = \"foo\"\n+ /* ktlint-enable foo-rule-id bar-rule-id */\n+ \"\"\".trimIndent()\n+ commentWrappingRuleAssertThat(code)\n+ .withEditorConfigOverride(CODE_STYLE_PROPERTY to ktlint_official)\n+ .hasNoLintViolations()\n+ }\n }\ndiff --git a/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/EnumEntryNameCaseRuleTest.kt b/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/EnumEntryNameCaseRuleTest.kt\nindex 9d165e762c..cbc1ebc757 100644\n--- a/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/EnumEntryNameCaseRuleTest.kt\n+++ b/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/EnumEntryNameCaseRuleTest.kt\n@@ -29,12 +29,9 @@ class EnumEntryNameCaseRuleTest {\n _FOO\n }\n \"\"\".trimIndent()\n+ @Suppress(\"ktlint:argument-list-wrapping\", \"ktlint:max-line-length\")\n enumEntryNameCaseRuleAssertThat(code)\n- .hasLintViolationWithoutAutoCorrect(\n- 2,\n- 5,\n- \"Enum entry name should be uppercase underscore-separated names like \\\"ENUM_ENTRY\\\" or upper camel-case like \\\"EnumEntry\\\"\",\n- )\n+ .hasLintViolationWithoutAutoCorrect(2, 5, \"Enum entry name should be uppercase underscore-separated names like \\\"ENUM_ENTRY\\\" or upper camel-case like \\\"EnumEntry\\\"\")\n }\n \n @Test\ndiff --git a/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/FilenameRuleTest.kt b/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/FilenameRuleTest.kt\nindex e95fe3bdeb..8ff0769cc8 100644\n--- a/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/FilenameRuleTest.kt\n+++ b/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/FilenameRuleTest.kt\n@@ -86,13 +86,10 @@ class FilenameRuleTest {\n ],\n )\n fun `Given a file containing one top level declaration then the file should be named after the identifier`(code: String) {\n+ @Suppress(\"ktlint:argument-list-wrapping\", \"ktlint:max-line-length\")\n fileNameRuleAssertThat(code)\n .asFileWithPath(UNEXPECTED_FILE_NAME)\n- .hasLintViolationWithoutAutoCorrect(\n- 1,\n- 1,\n- \"File '$UNEXPECTED_FILE_NAME' contains a single top level declaration and should be named 'Foo.kt'\",\n- )\n+ .hasLintViolationWithoutAutoCorrect(1, 1, \"File '$UNEXPECTED_FILE_NAME' contains a single top level declaration and should be named 'Foo.kt'\")\n }\n \n @ParameterizedTest(name = \"Top level declaration: {0}\")\ndiff --git a/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/FunctionNamingRuleTest.kt b/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/FunctionNamingRuleTest.kt\nindex 0b2c042232..ea113c9848 100644\n--- a/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/FunctionNamingRuleTest.kt\n+++ b/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/FunctionNamingRuleTest.kt\n@@ -39,12 +39,9 @@ class FunctionNamingRuleTest {\n \"\"\"\n fun `Some name`() {}\n \"\"\".trimIndent()\n+ @Suppress(\"ktlint:argument-list-wrapping\", \"ktlint:max-line-length\")\n functionNamingRuleAssertThat(code)\n- .hasLintViolationWithoutAutoCorrect(\n- 1,\n- 5,\n- \"Function name should start with a lowercase letter (except factory methods) and use camel case\",\n- )\n+ .hasLintViolationWithoutAutoCorrect(1, 5, \"Function name should start with a lowercase letter (except factory methods) and use camel case\")\n }\n \n @ParameterizedTest(name = \"Junit import: {0}\")\n@@ -78,12 +75,9 @@ class FunctionNamingRuleTest {\n \"\"\"\n fun do_something() {}\n \"\"\".trimIndent()\n+ @Suppress(\"ktlint:argument-list-wrapping\", \"ktlint:max-line-length\")\n functionNamingRuleAssertThat(code)\n- .hasLintViolationWithoutAutoCorrect(\n- 1,\n- 5,\n- \"Function name should start with a lowercase letter (except factory methods) and use camel case\",\n- )\n+ .hasLintViolationWithoutAutoCorrect(1, 5, \"Function name should start with a lowercase letter (except factory methods) and use camel case\")\n }\n \n @ParameterizedTest(name = \"Junit import: {0}\")\n@@ -123,12 +117,9 @@ class FunctionNamingRuleTest {\n \"\"\"\n fun $functionName() = \"foo\"\n \"\"\".trimIndent()\n+ @Suppress(\"ktlint:argument-list-wrapping\", \"ktlint:max-line-length\")\n functionNamingRuleAssertThat(code)\n- .hasLintViolationWithoutAutoCorrect(\n- 1,\n- 5,\n- \"Function name should start with a lowercase letter (except factory methods) and use camel case\",\n- )\n+ .hasLintViolationWithoutAutoCorrect(1, 5, \"Function name should start with a lowercase letter (except factory methods) and use camel case\")\n }\n \n @ParameterizedTest(name = \"Suppression annotation: {0}\")\ndiff --git a/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/IndentationRuleTest.kt b/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/IndentationRuleTest.kt\nindex a234d30270..f1c49672ef 100644\n--- a/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/IndentationRuleTest.kt\n+++ b/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/IndentationRuleTest.kt\n@@ -3203,12 +3203,9 @@ internal class IndentationRuleTest {\n ${TAB}line2\n $MULTILINE_STRING_QUOTE.trimIndent()\n \"\"\".trimIndent()\n+ @Suppress(\"ktlint:argument-list-wrapping\", \"ktlint:max-line-length\")\n indentationRuleAssertThat(code)\n- .hasLintViolationWithoutAutoCorrect(\n- 1,\n- 11,\n- \"Indentation of multiline string should not contain both tab(s) and space(s)\",\n- )\n+ .hasLintViolationWithoutAutoCorrect(1, 11, \"Indentation of multiline string should not contain both tab(s) and space(s)\")\n }\n \n @Test\n@@ -5042,6 +5039,89 @@ internal class IndentationRuleTest {\n ).isFormattedAs(formattedCode)\n }\n \n+ @Test\n+ fun `Given an elvis operator followed by a multiline expression`() {\n+ val code =\n+ \"\"\"\n+ fun fooBar(foo: String?, bar: String) =\n+ foo\n+ ?.lowercase()\n+ ?: bar\n+ .uppercase()\n+ .trimIndent()\n+ \"\"\".trimIndent()\n+ indentationRuleAssertThat(code).hasNoLintViolations()\n+ }\n+\n+ @Nested\n+ inner class `Given a function with raw string literal as result` {\n+ @Test\n+ fun `As body expression on same line as equals and preceded by space`() {\n+ val code =\n+ \"\"\"\n+ private fun foo(\n+ bar: String,\n+ ) = $MULTILINE_STRING_QUOTE\n+ bar\n+ $MULTILINE_STRING_QUOTE.trimIndent()\n+ \"\"\".trimIndent()\n+ indentationRuleAssertThat(code).hasNoLintViolations()\n+ }\n+\n+ @Test\n+ fun `As body expression on same line as equals but not preceded by space`() {\n+ val code =\n+ \"\"\"\n+ private fun foo(\n+ bar: String,\n+ ) =$MULTILINE_STRING_QUOTE\n+ bar\n+ $MULTILINE_STRING_QUOTE.trimIndent()\n+ \"\"\".trimIndent()\n+ indentationRuleAssertThat(code).hasNoLintViolations()\n+ }\n+\n+ @Test\n+ fun `As body expression on next line`() {\n+ val code =\n+ \"\"\"\n+ private fun foo( bar: String) =\n+ $MULTILINE_STRING_QUOTE\n+ bar\n+ $MULTILINE_STRING_QUOTE.trimIndent()\n+ \"\"\".trimIndent()\n+ indentationRuleAssertThat(code).hasNoLintViolations()\n+ }\n+\n+ @Test\n+ fun `As block body`() {\n+ val code =\n+ \"\"\"\n+ private fun foo( bar: String): String {\n+ return $MULTILINE_STRING_QUOTE\n+ bar\n+ $MULTILINE_STRING_QUOTE.trimIndent()\n+ }\n+ \"\"\".trimIndent()\n+ indentationRuleAssertThat(code).hasNoLintViolations()\n+ }\n+\n+ @Test\n+ fun `As body expression of function wrapped in class`() {\n+ val code =\n+ \"\"\"\n+ class Bar {\n+ private fun foo(\n+ bar: String,\n+ ) = $MULTILINE_STRING_QUOTE\n+ bar\n+ $MULTILINE_STRING_QUOTE.trimIndent()\n+ }\n+ \"\"\".trimIndent()\n+ indentationRuleAssertThat(code).hasNoLintViolations()\n+ }\n+ }\n+\n private companion object {\n val INDENT_STYLE_TAB =\n INDENT_STYLE_PROPERTY to PropertyType.IndentStyleValue.tab\ndiff --git a/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/KdocWrappingRuleTest.kt b/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/KdocWrappingRuleTest.kt\nindex 9e92f18725..f6a6080b4c 100644\n--- a/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/KdocWrappingRuleTest.kt\n+++ b/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/KdocWrappingRuleTest.kt\n@@ -64,12 +64,9 @@ class KdocWrappingRuleTest {\n * with a newline\n */\n \"\"\".trimIndent()\n+ @Suppress(\"ktlint:argument-list-wrapping\", \"ktlint:max-line-length\")\n kdocWrappingRuleAssertThat(code)\n- .hasLintViolationWithoutAutoCorrect(\n- 1,\n- 17,\n- \"A KDoc comment after any other element on the same line must be separated by a new line\",\n- )\n+ .hasLintViolationWithoutAutoCorrect(1, 17, \"A KDoc comment after any other element on the same line must be separated by a new line\")\n }\n \n @Test\n@@ -90,12 +87,9 @@ class KdocWrappingRuleTest {\n some KDoc comment\n */ = \"foo\"\n \"\"\".trimIndent()\n+ @Suppress(\"ktlint:argument-list-wrapping\", \"ktlint:max-line-length\")\n kdocWrappingRuleAssertThat(code)\n- .hasLintViolationWithoutAutoCorrect(\n- 1,\n- 9,\n- \"A KDoc comment starting on same line as another element and ending on another line before another element is disallowed\",\n- )\n+ .hasLintViolationWithoutAutoCorrect(1, 9, \"A KDoc comment starting on same line as another element and ending on another line before another element is disallowed\")\n }\n \n @Test\ndiff --git a/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/MultilineExpressionWrappingTest.kt b/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/MultilineExpressionWrappingTest.kt\nindex 3c904ede40..5074bc66cb 100644\n--- a/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/MultilineExpressionWrappingTest.kt\n+++ b/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/MultilineExpressionWrappingTest.kt\n@@ -690,4 +690,109 @@ class MultilineExpressionWrappingTest {\n .withEditorConfigOverride(CODE_STYLE_PROPERTY to CodeStyleValue.ktlint_official)\n .hasNoLintViolations()\n }\n+\n+ @Test\n+ fun `Given a multiline expression with an EOL comment on the last line`() {\n+ val code =\n+ \"\"\"\n+ val foo = bar\n+ .length() // some-comment\n+\n+ val foobar = \"foobar\"\n+ \"\"\".trimIndent()\n+ val formattedCode =\n+ \"\"\"\n+ val foo =\n+ bar\n+ .length() // some-comment\n+\n+ val foobar = \"foobar\"\n+ \"\"\".trimIndent()\n+ multilineExpressionWrappingAssertThat(code)\n+ .addAdditionalRuleProvider { IndentationRule() }\n+ .withEditorConfigOverride(CODE_STYLE_PROPERTY to CodeStyleValue.ktlint_official)\n+ .hasLintViolation(1, 11, \"A multiline expression should start on a new line\")\n+ .isFormattedAs(formattedCode)\n+ }\n+\n+ @Test\n+ fun `Given an assignment to variable`() {\n+ val code =\n+ \"\"\"\n+ fun foo() {\n+ var givenCode: String\n+\n+ givenCode = $MULTILINE_STRING_QUOTE\n+ some text\n+ $MULTILINE_STRING_QUOTE.trimIndent()\n+ }\n+ \"\"\".trimIndent()\n+ val formattedCode =\n+ \"\"\"\n+ fun foo() {\n+ var givenCode: String\n+\n+ givenCode =\n+ $MULTILINE_STRING_QUOTE\n+ some text\n+ $MULTILINE_STRING_QUOTE.trimIndent()\n+ }\n+ \"\"\".trimIndent()\n+ multilineExpressionWrappingAssertThat(code)\n+ .addAdditionalRuleProvider { IndentationRule() }\n+ .withEditorConfigOverride(CODE_STYLE_PROPERTY to CodeStyleValue.ktlint_official)\n+ .hasLintViolation(4, 17, \"A multiline expression should start on a new line\")\n+ .isFormattedAs(formattedCode)\n+ }\n+\n+ @Test\n+ fun `Given a comparison in which the right hand side is a multiline expression`() {\n+ val code =\n+ \"\"\"\n+ fun foo(bar: String): Boolean {\n+ return bar != $MULTILINE_STRING_QUOTE\n+ some text\n+ $MULTILINE_STRING_QUOTE.trimIndent()\n+ }\n+ \"\"\".trimIndent()\n+ val formattedCode =\n+ \"\"\"\n+ fun foo(bar: String): Boolean {\n+ return bar !=\n+ $MULTILINE_STRING_QUOTE\n+ some text\n+ $MULTILINE_STRING_QUOTE.trimIndent()\n+ }\n+ \"\"\".trimIndent()\n+ multilineExpressionWrappingAssertThat(code)\n+ .addAdditionalRuleProvider { IndentationRule() }\n+ .withEditorConfigOverride(CODE_STYLE_PROPERTY to CodeStyleValue.ktlint_official)\n+ .hasLintViolation(2, 19, \"A multiline expression should start on a new line\")\n+ .isFormattedAs(formattedCode)\n+ }\n+\n+ fun fooBar(foobar: String?) =\n+ foobar\n+ ?.lowercase()\n+ ?: \"\"\"\n+ foo\n+ \"\"\"\n+ .uppercase()\n+ .trimIndent()\n+\n+ @Test\n+ fun `Given an elvis operator followed by a multiline expression then do not reformat`() {\n+ val code =\n+ \"\"\"\n+ fun fooBar(foobar: String?, bar: String) =\n+ foo\n+ ?.lowercase()\n+ ?: bar\n+ .uppercase()\n+ .trimIndent()\n+ \"\"\".trimIndent()\n+ multilineExpressionWrappingAssertThat(code)\n+ .addAdditionalRuleProvider { IndentationRule() }\n+ .hasNoLintViolations()\n+ }\n }\ndiff --git a/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/NoConsecutiveCommentsRuleTest.kt b/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/NoConsecutiveCommentsRuleTest.kt\nindex cd2cb7e4ca..6574988f3a 100644\n--- a/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/NoConsecutiveCommentsRuleTest.kt\n+++ b/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/NoConsecutiveCommentsRuleTest.kt\n@@ -7,6 +7,7 @@ import com.pinterest.ktlint.rule.engine.core.api.editorconfig.RuleExecution\n import com.pinterest.ktlint.rule.engine.core.api.editorconfig.createRuleExecutionEditorConfigProperty\n import com.pinterest.ktlint.test.KtLintAssertThat.Companion.assertThatRule\n import com.pinterest.ktlint.test.LintViolation\n+import org.junit.jupiter.api.Nested\n import org.junit.jupiter.api.Test\n import org.junit.jupiter.params.ParameterizedTest\n import org.junit.jupiter.params.provider.EnumSource\n@@ -51,13 +52,14 @@ class NoConsecutiveCommentsRuleTest {\n /** KDoc 1 */\n /* Block comment 2 */\n \"\"\".trimIndent()\n+ @Suppress(\"ktlint:argument-list-wrapping\", \"ktlint:max-line-length\")\n noConsecutiveBlankLinesRuleAssertThat(code)\n .withEditorConfigOverride(CODE_STYLE_PROPERTY to codeStyle)\n .withEditorConfigOverride(NO_CONSECUTIVE_COMMENTS_RULE_ID.createRuleExecutionEditorConfigProperty() to RuleExecution.enabled)\n .hasLintViolationsWithoutAutoCorrect(\n- LintViolation(2, 1, \"a block comment may not be preceded by an EOL comment\"),\n- LintViolation(3, 1, \"a KDoc may not be preceded by a block comment\"),\n- LintViolation(4, 1, \"a block comment may not be preceded by a KDoc\"),\n+ LintViolation(2, 1, \"a block comment may not be preceded by an EOL comment unless separated by a blank line\"),\n+ LintViolation(3, 1, \"a KDoc may not be preceded by a block comment unless separated by a blank line\"),\n+ LintViolation(4, 1, \"a block comment may not be preceded by a KDoc. Reversed order is allowed though when separated by a newline.\"),\n )\n }\n \n@@ -107,76 +109,141 @@ class NoConsecutiveCommentsRuleTest {\n )\n }\n \n- @Test\n- fun `Given a KDoc followed by a block comment then report a violation`() {\n- val code =\n- \"\"\"\n- /** KDoc */\n- /* Block comment */\n- \"\"\".trimIndent()\n- noConsecutiveBlankLinesRuleAssertThat(code)\n- .withEditorConfigOverride(CODE_STYLE_PROPERTY to ktlint_official)\n- .hasLintViolationWithoutAutoCorrect(2, 1, \"a block comment may not be preceded by a KDoc\")\n- }\n+ @Nested\n+ inner class `Given a KDoc and block comment` {\n+ @Test\n+ fun `Given a KDoc followed by a block comment then report a violation`() {\n+ val code =\n+ \"\"\"\n+ /** KDoc */\n+ /* Block comment */\n+ \"\"\".trimIndent()\n+ @Suppress(\"ktlint:argument-list-wrapping\", \"ktlint:max-line-length\")\n+ noConsecutiveBlankLinesRuleAssertThat(code)\n+ .withEditorConfigOverride(CODE_STYLE_PROPERTY to ktlint_official)\n+ .hasLintViolationWithoutAutoCorrect(2, 1, \"a block comment may not be preceded by a KDoc. Reversed order is allowed though when separated by a newline.\")\n+ }\n \n- @Test\n- fun `Given a block comment followed by a KDoc then report a violation`() {\n- val code =\n- \"\"\"\n- /* Block comment */\n- /** KDoc */\n- \"\"\".trimIndent()\n- noConsecutiveBlankLinesRuleAssertThat(code)\n- .withEditorConfigOverride(CODE_STYLE_PROPERTY to ktlint_official)\n- .hasLintViolationWithoutAutoCorrect(2, 1, \"a KDoc may not be preceded by a block comment\")\n- }\n+ @Test\n+ fun `Given a block comment followed by a KDoc then report a violation`() {\n+ val code =\n+ \"\"\"\n+ /* Block comment */\n+ /** KDoc */\n+ \"\"\".trimIndent()\n+ noConsecutiveBlankLinesRuleAssertThat(code)\n+ .withEditorConfigOverride(CODE_STYLE_PROPERTY to ktlint_official)\n+ .hasLintViolationWithoutAutoCorrect(2, 1, \"a KDoc may not be preceded by a block comment unless separated by a blank line\")\n+ }\n \n- @Test\n- fun `Given an EOL comment followed by a KDoc then report a violation`() {\n- val code =\n- \"\"\"\n- // EOL comment\n- /** KDoc */\n- \"\"\".trimIndent()\n- noConsecutiveBlankLinesRuleAssertThat(code)\n- .withEditorConfigOverride(CODE_STYLE_PROPERTY to ktlint_official)\n- .hasLintViolationWithoutAutoCorrect(2, 1, \"a KDoc may not be preceded by an EOL comment\")\n- }\n+ @Test\n+ fun `Given a block comment followed by a blank line and a KDoc then do not report a violation`() {\n+ val code =\n+ \"\"\"\n+ /* Block comment */\n \n- @Test\n- fun `Given a KDoc followed by an EOL comment then report a violation`() {\n- val code =\n- \"\"\"\n- /** KDoc */\n- // EOL comment\n- \"\"\".trimIndent()\n- noConsecutiveBlankLinesRuleAssertThat(code)\n- .withEditorConfigOverride(CODE_STYLE_PROPERTY to ktlint_official)\n- .hasLintViolationWithoutAutoCorrect(2, 1, \"an EOL comment may not be preceded by a KDoc\")\n+ /** KDoc */\n+ \"\"\".trimIndent()\n+ noConsecutiveBlankLinesRuleAssertThat(code)\n+ .withEditorConfigOverride(CODE_STYLE_PROPERTY to ktlint_official)\n+ .hasNoLintViolations()\n+ }\n }\n \n- @Test\n- fun `Given an EOL comment followed by a block comment then report a violation`() {\n- val code =\n- \"\"\"\n- // EOL comment\n- /* Block comment */\n- \"\"\".trimIndent()\n- noConsecutiveBlankLinesRuleAssertThat(code)\n- .withEditorConfigOverride(CODE_STYLE_PROPERTY to ktlint_official)\n- .hasLintViolationWithoutAutoCorrect(2, 1, \"a block comment may not be preceded by an EOL comment\")\n+ @Nested\n+ inner class `Given a KDoc and EOL comment` {\n+ @Test\n+ fun `Given a KDoc followed by an EOL comment then report a violation`() {\n+ val code =\n+ \"\"\"\n+ /** KDoc */\n+ // EOL comment\n+ \"\"\".trimIndent()\n+ @Suppress(\"ktlint:argument-list-wrapping\", \"ktlint:max-line-length\")\n+ noConsecutiveBlankLinesRuleAssertThat(code)\n+ .withEditorConfigOverride(CODE_STYLE_PROPERTY to ktlint_official)\n+ .hasLintViolationWithoutAutoCorrect(2, 1, \"an EOL comment may not be preceded by a KDoc. Reversed order is allowed though when separated by a newline.\")\n+ }\n+\n+ @Test\n+ fun `Given an EOL comment followed by a KDoc then report a violation`() {\n+ val code =\n+ \"\"\"\n+ // EOL comment\n+ /** KDoc */\n+ \"\"\".trimIndent()\n+ noConsecutiveBlankLinesRuleAssertThat(code)\n+ .withEditorConfigOverride(CODE_STYLE_PROPERTY to ktlint_official)\n+ .hasLintViolationWithoutAutoCorrect(2, 1, \"a KDoc may not be preceded by an EOL comment unless separated by a blank line\")\n+ }\n+\n+ @Test\n+ fun `Given an EOL comment followed by a blank line and a KDoc then report a violation`() {\n+ val code =\n+ \"\"\"\n+ // EOL comment\n+\n+ /** KDoc */\n+ \"\"\".trimIndent()\n+ noConsecutiveBlankLinesRuleAssertThat(code)\n+ .withEditorConfigOverride(CODE_STYLE_PROPERTY to ktlint_official)\n+ .hasNoLintViolations()\n+ }\n }\n \n- @Test\n- fun `Given a block comment followed by an EOL comment then report a violation`() {\n- val code =\n- \"\"\"\n- /* Block comment */\n- // EOL comment\n- \"\"\".trimIndent()\n- noConsecutiveBlankLinesRuleAssertThat(code)\n- .withEditorConfigOverride(CODE_STYLE_PROPERTY to ktlint_official)\n- .hasLintViolationWithoutAutoCorrect(2, 1, \"an EOL comment may not be preceded by a block comment\")\n+ @Nested\n+ inner class `Given a block and EOL comment` {\n+ @Test\n+ fun `Given an EOL comment followed by a block comment then report a violation`() {\n+ val code =\n+ \"\"\"\n+ // EOL comment\n+ /* Block comment */\n+ \"\"\".trimIndent()\n+ @Suppress(\"ktlint:argument-list-wrapping\", \"ktlint:max-line-length\")\n+ noConsecutiveBlankLinesRuleAssertThat(code)\n+ .withEditorConfigOverride(CODE_STYLE_PROPERTY to ktlint_official)\n+ .hasLintViolationWithoutAutoCorrect(2, 1, \"a block comment may not be preceded by an EOL comment unless separated by a blank line\")\n+ }\n+\n+ @Test\n+ fun `Given an EOL comment followed by a blank line and a block comment then report a violation`() {\n+ val code =\n+ \"\"\"\n+ // EOL comment\n+\n+ /* Block comment */\n+ \"\"\".trimIndent()\n+ noConsecutiveBlankLinesRuleAssertThat(code)\n+ .withEditorConfigOverride(CODE_STYLE_PROPERTY to ktlint_official)\n+ .hasNoLintViolations()\n+ }\n+\n+ @Test\n+ fun `Given a block comment followed by an EOL comment then report a violation`() {\n+ val code =\n+ \"\"\"\n+ /* Block comment */\n+ // EOL comment\n+ \"\"\".trimIndent()\n+ @Suppress(\"ktlint:argument-list-wrapping\", \"ktlint:max-line-length\")\n+ noConsecutiveBlankLinesRuleAssertThat(code)\n+ .withEditorConfigOverride(CODE_STYLE_PROPERTY to ktlint_official)\n+ .hasLintViolationWithoutAutoCorrect(2, 1, \"an EOL comment may not be preceded by a block comment unless separated by a blank line\")\n+ }\n+\n+ @Test\n+ fun `Given a block comment followed by a blank line and an EOL comment then report a violation`() {\n+ val code =\n+ \"\"\"\n+ /* Block comment */\n+\n+ // EOL comment\n+ \"\"\".trimIndent()\n+ noConsecutiveBlankLinesRuleAssertThat(code)\n+ .withEditorConfigOverride(CODE_STYLE_PROPERTY to ktlint_official)\n+ .hasNoLintViolations()\n+ }\n }\n \n @Test\ndiff --git a/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/ParameterListSpacingRuleTest.kt b/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/ParameterListSpacingRuleTest.kt\nindex e813f919cb..ff59f97677 100644\n--- a/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/ParameterListSpacingRuleTest.kt\n+++ b/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/ParameterListSpacingRuleTest.kt\n@@ -462,6 +462,19 @@ class ParameterListSpacingRuleTest {\n .hasNoLintViolations()\n }\n \n+ @Test\n+ fun `Given a class with a parameter having an annotated type on a separate line then do not report a violation`() {\n+ val code =\n+ \"\"\"\n+ data class Foo(\n+ val bar:\n+ @FooBar(\"foobar\")\n+ Bar,\n+ )\n+ \"\"\".trimIndent()\n+ parameterListSpacingRuleAssertThat(code).hasNoLintViolations()\n+ }\n+\n private companion object {\n const val TOO_MANY_SPACES = \" \"\n }\ndiff --git a/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/PropertyNamingRuleTest.kt b/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/PropertyNamingRuleTest.kt\nindex e65cdf5c56..0081183fe8 100644\n--- a/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/PropertyNamingRuleTest.kt\n+++ b/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/PropertyNamingRuleTest.kt\n@@ -42,12 +42,9 @@ class PropertyNamingRuleTest {\n const val FOO_BAR_2 = \"foo-bar-2\"\n const val \u0178\u00c8\u0160_TH\u00ceS_IS_ALLOWED_123 = \"Yes this is allowed\"\n \"\"\".trimIndent()\n+ @Suppress(\"ktlint:argument-list-wrapping\", \"ktlint:max-line-length\")\n propertyNamingRuleAssertThat(code)\n- .hasLintViolationWithoutAutoCorrect(\n- 1,\n- 11,\n- \"Property name should use the screaming snake case notation when the value can not be changed\",\n- )\n+ .hasLintViolationWithoutAutoCorrect(1, 11, \"Property name should use the screaming snake case notation when the value can not be changed\")\n }\n \n @Test\n@@ -57,12 +54,9 @@ class PropertyNamingRuleTest {\n val foo = Foo()\n val FOO_BAR = FooBar()\n \"\"\".trimIndent()\n+ @Suppress(\"ktlint:argument-list-wrapping\", \"ktlint:max-line-length\")\n propertyNamingRuleAssertThat(code)\n- .hasLintViolationWithoutAutoCorrect(\n- 1,\n- 5,\n- \"Property name should use the screaming snake case notation when the value can not be changed\",\n- )\n+ .hasLintViolationWithoutAutoCorrect(1, 5, \"Property name should use the screaming snake case notation when the value can not be changed\")\n }\n \n @Test\n@@ -76,12 +70,9 @@ class PropertyNamingRuleTest {\n }\n }\n \"\"\".trimIndent()\n+ @Suppress(\"ktlint:argument-list-wrapping\", \"ktlint:max-line-length\")\n propertyNamingRuleAssertThat(code)\n- .hasLintViolationWithoutAutoCorrect(\n- 3,\n- 13,\n- \"Property name should use the screaming snake case notation when the value can not be changed\",\n- )\n+ .hasLintViolationWithoutAutoCorrect(3, 13, \"Property name should use the screaming snake case notation when the value can not be changed\")\n }\n \n @Test\ndiff --git a/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/TypeParameterListSpacingRuleTest.kt b/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/TypeParameterListSpacingRuleTest.kt\nindex 50da2e33d9..df326e4904 100644\n--- a/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/TypeParameterListSpacingRuleTest.kt\n+++ b/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/TypeParameterListSpacingRuleTest.kt\n@@ -201,49 +201,12 @@ class TypeParameterListSpacingRuleTest {\n \"\"\".trimIndent()\n typeParameterListSpacingRuleAssertThat(code)\n .hasLintViolations(\n- LintViolation(1, 16, \"Expected a single space\"),\n- LintViolation(2, 16, \"Expected a single space\"),\n- LintViolation(3, 16, \"Expected a single space\"),\n- LintViolation(4, 16, \"Expected a single space\"),\n- LintViolation(5, 16, \"Expected a single space\"),\n- LintViolation(6, 16, \"Expected a single space\"),\n- ).isFormattedAs(formattedCode)\n- }\n-\n- @Test\n- fun `Given a class definition with a type parameter list followed by newlines and a compound constructor then replace with single space`() {\n- val code =\n- \"\"\"\n- class Foo1\n- constructor() {}\n- class Foo2\n- actual constructor() {}\n- class Foo3\n- private constructor() {}\n- class Foo4\n- internal constructor() {}\n- class Foo5\n- @FooBar constructor() {}\n- class Foo6\n- @FooBar internal constructor() {}\n- \"\"\".trimIndent()\n- val formattedCode =\n- \"\"\"\n- class Foo1 constructor() {}\n- class Foo2 actual constructor() {}\n- class Foo3 private constructor() {}\n- class Foo4 internal constructor() {}\n- class Foo5 @FooBar constructor() {}\n- class Foo6 @FooBar internal constructor() {}\n- \"\"\".trimIndent()\n- typeParameterListSpacingRuleAssertThat(code)\n- .hasLintViolations(\n- LintViolation(1, 16, \"Expected a single space instead of newline\"),\n- LintViolation(3, 16, \"Expected a single space instead of newline\"),\n- LintViolation(5, 16, \"Expected a single space instead of newline\"),\n- LintViolation(7, 16, \"Expected a single space instead of newline\"),\n- LintViolation(9, 16, \"Expected a single space instead of newline\"),\n- LintViolation(11, 16, \"Expected a single space instead of newline\"),\n+ LintViolation(1, 16, \"Expected a single space or newline (with indent)\"),\n+ LintViolation(2, 16, \"Expected a single space or newline (with indent)\"),\n+ LintViolation(3, 16, \"Expected a single space or newline (with indent)\"),\n+ LintViolation(4, 16, \"Expected a single space or newline (with indent)\"),\n+ LintViolation(5, 16, \"Expected a single space or newline (with indent)\"),\n+ LintViolation(6, 16, \"Expected a single space or newline (with indent)\"),\n ).isFormattedAs(formattedCode)\n }\n \n@@ -331,4 +294,26 @@ class TypeParameterListSpacingRuleTest {\n typeParameterListSpacingRuleAssertThat(code)\n .hasNoLintViolations()\n }\n+\n+ @Test\n+ fun `Given a class with an annotated constructor on a separate line then do not report a violation`() {\n+ val code =\n+ \"\"\"\n+ class Foo\n+ @Bar\n+ constructor(val value: T?) : FooBar()\n+ \"\"\".trimIndent()\n+ typeParameterListSpacingRuleAssertThat(code)\n+ .hasNoLintViolations()\n+ }\n+\n+ @Test\n+ fun `Given a class with an annotated constructor on same line as parameter type list then do not report a violation`() {\n+ val code =\n+ \"\"\"\n+ class Foo @Bar constructor(val value: T?) : FooBar()\n+ \"\"\".trimIndent()\n+ typeParameterListSpacingRuleAssertThat(code)\n+ .hasNoLintViolations()\n+ }\n }\n", "problem_statement": "Ignore block comment inside single line block\nGive an singe line block containing a block comment than do not wrap this comment to a multiline block. So code below should be kept unchanged:\r\n```\r\nval foo = { /* no-op */ }\r\n```\n", "hints_text": "", "created_at": "2023-04-16T14:36:48Z", "version": "0.49", "FAIL_TO_PASS": [ "gradle_test_execution" ], "PASS_TO_PASS": [], "ERROR_TO_PASS": [], "environment_setup_commit": "410d8849874f4d3600f9d4572e0850adccce4f2d" }, { "repo": "pinterest/ktlint", "pull_number": 1856, "instance_id": "pinterest__ktlint-1856", "issue_numbers": [ "1830" ], "base_commit": "f37fdc9757f8dca8cd010e5f499068d48728e05a", "patch": "diff --git a/CHANGELOG.md b/CHANGELOG.md\nindex ad7358ba4e..674682ba0d 100644\n--- a/CHANGELOG.md\n+++ b/CHANGELOG.md\n@@ -252,6 +252,7 @@ Previously the default value for `.editorconfig` property `max_line_length` was\n * Fix indentation of a multiline typealias `indent` ([#1788](https://github.com/pinterest/ktlint/issues/1788))\n * Fix false positive when multiple KDOCs exists between a declaration and another annotated declaration `spacing-between-declarations-with-annotations` ([#1802](https://github.com/pinterest/ktlint/issues/1802))\n * Fix false positive when a single line statement containing a block having exactly the maximum line length is preceded by a blank line `wrapping` ([#1808](https://github.com/pinterest/ktlint/issues/1808))\n+* Fix false positive when a single line contains multiple dot qualified expressions and/or safe expressions `indent` ([#1830](https://github.com/pinterest/ktlint/issues/1830))\n \n ### Changed\n * Wrap the parameters of a function literal containing a multiline parameter list (only in `ktlint_official` code style) `parameter-list-wrapping` ([#1681](https://github.com/pinterest/ktlint/issues/1681)).\ndiff --git a/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/IndentationRule.kt b/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/IndentationRule.kt\nindex 2b2d53b9b8..17f8e751a7 100644\n--- a/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/IndentationRule.kt\n+++ b/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/IndentationRule.kt\n@@ -214,7 +214,8 @@ public class IndentationRule :\n node.elementType == BINARY_WITH_TYPE ||\n node.elementType == SUPER_TYPE_ENTRY ||\n node.elementType == TYPE_ARGUMENT_LIST ||\n- node.elementType == TYPE_PARAMETER_LIST ->\n+ node.elementType == TYPE_PARAMETER_LIST ||\n+ node.elementType == USER_TYPE ->\n startIndentContext(node)\n \n node.elementType == DELEGATED_SUPER_TYPE_ENTRY ||\n@@ -257,9 +258,7 @@ public class IndentationRule :\n node.elementType == BINARY_EXPRESSION ->\n visitBinaryExpression(node)\n \n- node.elementType == DOT_QUALIFIED_EXPRESSION ||\n- node.elementType == SAFE_ACCESS_EXPRESSION ||\n- node.elementType == USER_TYPE -> {\n+ node.elementType in CHAINABLE_EXPRESSION -> {\n if (codeStyle == ktlint_official &&\n node.elementType == DOT_QUALIFIED_EXPRESSION &&\n node.treeParent?.elementType == ARRAY_ACCESS_EXPRESSION &&\n@@ -274,7 +273,9 @@ public class IndentationRule :\n fromAstNode = node.treeParent,\n toAstNode = node.treeParent.treeParent.lastChildLeafOrSelf(),\n )\n- } else if (node.treeParent?.elementType != node.elementType) {\n+ } else if (node.treeParent.elementType in CHAINABLE_EXPRESSION) {\n+ // Multiple dot qualified expressions and/or safe expression on the same line should not increase the indent level\n+ } else {\n startIndentContext(node)\n }\n }\n@@ -1068,6 +1069,7 @@ public class IndentationRule :\n private companion object {\n const val KDOC_CONTINUATION_INDENT = \" \"\n const val TYPE_CONSTRAINT_CONTINUATION_INDENT = \" \" // Length of keyword \"where\" plus separating space\n+ val CHAINABLE_EXPRESSION = setOf(DOT_QUALIFIED_EXPRESSION, SAFE_ACCESS_EXPRESSION)\n }\n \n private data class IndentContext(\n", "test_patch": "diff --git a/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/IndentationRuleTest.kt b/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/IndentationRuleTest.kt\nindex eb21667346..22e8d38a80 100644\n--- a/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/IndentationRuleTest.kt\n+++ b/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/IndentationRuleTest.kt\n@@ -3974,7 +3974,7 @@ internal class IndentationRuleTest {\n ).isFormattedAs(formattedCode)\n }\n \n- @Test\n+ @Test // user_type\n fun `Issue 1210 - Given a supertype delegate`() {\n val code =\n \"\"\"\n@@ -4921,6 +4921,19 @@ internal class IndentationRuleTest {\n indentationRuleAssertThat(code).hasNoLintViolations()\n }\n \n+ @Test\n+ fun `Issue 1830 - Given a dot qualified expression followed by an safe access expression on the same line`() {\n+ val code =\n+ \"\"\"\n+ private fun test(): Boolean? =\n+ runCatching { true }\n+ .getOrNull()?.let { result ->\n+ !result\n+ }\n+ \"\"\".trimIndent()\n+ indentationRuleAssertThat(code).hasNoLintViolations()\n+ }\n+\n private companion object {\n val INDENT_STYLE_TAB =\n INDENT_STYLE_PROPERTY to PropertyType.IndentStyleValue.tab\n", "problem_statement": "False positive indent after updating from 0.47.1\n## Expected Behavior\r\n\r\nFollowing code should pass indent validation:\r\n```kotlin\r\n private fun test(): Boolean? =\r\n runCatching { true }\r\n .getOrNull()?.let { result ->\r\n !result\r\n }\r\n```\r\n\r\nIt's also how IDEA indents code.\r\n\r\n## Observed Behavior\r\n\r\n0.48.2 and current master ([44ad030](https://github.com/pinterest/ktlint/commit/44ad0303546f07887058ed444a73cd9c1df1e712)) return:\r\n\r\n```\r\n[LintError(line=4, col=1, ruleId=standard:indent, detail=Unexpected indentation (12) (should be 8), canBeAutoCorrected=true),\r\n LintError(line=5, col=1, ruleId=standard:indent, detail=Unexpected indentation (8) (should be 4), canBeAutoCorrected=true)]\r\n```\r\n\r\nThis snippet was accepted by 0.47.1.\n", "hints_text": "", "created_at": "2023-03-13T17:46:24Z", "version": "0.49", "FAIL_TO_PASS": [ "gradle_test_execution" ], "PASS_TO_PASS": [], "ERROR_TO_PASS": [], "environment_setup_commit": "410d8849874f4d3600f9d4572e0850adccce4f2d" }, { "repo": "pinterest/ktlint", "pull_number": 2026, "instance_id": "pinterest__ktlint-2026", "issue_numbers": [ "2024" ], "base_commit": "48ffc6e2803b07bedb23b584053c117f203d4904", "patch": "diff --git a/CHANGELOG.md b/CHANGELOG.md\nindex b971418b14..428006c0db 100644\n--- a/CHANGELOG.md\n+++ b/CHANGELOG.md\n@@ -10,6 +10,8 @@ This project adheres to [Semantic Versioning](https://semver.org/).\n \n ### Fixed\n \n+* Do not flag a (potential) mutable extension property in case the getter is annotated or prefixed with a modifier `property-naming` ([#2024](https://github.com/pinterest/ktlint/issues/2024))\n+\n ### Changed\n \n ## [0.49.1] - 2023-05-12\ndiff --git a/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/PropertyNamingRule.kt b/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/PropertyNamingRule.kt\nindex 9942f64ae7..d3d4a00131 100644\n--- a/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/PropertyNamingRule.kt\n+++ b/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/PropertyNamingRule.kt\n@@ -3,6 +3,7 @@ package com.pinterest.ktlint.ruleset.standard.rules\n import com.pinterest.ktlint.rule.engine.core.api.ElementType.CLASS_BODY\n import com.pinterest.ktlint.rule.engine.core.api.ElementType.CONST_KEYWORD\n import com.pinterest.ktlint.rule.engine.core.api.ElementType.FILE\n+import com.pinterest.ktlint.rule.engine.core.api.ElementType.GET_KEYWORD\n import com.pinterest.ktlint.rule.engine.core.api.ElementType.IDENTIFIER\n import com.pinterest.ktlint.rule.engine.core.api.ElementType.MODIFIER_LIST\n import com.pinterest.ktlint.rule.engine.core.api.ElementType.OBJECT_DECLARATION\n@@ -102,10 +103,7 @@ public class PropertyNamingRule :\n }\n }\n \n- private fun ASTNode.hasCustomGetter() =\n- findChildByType(PROPERTY_ACCESSOR)\n- ?.firstChildNode\n- ?.text == \"get\"\n+ private fun ASTNode.hasCustomGetter() = findChildByType(PROPERTY_ACCESSOR)?.findChildByType(GET_KEYWORD) != null\n \n private fun ASTNode.hasConstModifier() = hasModifier(CONST_KEYWORD)\n \n", "test_patch": "diff --git a/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/PropertyNamingRuleTest.kt b/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/PropertyNamingRuleTest.kt\nindex 0081183fe8..99768a1aab 100644\n--- a/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/PropertyNamingRuleTest.kt\n+++ b/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/PropertyNamingRuleTest.kt\n@@ -104,6 +104,20 @@ class PropertyNamingRuleTest {\n propertyNamingRuleAssertThat(code).hasNoLintViolations()\n }\n \n+ @Test\n+ fun `Given a top level property extension function having a custom get function and not in screaming case notation then do not emit`() {\n+ val code =\n+ \"\"\"\n+ val fooBar1: Any\n+ get() = foobar() // Lint can not check whether data is immutable\n+ val fooBar2\n+ inline get() = foobar() // Lint can not check whether data is immutable\n+ val fooBar3\n+ @Bar get() = foobar() // Lint can not check whether data is immutable\n+ \"\"\".trimIndent()\n+ propertyNamingRuleAssertThat(code).hasNoLintViolations()\n+ }\n+\n @Test\n fun `Given a backing val property name having a custom get function and not in screaming case notation then do not emit`() {\n val code =\n", "problem_statement": "property-naming flags extension properties\nThe following code gets flagged with 0.49.1:\r\n\r\n```kotlin\r\nval Context.adsDelegateFactory @SuppressLint(\"WrongConstant\") get() =\r\n applicationContext.getSystemService(SYSTEM_SERVICE_AD_DELEGATE_FACTORY) as AdsDelegateFactory\r\n```\r\n\r\n> Property name should use the screaming snake case notation when the value can not be changed (standard:property-naming)\r\n\r\nI would not expect this, if you're adding a property via an extension and leveraging `get()` since the value can indeed change inside the implementation.\n", "hints_text": "So when I remove `@SuppressLint(\"WrongConstant\")` it does not get flagged as expected. So there's something weird going on.\nIndeed, the annotation causes the check to fail. Same happens with:\r\n```\r\nval Context.adsDelegateFactory private get() =\r\n applicationContext.getSystemService(SYSTEM_SERVICE_AD_DELEGATE_FACTORY) as AdsDelegateFactory\r\n```\nProblem will either be resolved in `0.49.2` only when more pressing bugs need to be fixed. Otherwise it will be fixed in the next normal release.", "created_at": "2023-05-14T18:55:48Z", "version": "0.49", "FAIL_TO_PASS": [ "gradle_test_execution" ], "PASS_TO_PASS": [], "ERROR_TO_PASS": [], "environment_setup_commit": "410d8849874f4d3600f9d4572e0850adccce4f2d" }, { "repo": "pinterest/ktlint", "pull_number": 1923, "instance_id": "pinterest__ktlint-1923", "issue_numbers": [ "1904" ], "base_commit": "c9a3d2aa32865c7d52867dbde4b6174f3260d6a2", "patch": "diff --git a/CHANGELOG.md b/CHANGELOG.md\nindex 472119cf52..85f32bc34c 100644\n--- a/CHANGELOG.md\n+++ b/CHANGELOG.md\n@@ -292,6 +292,7 @@ if (node.isRoot()) {\n * Add newline after adding trailing comma in parameter list of a function literal `trailing-comma-on-declaration-site` ([#1911](https://github.com/pinterest/ktlint/issues/1911))\n * Wrap annotations before class constructor in code style `ktlint_official`. `annotation` ([#1916](https://github.com/pinterest/ktlint/issues/1916))\n * Annotations on type projections should be wrapped in same way as other annotations `annotation` ([#1917](https://github.com/pinterest/ktlint/issues/1917))\n+* An if-else followed by an elvis operator should not be wrapped in an else-block `multiline-if-else` ([#1904](https://github.com/pinterest/ktlint/issues/1904))\n \n ### Changed\n * Wrap the parameters of a function literal containing a multiline parameter list (only in `ktlint_official` code style) `parameter-list-wrapping` ([#1681](https://github.com/pinterest/ktlint/issues/1681)).\ndiff --git a/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/MultiLineIfElseRule.kt b/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/MultiLineIfElseRule.kt\nindex 33f6a6e460..3fe1e6aee9 100644\n--- a/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/MultiLineIfElseRule.kt\n+++ b/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/MultiLineIfElseRule.kt\n@@ -1,6 +1,8 @@\n package com.pinterest.ktlint.ruleset.standard.rules\n \n+import com.pinterest.ktlint.rule.engine.core.api.ElementType.BINARY_EXPRESSION\n import com.pinterest.ktlint.rule.engine.core.api.ElementType.BLOCK\n+import com.pinterest.ktlint.rule.engine.core.api.ElementType.DOT_QUALIFIED_EXPRESSION\n import com.pinterest.ktlint.rule.engine.core.api.ElementType.ELSE\n import com.pinterest.ktlint.rule.engine.core.api.ElementType.ELSE_KEYWORD\n import com.pinterest.ktlint.rule.engine.core.api.ElementType.IF\n@@ -52,29 +54,54 @@ public class MultiLineIfElseRule :\n autoCorrect: Boolean,\n emit: (offset: Int, errorMessage: String, canBeAutoCorrected: Boolean) -> Unit,\n ) {\n- if (node.elementType == THEN || node.elementType == ELSE) {\n- if (node.firstChildNode?.elementType == BLOCK) {\n+ if (node.elementType != THEN && node.elementType != ELSE) {\n+ return\n+ }\n+\n+ // Ignore when already wrapped in a block\n+ if (node.firstChildNode?.elementType == BLOCK) {\n+ return\n+ }\n+\n+ if (node.elementType == ELSE && node.firstChildNode?.elementType == BINARY_EXPRESSION) {\n+ // Allow\n+ // val foo = if (bar1) {\n+ // \"bar1\"\n+ // } else {\n+ // null\n+ // } ?: \"something-else\"\n+ return\n+ }\n+\n+ if (node.elementType == ELSE && node.firstChildNode?.elementType == DOT_QUALIFIED_EXPRESSION) {\n+ // Allow\n+ // val foo = if (bar1) {\n+ // \"bar1\"\n+ // } else {\n+ // \"bar2\"\n+ // }.plus(\"foo\")\n+ return\n+ }\n+\n+ if (!node.treePrev.textContains('\\n')) {\n+ if (node.firstChildNode.elementType == IF) {\n+ // Allow single line for:\n+ // else if (...)\n return\n }\n-\n- if (!node.treePrev.textContains('\\n')) {\n- if (node.firstChildNode.elementType == IF) {\n- // Allow single line for:\n- // else if (...)\n- return\n- }\n- if (!node.treeParent.textContains('\\n')) {\n- // Allow single line if statements as long as they are really simple (e.g. do not contain newlines)\n- // if (...) // no else statement\n- // if (...) else \n- return\n- }\n+ if (!node.treeParent.textContains('\\n')) {\n+ // Allow single line if statements as long as they are really simple (e.g. do not contain newlines)\n+ // if (...) // no else statement\n+ // if (...) else \n+ return\n }\n \n- emit(node.firstChildNode.startOffset, \"Missing { ... }\", true)\n- if (autoCorrect) {\n- autocorrect(node)\n- }\n+ Unit\n+ }\n+\n+ emit(node.firstChildNode.startOffset, \"Missing { ... }\", true)\n+ if (autoCorrect) {\n+ autocorrect(node)\n }\n }\n \n", "test_patch": "diff --git a/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/MultiLineIfElseRuleTest.kt b/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/MultiLineIfElseRuleTest.kt\nindex a2f553902e..e509735182 100644\n--- a/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/MultiLineIfElseRuleTest.kt\n+++ b/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/MultiLineIfElseRuleTest.kt\n@@ -569,4 +569,32 @@ class MultiLineIfElseRuleTest {\n LintViolation(3, 10, \"Missing { ... }\"),\n ).isFormattedAs(formattedCode)\n }\n+\n+ @Test\n+ fun `Issue 1904 - Given an nested if else statement followed by an elvis operator`() {\n+ val code =\n+ \"\"\"\n+ val foo = if (bar1) {\n+ \"bar1\"\n+ } else {\n+ null\n+ } ?: \"something-else\"\n+ \"\"\".trimIndent()\n+ multiLineIfElseRuleAssertThat(code).hasNoLintViolations()\n+ }\n+\n+ @Test\n+ fun `Issue 1904 - Given an nested if else statement and else which is part of a dot qualified expression`() {\n+ val code =\n+ \"\"\"\n+ val foo = if (bar1) {\n+ \"bar1\"\n+ } else if (bar2) {\n+ \"bar2\"\n+ } else {\n+ \"bar3\"\n+ }.plus(\"foo\")\n+ \"\"\".trimIndent()\n+ multiLineIfElseRuleAssertThat(code).hasNoLintViolations()\n+ }\n }\n", "problem_statement": "False positive at multiline-if-else when using \"else if\"\n\r\n## Expected Behavior\r\n```\r\nelse if () {\r\n}\r\n```\r\nShould stay as is\r\n\r\n\r\n## Observed Behavior\r\nIt gets formatted to\r\n```\r\nelse {\r\n if () {\r\n }\r\n}\r\n```\r\n\r\n## Steps to Reproduce\r\n```\r\n val x = if (showFilter) {\r\n 1\r\n } else if (activeTabIndex.value == 0) {\r\n 2\r\n } else {\r\n null\r\n } ?: 0\r\n```\r\n\r\n-->\r\n\r\n```\r\n val x = if (showFilter) {\r\n 1\r\n } else {\r\n if (activeTabIndex.value == 0) {\r\n 2\r\n } else {\r\n null\r\n } ?: 0\r\n }\r\n```\r\n\r\n## Your Environment\r\n* Version of ktlint used: 0.48.2\r\n* Relevant parts of the `.editorconfig` settings\r\n* Operating System and version: macOS\r\n\n", "hints_text": "Tnx for reporting. It is just in time to be fixed in next release.\nSimilarly the example below should be accepted without reformatting as well:\r\n```\r\nval foo = if (bar1) {\r\n \"bar1\"\r\n} else if (bar2) {\r\n \"bar2\"\r\n} else {\r\n \"bar3\"\r\n}.plus(\"foo\")\r\n``` ", "created_at": "2023-04-07T18:29:17Z", "version": "0.49", "FAIL_TO_PASS": [ "gradle_test_execution" ], "PASS_TO_PASS": [], "ERROR_TO_PASS": [], "environment_setup_commit": "410d8849874f4d3600f9d4572e0850adccce4f2d" }, { "repo": "pinterest/ktlint", "pull_number": 1843, "instance_id": "pinterest__ktlint-1843", "issue_numbers": [ "1764" ], "base_commit": "315e75d0a4523ae6035f53a58d936bbdb4fbcf90", "patch": "diff --git a/CHANGELOG.md b/CHANGELOG.md\nindex 37b0e98bbd..9b1bf54ad3 100644\n--- a/CHANGELOG.md\n+++ b/CHANGELOG.md\n@@ -243,6 +243,7 @@ Previously the default value for `.editorconfig` property `max_line_length` was\n * Fix continuation indent for a dot qualified array access expression in `ktlint_official` code style only `indent` ([#1540](https://github.com/pinterest/ktlint/issues/1540)).\n * When generating the `.editorconfig` use value `off` for the `max_line_length` property instead of value `-1` to denote that lines are not restricted to a maximum length ([#1824](https://github.com/pinterest/ktlint/issues/1824)).\n * Do not report an \"unnecessary semicolon\" after adding a trailing comma to an enum class containing a code element after the last enum entry `trailing-comma-on-declaration-site` ([#1786](https://github.com/pinterest/ktlint/issues/1786))\n+* A newline before a function return type should not be removed in case that leads to exceeding the maximum line length `function-return-type-spacing` ([#1764](https://github.com/pinterest/ktlint/issues/1764))\n \n ### Changed\n * Wrap the parameters of a function literal containing a multiline parameter list (only in `ktlint_official` code style) `parameter-list-wrapping` ([#1681](https://github.com/pinterest/ktlint/issues/1681)).\ndiff --git a/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/FunctionReturnTypeSpacingRule.kt b/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/FunctionReturnTypeSpacingRule.kt\nindex 06a2f93e3c..aa60f19de1 100644\n--- a/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/FunctionReturnTypeSpacingRule.kt\n+++ b/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/FunctionReturnTypeSpacingRule.kt\n@@ -5,15 +5,28 @@ import com.pinterest.ktlint.rule.engine.core.api.ElementType.FUN\n import com.pinterest.ktlint.rule.engine.core.api.ElementType.WHITE_SPACE\n import com.pinterest.ktlint.rule.engine.core.api.Rule\n import com.pinterest.ktlint.rule.engine.core.api.RuleId\n+import com.pinterest.ktlint.rule.engine.core.api.editorconfig.EditorConfig\n+import com.pinterest.ktlint.rule.engine.core.api.editorconfig.MAX_LINE_LENGTH_PROPERTY\n+import com.pinterest.ktlint.rule.engine.core.api.isWhiteSpaceWithNewline\n import com.pinterest.ktlint.rule.engine.core.api.nextLeaf\n import com.pinterest.ktlint.rule.engine.core.api.prevLeaf\n import com.pinterest.ktlint.rule.engine.core.api.upsertWhitespaceAfterMe\n import com.pinterest.ktlint.ruleset.standard.StandardRule\n import org.jetbrains.kotlin.com.intellij.lang.ASTNode\n+import org.jetbrains.kotlin.psi.psiUtil.leaves\n \n public class FunctionReturnTypeSpacingRule :\n- StandardRule(\"function-return-type-spacing\"),\n+ StandardRule(\n+ id = \"function-return-type-spacing\",\n+ usesEditorConfigProperties = setOf(MAX_LINE_LENGTH_PROPERTY),\n+ ),\n Rule.Experimental {\n+ private var maxLineLength = MAX_LINE_LENGTH_PROPERTY.defaultValue\n+\n+ override fun beforeFirstNode(editorConfig: EditorConfig) {\n+ maxLineLength = editorConfig[MAX_LINE_LENGTH_PROPERTY]\n+ }\n+\n override fun beforeVisitChildNodes(\n node: ASTNode,\n autoCorrect: Boolean,\n@@ -57,13 +70,38 @@ public class FunctionReturnTypeSpacingRule :\n ?.takeIf { it.elementType == WHITE_SPACE }\n .let { whiteSpaceAfterColon ->\n if (whiteSpaceAfterColon?.text != \" \") {\n- emit(node.startOffset, \"Single space expected between colon and return type\", true)\n- if (autoCorrect) {\n- node.upsertWhitespaceAfterMe(\" \")\n+ // In case the whitespace contains a newline than replacing it with a single space results in merging the lines to a\n+ // single line. This rule allows this only when the merged lines entirely fit on a single line. Suppose that code below\n+ // does not fit on a single line:\n+ // fun foo():\n+ // String = \"some-looooooooooooooooong-string\"\n+ // This rule does *not* attempt to reformat the code as follows:\n+ // fun foo(): String =\n+ // \"some-looooooooooooooooong-string\"\n+ // See FunctionSignatureRule for such reformatting.\n+ val newLineLength =\n+ node.lengthUntilNewline(false) + // Length of line before but excluding the colon\n+ node.textLength + // Length of the colon itself\n+ 1 + // Length of the fixed whitespace\n+ whiteSpaceAfterColon.lengthUntilNewline(true) // Length of the line after but excluding the whitespace\n+ if (newLineLength <= maxLineLength) {\n+ emit(node.startOffset, \"Single space expected between colon and return type\", true)\n+ if (autoCorrect) {\n+ node.upsertWhitespaceAfterMe(\" \")\n+ }\n }\n }\n }\n }\n+\n+ private fun ASTNode?.lengthUntilNewline(forward: Boolean) =\n+ if (this == null) {\n+ 0\n+ } else {\n+ leaves(forward = forward)\n+ .takeWhile { !it.isWhiteSpaceWithNewline() }\n+ .sumOf { it.textLength }\n+ }\n }\n \n public val FUNCTION_RETURN_TYPE_SPACING_RULE_ID: RuleId = FunctionReturnTypeSpacingRule().ruleId\n", "test_patch": "diff --git a/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/FunctionReturnTypeSpacingRuleTest.kt b/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/FunctionReturnTypeSpacingRuleTest.kt\nindex e77f7e35ee..644d0fa541 100644\n--- a/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/FunctionReturnTypeSpacingRuleTest.kt\n+++ b/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/FunctionReturnTypeSpacingRuleTest.kt\n@@ -1,5 +1,7 @@\n package com.pinterest.ktlint.ruleset.standard.rules\n \n+import com.pinterest.ktlint.test.KtLintAssertThat.Companion.EOL_CHAR\n+import com.pinterest.ktlint.test.KtLintAssertThat.Companion.MAX_LINE_LENGTH_MARKER\n import com.pinterest.ktlint.test.KtLintAssertThat.Companion.assertThatRule\n import org.junit.jupiter.api.Test\n \n@@ -91,4 +93,41 @@ class FunctionReturnTypeSpacingRuleTest {\n .hasLintViolation(1, 10, \"Single space expected between colon and return type\")\n .isFormattedAs(formattedCode)\n }\n+\n+ @Test\n+ fun `Given a function signature with a new line between the colon and the return type which when concatenated does not exceed the maximum line length then do reformat`() {\n+ val code =\n+ \"\"\"\n+ // $MAX_LINE_LENGTH_MARKER $EOL_CHAR\n+ fun foo():\n+ String = \"some-result\"\n+ \"\"\".trimIndent()\n+ val formattedCode =\n+ \"\"\"\n+ // $MAX_LINE_LENGTH_MARKER $EOL_CHAR\n+ fun foo(): String = \"some-result\"\n+ \"\"\".trimIndent()\n+ functionReturnTypeSpacingRuleAssertThat(code)\n+ .setMaxLineLength()\n+ .hasLintViolation(2, 10, \"Single space expected between colon and return type\")\n+ .isFormattedAs(formattedCode)\n+ }\n+\n+ @Test\n+ fun `Given a function signature with a new line between the colon and the return type which when concatenated does exceed the maximum line length then do not reformat`() {\n+ val code =\n+ \"\"\"\n+ // $MAX_LINE_LENGTH_MARKER $EOL_CHAR\n+ fun foo():\n+ String = \"some-result\"\n+ \"\"\".trimIndent()\n+ val formattedCode =\n+ \"\"\"\n+ // $MAX_LINE_LENGTH_MARKER $EOL_CHAR\n+ fun foo(): String = \"some-result\"\n+ \"\"\".trimIndent()\n+ functionReturnTypeSpacingRuleAssertThat(code)\n+ .setMaxLineLength()\n+ .hasNoLintViolations()\n+ }\n }\n", "problem_statement": "experimental:function-return-type-spacing can violate max-line rule\n\r\n\r\n## Steps to Reproduce\r\n\r\n\r\n\r\n\r\n\r\n```\r\n fun thisIsAVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryLongFunction():\r\n AndAlsoALongReturnType {\r\n\r\n }\r\n```\r\n\r\nwill reformat to:\r\n```\r\n fun thisIsAVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryLongFunction(): AndAlsoALongReturnType {\r\n\r\n }\r\n```\r\n\r\nWhich will violate the max-line-length rule.\r\n\r\nThe rule may need to make an exception for parameterless functions, or honor the max line length.\r\n\r\n## Your Environment\r\n\r\n* Version of ktlint used:\r\n* Relevant parts of the `.editorconfig` settings\r\n```\r\n[*.{kt,kts}]\r\nmax_line_length = 120\r\n```\r\n* Name and version (or code for custom task) of integration used (Gradle plugin, Maven plugin, command line, custom Gradle task): ktlint 0.48.1, CLI\r\n\n", "hints_text": "", "created_at": "2023-03-07T11:30:47Z", "version": "0.49", "FAIL_TO_PASS": [ "gradle_test_execution" ], "PASS_TO_PASS": [], "ERROR_TO_PASS": [], "environment_setup_commit": "410d8849874f4d3600f9d4572e0850adccce4f2d" }, { "repo": "pinterest/ktlint", "pull_number": 1857, "instance_id": "pinterest__ktlint-1857", "issue_numbers": [ "1845" ], "base_commit": "7f323befc51af1d38eca3a16d2c0ff1b2c7edb5b", "patch": "diff --git a/CHANGELOG.md b/CHANGELOG.md\nindex 674682ba0d..65486fb6ac 100644\n--- a/CHANGELOG.md\n+++ b/CHANGELOG.md\n@@ -253,6 +253,7 @@ Previously the default value for `.editorconfig` property `max_line_length` was\n * Fix false positive when multiple KDOCs exists between a declaration and another annotated declaration `spacing-between-declarations-with-annotations` ([#1802](https://github.com/pinterest/ktlint/issues/1802))\n * Fix false positive when a single line statement containing a block having exactly the maximum line length is preceded by a blank line `wrapping` ([#1808](https://github.com/pinterest/ktlint/issues/1808))\n * Fix false positive when a single line contains multiple dot qualified expressions and/or safe expressions `indent` ([#1830](https://github.com/pinterest/ktlint/issues/1830))\n+* When `.editorconfig` property `ij_kotlin_imports_layout` contains a `|` but no import exists that match any pattern before the first `|` then do not report a violation nor insert a blank line `import-ordering` ([#1845](https://github.com/pinterest/ktlint/issues/1845))\n \n ### Changed\n * Wrap the parameters of a function literal containing a multiline parameter list (only in `ktlint_official` code style) `parameter-list-wrapping` ([#1681](https://github.com/pinterest/ktlint/issues/1681)).\ndiff --git a/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/ImportOrderingRule.kt b/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/ImportOrderingRule.kt\nindex 32fe19b3fd..b312b5a49a 100644\n--- a/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/ImportOrderingRule.kt\n+++ b/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/ImportOrderingRule.kt\n@@ -84,7 +84,7 @@ public class ImportOrderingRule :\n break\n }\n }\n- if (hasBlankLines) {\n+ if (hasBlankLines && prev != null) {\n sortedImportsWithSpaces += PsiWhiteSpaceImpl(\"\\n\\n\")\n }\n sortedImportsWithSpaces += current\n", "test_patch": "diff --git a/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/importordering/ImportOrderingRuleCustomTest.kt b/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/importordering/ImportOrderingRuleCustomTest.kt\nindex 78c57d8960..2b13cce496 100644\n--- a/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/importordering/ImportOrderingRuleCustomTest.kt\n+++ b/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/importordering/ImportOrderingRuleCustomTest.kt\n@@ -247,4 +247,24 @@ class ImportOrderingRuleCustomTest {\n .withEditorConfigOverride(IJ_KOTLIN_IMPORTS_LAYOUT_PROPERTY to \"kotlin.io.Closeable.*,kotlin.**,*\")\n .isFormattedAs(formattedCode)\n }\n+\n+ @Test\n+ fun `Issue 1845 - Given a list of pattern entries including a '|' pattern but no import exists that match any pattern before the first '|'`() {\n+ val code =\n+ \"\"\"\n+ import java.nio.file.Files\n+ import java.nio.file.Paths\n+ import java.util.Objects\n+\n+ object TestData {\n+ fun loadString(dataset: String): String {\n+ val path = Paths.get(Objects.requireNonNull(TestData::class.java.getResource(dataset)).toURI())\n+ return String(Files.readAllBytes(path))\n+ }\n+ }\n+ \"\"\".trimIndent()\n+ importOrderingRuleAssertThat(code)\n+ .withEditorConfigOverride(IJ_KOTLIN_IMPORTS_LAYOUT_PROPERTY to \"*, |, javax.**, java.**, |, kotlinx.**, kotlin.**\")\n+ .hasNoLintViolations()\n+ }\n }\n", "problem_statement": "`ij_kotlin_imports_layout` with `|` generates multiple line breaks\n## Expected Behavior\r\nI'm currently using the `import-ordering` rule with the following config:\r\n```\r\nij_kotlin_imports_layout = *, |, javax.**, java.**, |, kotlinx.**, kotlin.**\r\n```\r\n\r\nI'd expect one of my files to be formatted like:\r\n```\r\npackage test\r\n\r\nimport java.nio.file.Files\r\nimport java.nio.file.Paths\r\nimport java.util.Objects\r\n\r\nobject TestData {\r\n fun loadString(dataset: String): String {\r\n val path = Paths.get(Objects.requireNonNull(TestData::class.java.getResource(dataset)).toURI())\r\n return String(Files.readAllBytes(path))\r\n }\r\n}\r\n```\r\n\r\n## Observed Behavior\r\nFor some reason (I assume because of the two `|` in the layout config and not having any imports that match `*`), I got two extra line breaks in the file:\r\n```\r\npackage test\r\n\r\n\r\n\r\nimport java.nio.file.Files\r\nimport java.nio.file.Paths\r\nimport java.util.Objects\r\n\r\nobject TestData {\r\n fun loadString(dataset: String): String {\r\n val path = Paths.get(Objects.requireNonNull(TestData::class.java.getResource(dataset)).toURI())\r\n return String(Files.readAllBytes(path))\r\n }\r\n}\r\n```\r\n\r\nIt seems that the number of extra line breaks is equals the number of `|` in the config, but if I remove the extra line breaks, I have to run `ktlint -F` twice until it stabilises, which makes the issue even worse.\r\n\r\n## Steps to Reproduce\r\nUse the configuration and file above.\r\n\r\n## Your Environment\r\n* Version of ktlint used: 0.48.2\r\n* Relevant parts of the `.editorconfig` settings: (mentioned above)\r\n\n", "hints_text": "This seems to be a regression bug in `0.48.2`. It works fine with `0.48.1`.", "created_at": "2023-03-13T19:34:30Z", "version": "0.49", "FAIL_TO_PASS": [ "gradle_test_execution" ], "PASS_TO_PASS": [], "ERROR_TO_PASS": [], "environment_setup_commit": "410d8849874f4d3600f9d4572e0850adccce4f2d" }, { "repo": "pinterest/ktlint", "pull_number": 1920, "instance_id": "pinterest__ktlint-1920", "issue_numbers": [ "1916", "1917" ], "base_commit": "07297749f99ce457e7a6f18e24e4eea4c5afc4ba", "patch": "diff --git a/CHANGELOG.md b/CHANGELOG.md\nindex 18caaa55d2..bdbdb9d7fe 100644\n--- a/CHANGELOG.md\n+++ b/CHANGELOG.md\n@@ -280,6 +280,8 @@ Previously the default value for `.editorconfig` property `max_line_length` was\n * Wrap annotated function parameters to a separate line in code style `ktlint_official` only. `function-signature`, `parameter-list-wrapping` ([#1908](https://github.com/pinterest/ktlint/issues/1908))\n * Wrap annotated projection types in type argument lists to a separate line `annotation` ([#1909](https://github.com/pinterest/ktlint/issues/1909))\n * Add newline after adding trailing comma in parameter list of a function literal `trailing-comma-on-declaration-site` ([#1911](https://github.com/pinterest/ktlint/issues/1911))\n+* Wrap annotations before class constructor in code style `ktlint_official`. `annotation` ([#1916](https://github.com/pinterest/ktlint/issues/1916))\n+* Annotations on type projections should be wrapped in same way as other annotations `annotation` ([#1917](https://github.com/pinterest/ktlint/issues/1917))\n \n ### Changed\n * Wrap the parameters of a function literal containing a multiline parameter list (only in `ktlint_official` code style) `parameter-list-wrapping` ([#1681](https://github.com/pinterest/ktlint/issues/1681)).\ndiff --git a/ktlint-cli/src/main/kotlin/com/pinterest/ktlint/cli/api/Baseline.kt b/ktlint-cli/src/main/kotlin/com/pinterest/ktlint/cli/api/Baseline.kt\nindex 6832fd5764..0806d19aec 100644\n--- a/ktlint-cli/src/main/kotlin/com/pinterest/ktlint/cli/api/Baseline.kt\n+++ b/ktlint-cli/src/main/kotlin/com/pinterest/ktlint/cli/api/Baseline.kt\n@@ -164,10 +164,14 @@ private class BaselineLoader(private val path: String) {\n col = getAttribute(\"column\").toInt(),\n ruleId =\n getAttribute(\"source\")\n- .let {\n+ .let { ruleId ->\n // Ensure backwards compatibility with baseline files in which the rule set id for standard rules is not saved\n- RuleId.prefixWithStandardRuleSetIdWhenMissing(it)\n- .also { ruleReferenceWithoutRuleSetIdPrefix++ }\n+ RuleId.prefixWithStandardRuleSetIdWhenMissing(ruleId)\n+ .also { prefixedRuleId ->\n+ if (prefixedRuleId != ruleId) {\n+ ruleReferenceWithoutRuleSetIdPrefix++\n+ }\n+ }\n },\n detail = \"\", // Not available in the baseline\n status = BASELINE_IGNORED,\ndiff --git a/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/AnnotationRule.kt b/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/AnnotationRule.kt\nindex bdddca0835..7dbe0f6a16 100644\n--- a/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/AnnotationRule.kt\n+++ b/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/AnnotationRule.kt\n@@ -1,47 +1,47 @@\n package com.pinterest.ktlint.ruleset.standard.rules\n \n-import com.pinterest.ktlint.rule.engine.core.api.ElementType\n import com.pinterest.ktlint.rule.engine.core.api.ElementType.ANNOTATED_EXPRESSION\n import com.pinterest.ktlint.rule.engine.core.api.ElementType.ANNOTATION\n import com.pinterest.ktlint.rule.engine.core.api.ElementType.ANNOTATION_ENTRY\n+import com.pinterest.ktlint.rule.engine.core.api.ElementType.BLOCK\n+import com.pinterest.ktlint.rule.engine.core.api.ElementType.CONSTRUCTOR_KEYWORD\n import com.pinterest.ktlint.rule.engine.core.api.ElementType.FILE_ANNOTATION_LIST\n+import com.pinterest.ktlint.rule.engine.core.api.ElementType.GT\n import com.pinterest.ktlint.rule.engine.core.api.ElementType.MODIFIER_LIST\n+import com.pinterest.ktlint.rule.engine.core.api.ElementType.TYPE_ARGUMENT_LIST\n import com.pinterest.ktlint.rule.engine.core.api.ElementType.TYPE_PROJECTION\n import com.pinterest.ktlint.rule.engine.core.api.ElementType.TYPE_REFERENCE\n import com.pinterest.ktlint.rule.engine.core.api.ElementType.VALUE_ARGUMENT\n import com.pinterest.ktlint.rule.engine.core.api.ElementType.VALUE_ARGUMENT_LIST\n import com.pinterest.ktlint.rule.engine.core.api.ElementType.VALUE_PARAMETER\n-import com.pinterest.ktlint.rule.engine.core.api.ElementType.WHITE_SPACE\n import com.pinterest.ktlint.rule.engine.core.api.IndentConfig\n import com.pinterest.ktlint.rule.engine.core.api.Rule.VisitorModifier.RunAfterRule\n import com.pinterest.ktlint.rule.engine.core.api.Rule.VisitorModifier.RunAfterRule.Mode.REGARDLESS_WHETHER_RUN_AFTER_RULE_IS_LOADED_OR_DISABLED\n import com.pinterest.ktlint.rule.engine.core.api.RuleId\n import com.pinterest.ktlint.rule.engine.core.api.children\n import com.pinterest.ktlint.rule.engine.core.api.editorconfig.CODE_STYLE_PROPERTY\n+import com.pinterest.ktlint.rule.engine.core.api.editorconfig.CodeStyleValue\n import com.pinterest.ktlint.rule.engine.core.api.editorconfig.EditorConfig\n import com.pinterest.ktlint.rule.engine.core.api.editorconfig.INDENT_SIZE_PROPERTY\n import com.pinterest.ktlint.rule.engine.core.api.editorconfig.INDENT_STYLE_PROPERTY\n import com.pinterest.ktlint.rule.engine.core.api.firstChildLeafOrSelf\n-import com.pinterest.ktlint.rule.engine.core.api.isCodeLeaf\n+import com.pinterest.ktlint.rule.engine.core.api.indent\n import com.pinterest.ktlint.rule.engine.core.api.isWhiteSpace\n import com.pinterest.ktlint.rule.engine.core.api.isWhiteSpaceWithNewline\n import com.pinterest.ktlint.rule.engine.core.api.lastChildLeafOrSelf\n import com.pinterest.ktlint.rule.engine.core.api.nextCodeLeaf\n-import com.pinterest.ktlint.rule.engine.core.api.nextLeaf\n-import com.pinterest.ktlint.rule.engine.core.api.prevCodeLeaf\n+import com.pinterest.ktlint.rule.engine.core.api.nextCodeSibling\n+import com.pinterest.ktlint.rule.engine.core.api.nextSibling\n import com.pinterest.ktlint.rule.engine.core.api.prevLeaf\n import com.pinterest.ktlint.rule.engine.core.api.upsertWhitespaceAfterMe\n import com.pinterest.ktlint.rule.engine.core.api.upsertWhitespaceBeforeMe\n import com.pinterest.ktlint.rule.engine.core.util.safeAs\n import com.pinterest.ktlint.ruleset.standard.StandardRule\n import org.jetbrains.kotlin.com.intellij.lang.ASTNode\n-import org.jetbrains.kotlin.com.intellij.psi.impl.source.tree.LeafPsiElement\n-import org.jetbrains.kotlin.com.intellij.psi.impl.source.tree.PsiWhiteSpaceImpl\n import org.jetbrains.kotlin.descriptors.annotations.AnnotationUseSiteTarget\n import org.jetbrains.kotlin.psi.KtAnnotationEntry\n-import org.jetbrains.kotlin.psi.psiUtil.leaves\n import org.jetbrains.kotlin.psi.psiUtil.siblings\n-import org.jetbrains.kotlin.utils.addToStdlib.applyIf\n+import org.jetbrains.kotlin.utils.addToStdlib.ifTrue\n \n /**\n * Ensures that annotation are wrapped to separate lines.\n@@ -107,8 +107,12 @@ public class AnnotationRule :\n ) {\n when (node.elementType) {\n FILE_ANNOTATION_LIST -> {\n+ visitAnnotationList(node, emit, autoCorrect)\n visitFileAnnotationList(node, emit, autoCorrect)\n }\n+ ANNOTATED_EXPRESSION, MODIFIER_LIST -> {\n+ visitAnnotationList(node, emit, autoCorrect)\n+ }\n ANNOTATION -> {\n // Annotation array\n // @[...]\n@@ -117,116 +121,186 @@ public class AnnotationRule :\n ANNOTATION_ENTRY -> {\n visitAnnotationEntry(node, emit, autoCorrect)\n }\n+ TYPE_ARGUMENT_LIST -> {\n+ visitTypeArgumentList(node, emit, autoCorrect)\n+ }\n }\n }\n \n- private fun visitAnnotationEntry(\n+ private fun visitAnnotationList(\n node: ASTNode,\n emit: (offset: Int, errorMessage: String, canBeAutoCorrected: Boolean) -> Unit,\n autoCorrect: Boolean,\n ) {\n- require(node.elementType == ANNOTATION_ENTRY)\n+ require(node.elementType in ANNOTATION_CONTAINER)\n+\n+ if (node.shouldWrapAnnotations()) {\n+ val expectedIndent =\n+ when {\n+ node.elementType == ANNOTATED_EXPRESSION ->\n+ node.treeParent.indent().plus(indentConfig.indent)\n+ node.hasAnnotationBeforeConstructor() ->\n+ node.treeParent.treeParent.indent().plus(indentConfig.indent)\n+ else ->\n+ node.treeParent.indent()\n+ }\n \n- if (node.isAnnotationEntryWithValueArgumentList() &&\n- node.treeParent.treeParent.elementType != VALUE_PARAMETER &&\n- node.treeParent.treeParent.elementType != VALUE_ARGUMENT &&\n- node.isNotReceiverTargetAnnotation()\n- ) {\n- // Disallow:\n- // @Foo class Bar\n- // Allow function parameters and arguments to have annotation on same line as identifier:\n- // fun @receiver:Bar String.foo() {}\n- // fun foo(\n- // @Bar(\"bar\") bar,\n- // @Bar(\"bar\") \"42\",\n- // ) {}\n- checkForAnnotationWithParameterToBePlacedOnSeparateLine(node, emit, autoCorrect)\n- }\n+ node\n+ .children()\n+ .filter { it.elementType == ANNOTATION_ENTRY }\n+ .filter {\n+ it.isAnnotationEntryWithValueArgumentList() ||\n+ !it.isPrecededByOtherAnnotationEntryWithoutParametersOnTheSameLine()\n+ }.forEach { annotationEntry ->\n+ annotationEntry\n+ .prevLeaf()\n+ ?.let { prevLeaf ->\n+ // Let the indentation rule determine the exact indentation and only report and fix when the line needs to be\n+ // wrapped\n+ if (!prevLeaf.textContains('\\n')) {\n+ emit(prevLeaf.startOffset, \"Expected newline before annotation\", true)\n+ if (autoCorrect) {\n+ prevLeaf.upsertWhitespaceBeforeMe(\n+ prevLeaf\n+ .text\n+ .substringBeforeLast('\\n', \"\")\n+ .plus(expectedIndent),\n+ )\n+ }\n+ }\n+ }\n+ }\n \n- if (node.isOnSameLineAsAnnotatedConstruct()) {\n- if (node.isPrecededByAnnotationOnAnotherLine()) {\n- // Code below is disallowed\n- // @Foo1\n- // @Foo2 fun foo() {}\n- emit(\n- node.startOffset,\n- \"Annotation must be placed on a separate line when it is preceded by another annotation on a separate line\",\n- true,\n- )\n- if (autoCorrect) {\n- node\n- .lastChildLeafOrSelf()\n- .nextLeaf()\n- ?.upsertWhitespaceBeforeMe(getNewlineWithIndent(node.treeParent))\n+ node\n+ .children()\n+ .last { it.elementType == ANNOTATION_ENTRY }\n+ .lastChildLeafOrSelf()\n+ .nextCodeLeaf()\n+ ?.prevLeaf()\n+ ?.let { prevLeaf ->\n+ // Let the indentation rule determine the exact indentation and only report and fix when the line needs to be wrapped\n+ if (!prevLeaf.textContains('\\n')) {\n+ emit(prevLeaf.startOffset, \"Expected newline after last annotation\", true)\n+ if (autoCorrect) {\n+ prevLeaf.upsertWhitespaceAfterMe(expectedIndent)\n+ }\n+ }\n+ }\n+\n+ node\n+ .takeIf { it.elementType == ANNOTATED_EXPRESSION }\n+ ?.treeParent\n+ ?.takeIf { it.elementType == BLOCK }\n+ ?.nextSibling()\n+ ?.let { nextSibling ->\n+ // Let the indentation rule determine the exact indentation and only report and fix when the line needs to be wrapped\n+ if (!nextSibling.textContains('\\n')) {\n+ emit(nextSibling.startOffset, \"Expected newline\", true)\n+ if (autoCorrect) {\n+ nextSibling.upsertWhitespaceBeforeMe(node.indent())\n+ }\n+ }\n }\n+ }\n+ }\n+\n+ private fun ASTNode.shouldWrapAnnotations() =\n+ hasAnnotationWithParameter() ||\n+ hasMultipleAnnotationsOnSameLine() ||\n+ hasAnnotationBeforeConstructor()\n+\n+ private fun ASTNode.hasAnnotationWithParameter(): Boolean {\n+ require(elementType in ANNOTATION_CONTAINER)\n+ return children()\n+ .any {\n+ it.isAnnotationEntryWithValueArgumentList() &&\n+ it.treeParent.treeParent.elementType != VALUE_PARAMETER &&\n+ it.treeParent.treeParent.elementType != VALUE_ARGUMENT &&\n+ it.isNotReceiverTargetAnnotation()\n }\n+ }\n \n- if (node.treeParent.elementType != ANNOTATION &&\n- node.treeParent.treeParent.elementType != VALUE_PARAMETER &&\n- node.treeParent.treeParent.elementType != VALUE_ARGUMENT &&\n- node.isPrecededByOtherAnnotationEntryOnTheSameLine() &&\n- node.isLastAnnotationEntry()\n- ) {\n+ private fun ASTNode.hasMultipleAnnotationsOnSameLine(): Boolean {\n+ require(elementType in ANNOTATION_CONTAINER)\n+ return children()\n+ .any {\n+ it.treeParent.elementType != ANNOTATION &&\n+ it.treeParent.treeParent.elementType != VALUE_PARAMETER &&\n+ it.treeParent.treeParent.elementType != VALUE_ARGUMENT &&\n+ it.isPrecededByOtherAnnotationEntryOnTheSameLine() &&\n+ it.isLastAnnotationEntry()\n // Code below is disallowed\n // @Foo1 @Foo2 fun foo() {}\n // But following is allowed:\n // @[Foo1 Foo2] fun foo() {}\n // fun foo(@Bar1 @Bar2 bar) {}\n- emit(\n- node.findAnnotatedConstruct().startOffset,\n- \"Multiple annotations should not be placed on the same line as the annotated construct\",\n- true,\n- )\n- if (autoCorrect) {\n- node\n- .lastChildLeafOrSelf()\n- .nextCodeLeaf()\n- ?.upsertWhitespaceBeforeMe(\n- getNewlineWithIndent(node.treeParent)\n- .applyIf(node.typeProjectionOrNull() != null) {\n- plus(indentConfig.indent)\n- },\n- )\n- }\n }\n+ }\n \n- node.typeProjectionOrNull()\n- ?.prevCodeLeaf()\n- ?.let { startOfList ->\n- // Code below is disallowed\n- // var foo: List<@Foo1 @Foo2 String>\n- // But following is allowed:\n- // var foo: List<@[Foo1 Foo2] String>\n- // fun foo(@Bar1 @Bar2 bar) {}\n- if (node.isFollowedByOtherAnnotationEntryOnTheSameLine() &&\n- node.isFirstAnnotationEntry()\n- ) {\n- emit(startOfList.startOffset, \"Expected newline after '${startOfList.text}'\", true)\n- if (autoCorrect) {\n- startOfList\n- .upsertWhitespaceAfterMe(\n- getNewlineWithIndent(node.treeParent).plus(indentConfig.indent),\n- )\n+ private fun ASTNode.hasAnnotationBeforeConstructor() =\n+ codeStyle == CodeStyleValue.ktlint_official &&\n+ hasAnnotationEntry() &&\n+ nextCodeSibling()?.elementType == CONSTRUCTOR_KEYWORD\n+\n+ private fun ASTNode.hasAnnotationEntry() = children().any { it.elementType == ANNOTATION_ENTRY }\n+\n+ private fun visitTypeArgumentList(\n+ node: ASTNode,\n+ emit: (offset: Int, errorMessage: String, canBeAutoCorrected: Boolean) -> Unit,\n+ autoCorrect: Boolean,\n+ ) {\n+ node\n+ .children()\n+ .filter { it.elementType == TYPE_PROJECTION }\n+ .mapNotNull { it.findChildByType(TYPE_REFERENCE) }\n+ .filter { it.elementType == TYPE_REFERENCE }\n+ .mapNotNull { it.findChildByType(MODIFIER_LIST) }\n+ .filter { it.elementType == MODIFIER_LIST }\n+ .any { it.shouldWrapAnnotations() }\n+ .ifTrue { wrapTypeArgumentList(node, emit, autoCorrect) }\n+ }\n+\n+ private fun wrapTypeArgumentList(\n+ node: ASTNode,\n+ emit: (offset: Int, errorMessage: String, canBeAutoCorrected: Boolean) -> Unit,\n+ autoCorrect: Boolean,\n+ ) {\n+ val expectedIndent = node.indent().plus(indentConfig.indent)\n+\n+ node\n+ .children()\n+ .filter { it.elementType == TYPE_PROJECTION }\n+ .forEach { typeProjection ->\n+ typeProjection\n+ .prevLeaf()\n+ ?.let { prevLeaf ->\n+ if (prevLeaf.text != expectedIndent) {\n+ emit(prevLeaf.startOffset, \"Expected newline\", true)\n+ if (autoCorrect) {\n+ prevLeaf.upsertWhitespaceAfterMe(expectedIndent)\n+ }\n }\n }\n- if (node.isPrecededByOtherAnnotationEntryOnTheSameLine() &&\n- node.isLastAnnotationEntry()\n- ) {\n- node\n- .findAnnotatedConstruct()\n- .treeParent\n- .lastChildLeafOrSelf()\n- .nextLeaf { it.isCodeLeaf() && it.elementType != ElementType.COMMA }\n- ?.let { codeLeaf ->\n- emit(codeLeaf.startOffset, \"Expected newline before '${codeLeaf.text}'\", true)\n- if (autoCorrect) {\n- codeLeaf.upsertWhitespaceBeforeMe(getNewlineWithIndent(node.treeParent))\n- }\n- }\n+ }\n+\n+ node\n+ .findChildByType(GT)\n+ ?.let { gt ->\n+ if (gt.prevLeaf()?.text != expectedIndent) {\n+ emit(gt.startOffset, \"Expected newline\", true)\n+ if (autoCorrect) {\n+ gt.upsertWhitespaceBeforeMe(expectedIndent)\n }\n }\n- }\n+ }\n+ }\n \n+ private fun visitAnnotationEntry(\n+ node: ASTNode,\n+ emit: (offset: Int, errorMessage: String, canBeAutoCorrected: Boolean) -> Unit,\n+ autoCorrect: Boolean,\n+ ) {\n+ require(node.elementType == ANNOTATION_ENTRY)\n if (node.isPrecededByOtherAnnotationEntryOnTheSameLine() && node.isPrecededByAnnotationOnAnotherLine()) {\n // Code below is disallowed\n // @Foo1\n@@ -245,15 +319,6 @@ public class AnnotationRule :\n }\n }\n \n- private fun ASTNode.typeProjectionOrNull() =\n- takeIf { elementType == ANNOTATION_ENTRY }\n- ?.takeIf { it.treeParent.elementType == MODIFIER_LIST }\n- ?.treeParent\n- ?.takeIf { it.treeParent.elementType == TYPE_REFERENCE }\n- ?.treeParent\n- ?.takeIf { it.treeParent.elementType == TYPE_PROJECTION }\n- ?.treeParent\n-\n private fun ASTNode.isPrecededByAnnotationOnAnotherLine(): Boolean {\n val firstAnnotation = treeParent.findChildByType(ANNOTATION_ENTRY)\n return siblings(forward = false)\n@@ -261,52 +326,6 @@ public class AnnotationRule :\n .any { it.isWhiteSpaceWithNewline() }\n }\n \n- private fun checkForAnnotationWithParameterToBePlacedOnSeparateLine(\n- node: ASTNode,\n- emit: (offset: Int, errorMessage: String, canBeAutoCorrected: Boolean) -> Unit,\n- autoCorrect: Boolean,\n- ) {\n- if (node.isPrecededByOtherAnnotationEntry() && node.isOnSameLineAsPreviousAnnotationEntry()) {\n- emit(\n- node.startOffset,\n- \"Annotation with parameter(s) should be placed on a separate line prior to the annotated construct\",\n- true,\n- )\n- if (autoCorrect) {\n- node\n- .firstChildLeafOrSelf()\n- .upsertWhitespaceBeforeMe(\" \")\n- }\n- }\n-\n- if (node.isOnSameLineAsNextAnnotationEntryOrAnnotatedConstruct()) {\n- emit(\n- node.startOffset,\n- \"Annotation with parameter(s) should be placed on a separate line prior to the annotated construct\",\n- // Annotated expressions for which the annotation contains a parameter can be hard to correct\n- // automatically. See examples below. For now, let them be fixed manually.\n- // fun foo1() = @Suppress(\"DEPRECATION\") bar()\n- // if (@Suppress(\"DEPRECATION\") bar()) { .. }\n- node.treeParent.elementType != ANNOTATED_EXPRESSION,\n- )\n- if (autoCorrect) {\n- node\n- .lastChildLeafOrSelf()\n- .nextLeaf()\n- .safeAs()\n- ?.let {\n- if (it.elementType == WHITE_SPACE) {\n- it.replaceWithText(getNewlineWithIndent(node.treeParent))\n- } else {\n- it.rawInsertBeforeMe(\n- PsiWhiteSpaceImpl(getNewlineWithIndent(node.treeParent)),\n- )\n- }\n- }\n- }\n- }\n- }\n-\n private fun ASTNode.isNotReceiverTargetAnnotation() = getAnnotationUseSiteTarget() != AnnotationUseSiteTarget.RECEIVER\n \n private fun ASTNode.getAnnotationUseSiteTarget() =\n@@ -321,25 +340,19 @@ public class AnnotationRule :\n takeIf { it.elementType == ANNOTATION_ENTRY }\n ?.findChildByType(VALUE_ARGUMENT_LIST)\n \n- private fun ASTNode.isFirstAnnotationEntry() =\n- this ==\n- treeParent\n- .children()\n- .firstOrNull { it.elementType == ANNOTATION_ENTRY }\n-\n private fun ASTNode.isLastAnnotationEntry() =\n this ==\n treeParent\n .children()\n .lastOrNull { it.elementType == ANNOTATION_ENTRY }\n \n- private fun ASTNode.isPrecededByOtherAnnotationEntryOnTheSameLine() =\n+ private fun ASTNode.isPrecededByOtherAnnotationEntryWithoutParametersOnTheSameLine() =\n siblings(forward = false)\n- .takeWhile { !it.isWhiteSpaceWithNewline() }\n- .any { it.elementType == ANNOTATION_ENTRY }\n+ .takeWhile { !it.isWhiteSpaceWithNewline() && !it.isAnnotationEntryWithValueArgumentList() }\n+ .any { it.elementType == ANNOTATION_ENTRY && !it.isAnnotationEntryWithValueArgumentList() }\n \n- private fun ASTNode.isFollowedByOtherAnnotationEntryOnTheSameLine() =\n- siblings()\n+ private fun ASTNode.isPrecededByOtherAnnotationEntryOnTheSameLine() =\n+ siblings(forward = false)\n .takeWhile { !it.isWhiteSpaceWithNewline() }\n .any { it.elementType == ANNOTATION_ENTRY }\n \n@@ -359,33 +372,6 @@ public class AnnotationRule :\n .takeWhile { it.elementType != ANNOTATION_ENTRY }\n .none { it.isWhiteSpaceWithNewline() }\n \n- private fun ASTNode.isOnSameLineAsAnnotatedConstruct(): Boolean {\n- val annotatedConstruct = findAnnotatedConstruct()\n- return lastChildLeafOrSelf()\n- .leaves(forward = true)\n- .takeWhile { it != annotatedConstruct }\n- .none { it.isWhiteSpaceWithNewline() }\n- }\n-\n- private fun ASTNode.findAnnotatedConstruct(): ASTNode {\n- val astNode =\n- if (treeParent.elementType == MODIFIER_LIST) {\n- treeParent\n- } else {\n- this\n- }\n- return checkNotNull(\n- astNode.lastChildLeafOrSelf().nextCodeLeaf(),\n- )\n- }\n-\n- private fun ASTNode.isOnSameLineAsNextAnnotationEntryOrAnnotatedConstruct() =\n- if (isFollowedByOtherAnnotationEntry()) {\n- isOnSameLineAsNextAnnotationEntry()\n- } else {\n- isOnSameLineAsAnnotatedConstruct()\n- }\n-\n private fun visitFileAnnotationList(\n node: ASTNode,\n emit: (offset: Int, errorMessage: String, canBeAutoCorrected: Boolean) -> Unit,\n@@ -448,6 +434,15 @@ public class AnnotationRule :\n .substringAfterLast('\\n')\n return \"\\n\".plus(indentWithoutNewline)\n }\n+\n+ private companion object {\n+ val ANNOTATION_CONTAINER =\n+ listOf(\n+ ANNOTATED_EXPRESSION,\n+ FILE_ANNOTATION_LIST,\n+ MODIFIER_LIST,\n+ )\n+ }\n }\n \n public val ANNOTATION_RULE_ID: RuleId = AnnotationRule().ruleId\ndiff --git a/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/IndentationRule.kt b/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/IndentationRule.kt\nindex 50f8b7f213..b91c6b6bb2 100644\n--- a/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/IndentationRule.kt\n+++ b/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/IndentationRule.kt\n@@ -48,6 +48,7 @@ import com.pinterest.ktlint.rule.engine.core.api.ElementType.OBJECT_DECLARATION\n import com.pinterest.ktlint.rule.engine.core.api.ElementType.OPEN_QUOTE\n import com.pinterest.ktlint.rule.engine.core.api.ElementType.OPERATION_REFERENCE\n import com.pinterest.ktlint.rule.engine.core.api.ElementType.PARENTHESIZED\n+import com.pinterest.ktlint.rule.engine.core.api.ElementType.PRIMARY_CONSTRUCTOR\n import com.pinterest.ktlint.rule.engine.core.api.ElementType.PROPERTY\n import com.pinterest.ktlint.rule.engine.core.api.ElementType.PROPERTY_ACCESSOR\n import com.pinterest.ktlint.rule.engine.core.api.ElementType.RBRACE\n@@ -577,14 +578,24 @@ public class IndentationRule :\n toAstNode = typeConstraintList.lastChildLeafOrSelf(),\n ).prevCodeLeaf()\n }\n- node\n- .findChildByType(SUPER_TYPE_LIST)\n- ?.let { superTypeList ->\n- nextToAstNode = startIndentContext(\n- fromAstNode = superTypeList.getPrecedingLeadingCommentsAndWhitespaces(),\n- toAstNode = superTypeList.lastChildLeafOrSelf(),\n- ).prevCodeLeaf()\n- }\n+\n+ val primaryConstructor = node.findChildByType(PRIMARY_CONSTRUCTOR)\n+ if (codeStyle == ktlint_official && primaryConstructor != null) {\n+ // Indent both constructor and super type list\n+ nextToAstNode = startIndentContext(\n+ fromAstNode = primaryConstructor.getPrecedingLeadingCommentsAndWhitespaces(),\n+ toAstNode = nextToAstNode,\n+ ).prevCodeLeaf()\n+ } else {\n+ node\n+ .findChildByType(SUPER_TYPE_LIST)\n+ ?.let { superTypeList ->\n+ nextToAstNode = startIndentContext(\n+ fromAstNode = superTypeList.getPrecedingLeadingCommentsAndWhitespaces(),\n+ toAstNode = superTypeList.lastChildLeafOrSelf(),\n+ ).prevCodeLeaf()\n+ }\n+ }\n \n // Leading annotations and comments should be indented at same level as class itself\n startIndentContext(\ndiff --git a/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/TypeArgumentListSpacingRule.kt b/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/TypeArgumentListSpacingRule.kt\nindex 54ceba78e5..7cef327593 100644\n--- a/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/TypeArgumentListSpacingRule.kt\n+++ b/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/TypeArgumentListSpacingRule.kt\n@@ -1,23 +1,48 @@\n package com.pinterest.ktlint.ruleset.standard.rules\n \n import com.pinterest.ktlint.rule.engine.core.api.ElementType\n+import com.pinterest.ktlint.rule.engine.core.api.IndentConfig\n import com.pinterest.ktlint.rule.engine.core.api.Rule\n import com.pinterest.ktlint.rule.engine.core.api.RuleId\n+import com.pinterest.ktlint.rule.engine.core.api.editorconfig.EditorConfig\n+import com.pinterest.ktlint.rule.engine.core.api.editorconfig.INDENT_SIZE_PROPERTY\n+import com.pinterest.ktlint.rule.engine.core.api.editorconfig.INDENT_STYLE_PROPERTY\n import com.pinterest.ktlint.rule.engine.core.api.findCompositeParentElementOfType\n+import com.pinterest.ktlint.rule.engine.core.api.indent\n import com.pinterest.ktlint.rule.engine.core.api.isPartOfCompositeElementOfType\n+import com.pinterest.ktlint.rule.engine.core.api.isWhiteSpace\n import com.pinterest.ktlint.rule.engine.core.api.nextLeaf\n import com.pinterest.ktlint.rule.engine.core.api.nextSibling\n import com.pinterest.ktlint.rule.engine.core.api.prevLeaf\n import com.pinterest.ktlint.rule.engine.core.api.prevSibling\n+import com.pinterest.ktlint.rule.engine.core.api.upsertWhitespaceAfterMe\n+import com.pinterest.ktlint.rule.engine.core.api.upsertWhitespaceBeforeMe\n import com.pinterest.ktlint.ruleset.standard.StandardRule\n import org.jetbrains.kotlin.com.intellij.lang.ASTNode\n+import org.jetbrains.kotlin.utils.addToStdlib.applyIf\n \n /**\n * Lints and formats the spacing before and after the angle brackets of a type argument list.\n */\n public class TypeArgumentListSpacingRule :\n- StandardRule(\"type-argument-list-spacing\"),\n+ StandardRule(\n+ id = \"type-argument-list-spacing\",\n+ usesEditorConfigProperties =\n+ setOf(\n+ INDENT_SIZE_PROPERTY,\n+ INDENT_STYLE_PROPERTY,\n+ ),\n+ ),\n Rule.Experimental {\n+ private var indentConfig = IndentConfig.DEFAULT_INDENT_CONFIG\n+\n+ override fun beforeFirstNode(editorConfig: EditorConfig) {\n+ indentConfig = IndentConfig(\n+ indentStyle = editorConfig[INDENT_STYLE_PROPERTY],\n+ tabWidth = editorConfig[INDENT_SIZE_PROPERTY],\n+ )\n+ }\n+\n override fun beforeVisitChildNodes(\n node: ASTNode,\n autoCorrect: Boolean,\n@@ -70,21 +95,53 @@ public class TypeArgumentListSpacingRule :\n autoCorrect: Boolean,\n emit: (offset: Int, errorMessage: String, canBeAutoCorrected: Boolean) -> Unit,\n ) {\n- // No whitespace expected after opening angle bracket of type argument list\n- // val list = listOf< String>()\n+ val multiline = node.textContains('\\n')\n+ val expectedIndent =\n+ node\n+ .indent()\n+ .applyIf(multiline) {\n+ plus(indentConfig.indent)\n+ }\n+\n node\n .findChildByType(ElementType.LT)\n ?.nextSibling()\n- ?.takeIf { it.elementType == ElementType.WHITE_SPACE }\n- ?.let { noWhitespaceExpected(it, autoCorrect, emit) }\n+ ?.let { nextSibling ->\n+ if (multiline) {\n+ if (nextSibling.text != expectedIndent) {\n+ emit(nextSibling.startOffset, \"Expected newline\", true)\n+ if (autoCorrect) {\n+ nextSibling.upsertWhitespaceAfterMe(expectedIndent)\n+ }\n+ }\n+ } else {\n+ if (nextSibling.isWhiteSpace()) {\n+ // Disallow\n+ // val list = listOf< String>()\n+ noWhitespaceExpected(nextSibling, autoCorrect, emit)\n+ }\n+ }\n+ }\n \n- // No whitespace expected before closing angle bracket of type argument list\n- // val list = listOf()\n node\n .findChildByType(ElementType.GT)\n ?.prevSibling()\n- ?.takeIf { it.elementType == ElementType.WHITE_SPACE }\n- ?.let { noWhitespaceExpected(it, autoCorrect, emit) }\n+ ?.let { prevSibling ->\n+ if (multiline) {\n+ if (prevSibling.text != expectedIndent) {\n+ emit(prevSibling.startOffset, \"Expected newline\", true)\n+ if (autoCorrect) {\n+ prevSibling.upsertWhitespaceBeforeMe(expectedIndent)\n+ }\n+ }\n+ } else {\n+ if (prevSibling.isWhiteSpace()) {\n+ // Disallow\n+ // val list = listOf()\n+ noWhitespaceExpected(prevSibling, autoCorrect, emit)\n+ }\n+ }\n+ }\n }\n \n private fun noWhitespaceExpected(\n", "test_patch": "diff --git a/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/AnnotationRuleTest.kt b/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/AnnotationRuleTest.kt\nindex 57c1aa1ef4..c7d12357c7 100644\n--- a/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/AnnotationRuleTest.kt\n+++ b/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/AnnotationRuleTest.kt\n@@ -1,5 +1,7 @@\n package com.pinterest.ktlint.ruleset.standard.rules\n \n+import com.pinterest.ktlint.rule.engine.core.api.editorconfig.CODE_STYLE_PROPERTY\n+import com.pinterest.ktlint.rule.engine.core.api.editorconfig.CodeStyleValue.ktlint_official\n import com.pinterest.ktlint.test.KtLintAssertThat.Companion.assertThatRule\n import com.pinterest.ktlint.test.LintViolation\n import org.junit.jupiter.api.Nested\n@@ -39,11 +41,11 @@ class AnnotationRuleTest {\n fun `Given an annotation with a parameter followed by a EOL comment`() {\n val code =\n \"\"\"\n- @Suppress(\"AnnotationRule\") // some comment\n+ @Suppress(\"Something\") // some comment\n class FooBar {\n- @Suppress(\"AnnotationRule\") // some comment\n+ @Suppress(\"Something\") // some comment\n var foo: String\n- @Suppress(\"AnnotationRule\") // some comment\n+ @Suppress(\"Something\") // some comment\n fun bar() {}\n }\n \"\"\".trimIndent()\n@@ -54,54 +56,54 @@ class AnnotationRuleTest {\n fun `Given an annotation with a parameter on same line as annotation construct (possibly separated by a block comment or KDoc)`() {\n val code =\n \"\"\"\n- @Suppress(\"AnnotationRule\") class FooBar1 {\n- @Suppress(\"AnnotationRule\") var foo: String\n- @Suppress(\"AnnotationRule\") fun bar() {}\n+ @Suppress(\"Something\") class FooBar1 {\n+ @Suppress(\"Something\") var foo: String\n+ @Suppress(\"Something\") fun bar() {}\n }\n- @Suppress(\"AnnotationRule\") /* some comment */ class FooBar2 {\n- @Suppress(\"AnnotationRule\") /* some comment */ var foo: String\n- @Suppress(\"AnnotationRule\") /* some comment */ fun bar() {}\n+ @Suppress(\"Something\") /* some comment */ class FooBar2 {\n+ @Suppress(\"Something\") /* some comment */ var foo: String\n+ @Suppress(\"Something\") /* some comment */ fun bar() {}\n }\n- @Suppress(\"AnnotationRule\") /** some comment */ class FooBar3 {\n- @Suppress(\"AnnotationRule\") /** some comment */ var foo: String\n- @Suppress(\"AnnotationRule\") /** some comment */ fun bar() {}\n+ @Suppress(\"Something\") /** some comment */ class FooBar3 {\n+ @Suppress(\"Something\") /** some comment */ var foo: String\n+ @Suppress(\"Something\") /** some comment */ fun bar() {}\n }\n \"\"\".trimIndent()\n val formattedCode =\n \"\"\"\n- @Suppress(\"AnnotationRule\")\n+ @Suppress(\"Something\")\n class FooBar1 {\n- @Suppress(\"AnnotationRule\")\n+ @Suppress(\"Something\")\n var foo: String\n- @Suppress(\"AnnotationRule\")\n+ @Suppress(\"Something\")\n fun bar() {}\n }\n- @Suppress(\"AnnotationRule\")\n- /* some comment */ class FooBar2 {\n- @Suppress(\"AnnotationRule\")\n- /* some comment */ var foo: String\n- @Suppress(\"AnnotationRule\")\n- /* some comment */ fun bar() {}\n+ @Suppress(\"Something\") /* some comment */\n+ class FooBar2 {\n+ @Suppress(\"Something\") /* some comment */\n+ var foo: String\n+ @Suppress(\"Something\") /* some comment */\n+ fun bar() {}\n }\n- @Suppress(\"AnnotationRule\")\n- /** some comment */ class FooBar3 {\n- @Suppress(\"AnnotationRule\")\n- /** some comment */ var foo: String\n- @Suppress(\"AnnotationRule\")\n- /** some comment */ fun bar() {}\n+ @Suppress(\"Something\") /** some comment */\n+ class FooBar3 {\n+ @Suppress(\"Something\") /** some comment */\n+ var foo: String\n+ @Suppress(\"Something\") /** some comment */\n+ fun bar() {}\n }\n \"\"\".trimIndent()\n annotationRuleAssertThat(code)\n .hasLintViolations(\n- LintViolation(1, 1, \"Annotation with parameter(s) should be placed on a separate line prior to the annotated construct\"),\n- LintViolation(2, 5, \"Annotation with parameter(s) should be placed on a separate line prior to the annotated construct\"),\n- LintViolation(3, 5, \"Annotation with parameter(s) should be placed on a separate line prior to the annotated construct\"),\n- LintViolation(5, 1, \"Annotation with parameter(s) should be placed on a separate line prior to the annotated construct\"),\n- LintViolation(6, 5, \"Annotation with parameter(s) should be placed on a separate line prior to the annotated construct\"),\n- LintViolation(7, 5, \"Annotation with parameter(s) should be placed on a separate line prior to the annotated construct\"),\n- LintViolation(9, 1, \"Annotation with parameter(s) should be placed on a separate line prior to the annotated construct\"),\n- LintViolation(10, 5, \"Annotation with parameter(s) should be placed on a separate line prior to the annotated construct\"),\n- LintViolation(11, 5, \"Annotation with parameter(s) should be placed on a separate line prior to the annotated construct\"),\n+ LintViolation(1, 23, \"Expected newline after last annotation\"),\n+ LintViolation(2, 27, \"Expected newline after last annotation\"),\n+ LintViolation(3, 27, \"Expected newline after last annotation\"),\n+ LintViolation(5, 42, \"Expected newline after last annotation\"),\n+ LintViolation(6, 46, \"Expected newline after last annotation\"),\n+ LintViolation(7, 46, \"Expected newline after last annotation\"),\n+ LintViolation(9, 43, \"Expected newline after last annotation\"),\n+ LintViolation(10, 47, \"Expected newline after last annotation\"),\n+ LintViolation(11, 47, \"Expected newline after last annotation\"),\n ).isFormattedAs(formattedCode)\n }\n \n@@ -126,9 +128,9 @@ class AnnotationRuleTest {\n \"\"\".trimIndent()\n annotationRuleAssertThat(code)\n .hasLintViolations(\n- LintViolation(1, 11, \"Multiple annotations should not be placed on the same line as the annotated construct\"),\n- LintViolation(2, 15, \"Multiple annotations should not be placed on the same line as the annotated construct\"),\n- LintViolation(3, 15, \"Multiple annotations should not be placed on the same line as the annotated construct\"),\n+ LintViolation(1, 10, \"Expected newline after last annotation\"),\n+ LintViolation(2, 14, \"Expected newline after last annotation\"),\n+ LintViolation(3, 14, \"Expected newline after last annotation\"),\n ).isFormattedAs(formattedCode)\n }\n \n@@ -157,7 +159,7 @@ class AnnotationRuleTest {\n var foo: String\n \"\"\".trimIndent()\n annotationRuleAssertThat(code)\n- .hasLintViolation(1, 21, \"Multiple annotations should not be placed on the same line as the annotated construct\")\n+ .hasLintViolation(1, 20, \"Expected newline after last annotation\")\n .isFormattedAs(formattedCode)\n }\n \n@@ -173,7 +175,7 @@ class AnnotationRuleTest {\n var foo: String\n \"\"\".trimIndent()\n annotationRuleAssertThat(code)\n- .hasLintViolation(1, 21, \"Multiple annotations should not be placed on the same line as the annotated construct\")\n+ .hasLintViolation(1, 20, \"Expected newline after last annotation\")\n .isFormattedAs(formattedCode)\n }\n \n@@ -181,26 +183,26 @@ class AnnotationRuleTest {\n fun `Given an annotation with a parameter not followed by a space but on same line as annotated construct`() {\n val code =\n \"\"\"\n- @Suppress(\"AnnotationRule\")class FooBar {\n- @Suppress(\"AnnotationRule\")var foo: String\n- @Suppress(\"AnnotationRule\")fun bar() {}\n+ @Suppress(\"Something\")class FooBar {\n+ @Suppress(\"Something\")var foo: String\n+ @Suppress(\"Something\")fun bar() {}\n }\n \"\"\".trimIndent()\n val formattedCode =\n \"\"\"\n- @Suppress(\"AnnotationRule\")\n+ @Suppress(\"Something\")\n class FooBar {\n- @Suppress(\"AnnotationRule\")\n+ @Suppress(\"Something\")\n var foo: String\n- @Suppress(\"AnnotationRule\")\n+ @Suppress(\"Something\")\n fun bar() {}\n }\n \"\"\".trimIndent()\n annotationRuleAssertThat(code)\n .hasLintViolations(\n- LintViolation(1, 1, \"Annotation with parameter(s) should be placed on a separate line prior to the annotated construct\"),\n- LintViolation(2, 5, \"Annotation with parameter(s) should be placed on a separate line prior to the annotated construct\"),\n- LintViolation(3, 5, \"Annotation with parameter(s) should be placed on a separate line prior to the annotated construct\"),\n+ LintViolation(1, 22, \"Expected newline after last annotation\"),\n+ LintViolation(2, 26, \"Expected newline after last annotation\"),\n+ LintViolation(3, 26, \"Expected newline after last annotation\"),\n ).isFormattedAs(formattedCode)\n }\n \n@@ -230,7 +232,7 @@ class AnnotationRuleTest {\n }\n \"\"\".trimIndent()\n annotationRuleAssertThat(code)\n- .hasLintViolation(2, 5, \"Annotation with parameter(s) should be placed on a separate line prior to the annotated construct\")\n+ .hasLintViolation(7, 6, \"Expected newline after last annotation\")\n .isFormattedAs(formattedCode)\n }\n \n@@ -253,7 +255,7 @@ class AnnotationRuleTest {\n \"\"\".trimIndent()\n @Suppress(\"ktlint:argument-list-wrapping\", \"ktlint:max-line-length\")\n annotationRuleAssertThat(code)\n- .hasLintViolation(3, 5, \"Annotation must be placed on a separate line when it is preceded by another annotation on a separate line\")\n+ .hasLintViolation(3, 9, \"Expected newline after last annotation\")\n .isFormattedAs(formattedCode)\n }\n \n@@ -287,15 +289,6 @@ class AnnotationRuleTest {\n annotationRuleAssertThat(code).hasNoLintViolations()\n }\n \n- @Test\n- fun `Issue 628 - Given an annotation before the primary constructor `() {\n- val code =\n- \"\"\"\n- class Foo @Inject internal constructor()\n- \"\"\".trimIndent()\n- annotationRuleAssertThat(code).hasNoLintViolations()\n- }\n-\n @Test\n fun `Issue 642 - Given annotations on method parameters on same line as parameter`() {\n val code =\n@@ -390,6 +383,17 @@ class AnnotationRuleTest {\n .isFormattedAs(formattedCode)\n }\n \n+ @Test\n+ fun `Given a file annotation with parameter followed by a blank line`() {\n+ val code =\n+ \"\"\"\n+ @file:JvmName(\"FooClass\")\n+\n+ package foo.bar\n+ \"\"\".trimIndent()\n+ annotationRuleAssertThat(code).hasNoLintViolations()\n+ }\n+\n @Test\n fun `Issue 624 - Given a file annotation with parameter on same line as package`() {\n val code =\n@@ -405,7 +409,7 @@ class AnnotationRuleTest {\n @Suppress(\"ktlint:argument-list-wrapping\", \"ktlint:max-line-length\")\n annotationRuleAssertThat(code)\n .hasLintViolations(\n- LintViolation(1, 1, \"Annotation with parameter(s) should be placed on a separate line prior to the annotated construct\"),\n+ LintViolation(1, 26, \"Expected newline after last annotation\"),\n LintViolation(1, 27, \"File annotations should be separated from file contents with a blank line\"),\n ).isFormattedAs(formattedCode)\n }\n@@ -501,7 +505,7 @@ class AnnotationRuleTest {\n fun `Issue 1539 - Given an annotation with parameter followed by an EOL comment and followed by another annotation`() {\n val code =\n \"\"\"\n- @Suppress(\"AnnotationRule\") // some comment\n+ @Suppress(\"Something\") // some comment\n @Bar\n class Foo\n \"\"\".trimIndent()\n@@ -512,7 +516,7 @@ class AnnotationRuleTest {\n fun `Issue 1539 - Given an annotation with parameter followed by an EOL comment on separate line before annotated construct`() {\n val code =\n \"\"\"\n- @Suppress(\"AnnotationRule\")\n+ @Suppress(\"Something\")\n // some comment between last annotation and annotated construct\n class Foo\n \"\"\".trimIndent()\n@@ -552,17 +556,45 @@ class AnnotationRuleTest {\n }\n \n @Test\n- fun `Given an annotated expression on same line as annotated construct and the annotation contains a parameter then report a violation which can not be autocorrected`() {\n+ fun `Given an annotated expression on same line as annotated construct and the annotation contains a parameter`() {\n val code =\n \"\"\"\n- fun foo() = @Suppress(\"DEPRECATION\") bar()\n+ fun foo() = @Bar1 @Bar2 @Bar3(\"bar3\") @Bar4 bar()\n+ \"\"\".trimIndent()\n+ val formattedCode =\n+ \"\"\"\n+ fun foo() =\n+ @Bar1 @Bar2\n+ @Bar3(\"bar3\")\n+ @Bar4\n+ bar()\n \"\"\".trimIndent()\n annotationRuleAssertThat(code)\n- .hasLintViolationWithoutAutoCorrect(\n- 1,\n- 13,\n- \"Annotation with parameter(s) should be placed on a separate line prior to the annotated construct\",\n- )\n+ .hasLintViolations(\n+ LintViolation(1, 12, \"Expected newline before annotation\"),\n+ LintViolation(1, 24, \"Expected newline before annotation\"),\n+ LintViolation(1, 38, \"Expected newline before annotation\"),\n+ LintViolation(1, 44, \"Expected newline after last annotation\"),\n+ ).isFormattedAs(formattedCode)\n+ }\n+\n+ @Test\n+ fun `Given an annotated expression on same line as annotated construct and no annotation contains a parameter`() {\n+ val code =\n+ \"\"\"\n+ fun foo() = @Bar1 @Bar2 bar()\n+ \"\"\".trimIndent()\n+ val formattedCode =\n+ \"\"\"\n+ fun foo() =\n+ @Bar1 @Bar2\n+ bar()\n+ \"\"\".trimIndent()\n+ annotationRuleAssertThat(code)\n+ .hasLintViolations(\n+ LintViolation(1, 12, \"Expected newline before annotation\"),\n+ LintViolation(1, 24, \"Expected newline after last annotation\"),\n+ ).isFormattedAs(formattedCode)\n }\n \n @Test\n@@ -617,6 +649,27 @@ class AnnotationRuleTest {\n }\n }\n \n+ @Test\n+ fun `Given an annotation and other modifiers before the annotated construct`() {\n+ val code =\n+ \"\"\"\n+ @Bar(\"bar\") public class Foo\n+ @Bar(\"bar\") public fun foo() {}\n+ \"\"\".trimIndent()\n+ val formattedCode =\n+ \"\"\"\n+ @Bar(\"bar\")\n+ public class Foo\n+ @Bar(\"bar\")\n+ public fun foo() {}\n+ \"\"\".trimIndent()\n+ annotationRuleAssertThat(code)\n+ .hasLintViolations(\n+ LintViolation(1, 12, \"Expected newline after last annotation\"),\n+ LintViolation(2, 12, \"Expected newline after last annotation\"),\n+ ).isFormattedAs(formattedCode)\n+ }\n+\n @Test\n fun `Given a single annotation on same line as a type parameter then do not report a violation`() {\n val code =\n@@ -632,6 +685,17 @@ class AnnotationRuleTest {\n .hasNoLintViolations()\n }\n \n+ @Test\n+ fun `Given an annotation with parameter on followed by another modifier on the next line then do not report a violation`() {\n+ val code =\n+ \"\"\"\n+ @Target(AnnotationTarget.TYPE)\n+ annotation class Foo\n+ \"\"\".trimIndent()\n+ annotationRuleAssertThat(code)\n+ .hasNoLintViolations()\n+ }\n+\n @Nested\n inner class `Issue 1725 - Given multiple annotations on same line as a type parameter` {\n @Test\n@@ -645,15 +709,16 @@ class AnnotationRuleTest {\n val fooBar: List<\n @Foo @Bar\n String\n- > = emptyList()\n+ > = emptyList()\n \"\"\".trimIndent()\n annotationRuleAssertThat(code)\n .addAdditionalRuleProvider { TrailingCommaOnDeclarationSiteRule() }\n .addAdditionalRuleProvider { WrappingRule() }\n .hasLintViolations(\n- LintViolation(1, 17, \"Expected newline after '<'\"),\n- LintViolation(1, 28, \"Multiple annotations should not be placed on the same line as the annotated construct\"),\n- LintViolation(1, 34, \"Expected newline before '>'\"),\n+ LintViolation(1, 17, \"Expected newline\"),\n+ LintViolation(1, 17, \"Expected newline before annotation\"),\n+ LintViolation(1, 27, \"Expected newline after last annotation\"),\n+ LintViolation(1, 34, \"Expected newline\"),\n ).isFormattedAs(formattedCode)\n }\n \n@@ -680,13 +745,16 @@ class AnnotationRuleTest {\n .addAdditionalRuleProvider { IndentationRule() }\n .addAdditionalRuleProvider { WrappingRule() }\n .hasLintViolations(\n- LintViolation(1, 39, \"Expected newline after ','\"),\n- LintViolation(1, 51, \"Multiple annotations should not be placed on the same line as the annotated construct\"),\n- LintViolation(1, 57, \"Expected newline after ','\"),\n- LintViolation(1, 59, \"Expected newline before '@'\"),\n- LintViolation(1, 59, \"Annotation with parameter(s) should be placed on a separate line prior to the annotated construct\"),\n- LintViolation(1, 76, \"Multiple annotations should not be placed on the same line as the annotated construct\"),\n- LintViolation(1, 82, \"Expected newline before '>'\"),\n+ LintViolation(1, 19, \"Expected newline\"),\n+ LintViolation(1, 27, \"Expected newline\"),\n+ LintViolation(1, 40, \"Expected newline\"),\n+ LintViolation(1, 40, \"Expected newline before annotation\"),\n+ LintViolation(1, 50, \"Expected newline after last annotation\"),\n+ LintViolation(1, 58, \"Expected newline\"),\n+ LintViolation(1, 58, \"Expected newline before annotation\"),\n+ LintViolation(1, 70, \"Expected newline before annotation\"),\n+ LintViolation(1, 75, \"Expected newline after last annotation\"),\n+ LintViolation(1, 82, \"Expected newline\"),\n ).isFormattedAs(formattedCode)\n }\n }\n@@ -729,9 +797,164 @@ class AnnotationRuleTest {\n \"\"\".trimIndent()\n annotationRuleAssertThat(code)\n .hasLintViolations(\n- LintViolation(4, 17, \"Multiple annotations should not be placed on the same line as the annotated construct\"),\n- LintViolation(5, 5, \"Annotation with parameter(s) should be placed on a separate line prior to the annotated construct\"),\n- LintViolation(5, 25, \"Multiple annotations should not be placed on the same line as the annotated construct\"),\n+ LintViolation(4, 16, \"Expected newline after last annotation\"),\n+ LintViolation(5, 18, \"Expected newline before annotation\"),\n+ LintViolation(5, 24, \"Expected newline after last annotation\"),\n+ ).isFormattedAs(formattedCode)\n+ }\n+\n+ @Nested\n+ inner class `Given a class with a primary constructor` {\n+ @Test\n+ fun `Issue 628 - Given an annotation followed by other modifier before the primary constructor (non ktlint_official code style)`() {\n+ val code =\n+ \"\"\"\n+ class Foo @Inject internal constructor()\n+ \"\"\".trimIndent()\n+ annotationRuleAssertThat(code).hasNoLintViolations()\n+ }\n+\n+ @Nested\n+ inner class `Given ktlint_official code style` {\n+ @Test\n+ fun `Issue 628 - Given an annotation followed by other modifier before the primary constructor (ktlint_official code style)`() {\n+ val code =\n+ \"\"\"\n+ class Foo @Inject internal constructor()\n+ \"\"\".trimIndent()\n+ val formattedCode =\n+ \"\"\"\n+ class Foo\n+ @Inject\n+ internal constructor()\n+ \"\"\".trimIndent()\n+ annotationRuleAssertThat(code)\n+ .withEditorConfigOverride(CODE_STYLE_PROPERTY to ktlint_official)\n+ .hasLintViolations(\n+ LintViolation(1, 10, \"Expected newline before annotation\"),\n+ LintViolation(1, 18, \"Expected newline after last annotation\"),\n+ ).isFormattedAs(formattedCode)\n+ }\n+\n+ @Test\n+ fun `Given an annotation with parameter`() {\n+ val code =\n+ \"\"\"\n+ data class Foo @Bar1 @Bar2(\"bar\") @Bar3 @Bar4 constructor(private val foobar: Int) {\n+ fun foo(): String = \"foo\"\n+ }\n+ \"\"\".trimIndent()\n+ val formattedCode =\n+ \"\"\"\n+ data class Foo\n+ @Bar1\n+ @Bar2(\"bar\")\n+ @Bar3\n+ @Bar4\n+ constructor(private val foobar: Int) {\n+ fun foo(): String = \"foo\"\n+ }\n+ \"\"\".trimIndent()\n+ annotationRuleAssertThat(code)\n+ .addAdditionalRuleProvider { IndentationRule() }\n+ .withEditorConfigOverride(CODE_STYLE_PROPERTY to ktlint_official)\n+ .hasLintViolations(\n+ LintViolation(1, 15, \"Expected newline before annotation\"),\n+ LintViolation(1, 21, \"Expected newline before annotation\"),\n+ LintViolation(1, 34, \"Expected newline before annotation\"),\n+ LintViolation(1, 46, \"Expected newline after last annotation\"),\n+ ).isFormattedAs(formattedCode)\n+ }\n+\n+ @Test\n+ fun `Given annotations without parameters`() {\n+ val code =\n+ \"\"\"\n+ data class Foo @Bar1 @Bar2 constructor(private val foobar: Int) {\n+ fun foo(): String = \"foo\"\n+ }\n+ \"\"\".trimIndent()\n+ val formattedCode =\n+ \"\"\"\n+ data class Foo\n+ @Bar1 @Bar2\n+ constructor(private val foobar: Int) {\n+ fun foo(): String = \"foo\"\n+ }\n+ \"\"\".trimIndent()\n+ annotationRuleAssertThat(code)\n+ .withEditorConfigOverride(CODE_STYLE_PROPERTY to ktlint_official)\n+ .hasLintViolations(\n+ LintViolation(1, 15, \"Expected newline before annotation\"),\n+ LintViolation(1, 27, \"Expected newline after last annotation\"),\n+ ).isFormattedAs(formattedCode)\n+ }\n+\n+ @Test\n+ fun `Given single annotation without parameter`() {\n+ val code =\n+ \"\"\"\n+ data class Foo @Bar1 constructor(private val foobar: Int) {\n+ fun foo(): String = \"foo\"\n+ }\n+ \"\"\".trimIndent()\n+ val formattedCode =\n+ \"\"\"\n+ data class Foo\n+ @Bar1\n+ constructor(private val foobar: Int) {\n+ fun foo(): String = \"foo\"\n+ }\n+ \"\"\".trimIndent()\n+ annotationRuleAssertThat(code)\n+ .withEditorConfigOverride(CODE_STYLE_PROPERTY to ktlint_official)\n+ .hasLintViolations(\n+ LintViolation(1, 15, \"Expected newline before annotation\"),\n+ LintViolation(1, 21, \"Expected newline after last annotation\"),\n+ ).isFormattedAs(formattedCode)\n+ }\n+ }\n+ }\n+\n+ @Test\n+ fun `Given an annotation with parameter preceded by a blank line then do not remove the blank line`() {\n+ val code =\n+ \"\"\"\n+ val foo = \"foo\"\n+\n+ @Bar(\"bar\")\n+ fun bar() = \"bar\"\n+ \"\"\".trimIndent()\n+ annotationRuleAssertThat(code).hasNoLintViolations()\n+ }\n+\n+ @Test\n+ fun `Given a function literal containing an annotated expression`() {\n+ val code =\n+ \"\"\"\n+ val foo = {\n+ @Bar(\"bar\")\n+ foobar { \"foobar\" }\n+ }\n+ val foo = { @Bar(\"bar\") foobar { \"foobar\" } }\n+ \"\"\".trimIndent()\n+ val formattedCode =\n+ \"\"\"\n+ val foo = {\n+ @Bar(\"bar\")\n+ foobar { \"foobar\" }\n+ }\n+ val foo = {\n+ @Bar(\"bar\")\n+ foobar { \"foobar\" }\n+ }\n+ \"\"\".trimIndent()\n+ annotationRuleAssertThat(code)\n+ .addAdditionalRuleProvider { IndentationRule() }\n+ .hasLintViolations(\n+ LintViolation(5, 12, \"Expected newline before annotation\"),\n+ LintViolation(5, 24, \"Expected newline after last annotation\"),\n+ LintViolation(5, 44, \"Expected newline\"),\n ).isFormattedAs(formattedCode)\n }\n }\ndiff --git a/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/IndentationRuleTest.kt b/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/IndentationRuleTest.kt\nindex 01dbefdfd5..a234d30270 100644\n--- a/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/IndentationRuleTest.kt\n+++ b/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/IndentationRuleTest.kt\n@@ -4959,6 +4959,89 @@ internal class IndentationRuleTest {\n indentationRuleAssertThat(code).hasNoLintViolations()\n }\n \n+ @Test\n+ fun `Issue 1916 - Given a class declaration with an annotation before the constructor`() {\n+ val code =\n+ \"\"\"\n+ class Foo\n+ @Bar1 @Bar2\n+ constructor(\n+ foo1: Foo1,\n+ foo2: Foo2,\n+ ) {\n+ fun foo() = \"foo\"\n+ }\n+ \"\"\".trimIndent()\n+ val formattedCode =\n+ \"\"\"\n+ class Foo\n+ @Bar1 @Bar2\n+ constructor(\n+ foo1: Foo1,\n+ foo2: Foo2,\n+ ) {\n+ fun foo() = \"foo\"\n+ }\n+ \"\"\".trimIndent()\n+ indentationRuleAssertThat(code)\n+ .withEditorConfigOverride(CODE_STYLE_PROPERTY to ktlint_official)\n+ .hasLintViolations(\n+ LintViolation(2, 1, \"Unexpected indentation (0) (should be 4)\"),\n+ LintViolation(3, 1, \"Unexpected indentation (0) (should be 4)\"),\n+ LintViolation(4, 1, \"Unexpected indentation (4) (should be 8)\"),\n+ LintViolation(5, 1, \"Unexpected indentation (4) (should be 8)\"),\n+ LintViolation(6, 1, \"Unexpected indentation (0) (should be 4)\"),\n+ LintViolation(7, 1, \"Unexpected indentation (4) (should be 8)\"),\n+ LintViolation(8, 1, \"Unexpected indentation (0) (should be 4)\"),\n+ ).isFormattedAs(formattedCode)\n+ }\n+\n+ @Test\n+ fun `Issue 1916 - Given a class declaration with an annotation before the constructor nad having a super type list`() {\n+ val code =\n+ \"\"\"\n+ class Foo\n+ @Bar1 @Bar2\n+ constructor(\n+ foo1: Foo1,\n+ foo2: Foo2,\n+ ) : Foobar(\n+ \"foobar1\",\n+ \"foobar2\",\n+ ) {\n+ fun foo() = \"foo\"\n+ }\n+ \"\"\".trimIndent()\n+ val formattedCode =\n+ \"\"\"\n+ class Foo\n+ @Bar1 @Bar2\n+ constructor(\n+ foo1: Foo1,\n+ foo2: Foo2,\n+ ) : Foobar(\n+ \"foobar1\",\n+ \"foobar2\",\n+ ) {\n+ fun foo() = \"foo\"\n+ }\n+ \"\"\".trimIndent()\n+ indentationRuleAssertThat(code)\n+ .withEditorConfigOverride(CODE_STYLE_PROPERTY to ktlint_official)\n+ .hasLintViolations(\n+ LintViolation(2, 1, \"Unexpected indentation (0) (should be 4)\"),\n+ LintViolation(3, 1, \"Unexpected indentation (0) (should be 4)\"),\n+ LintViolation(4, 1, \"Unexpected indentation (4) (should be 8)\"),\n+ LintViolation(5, 1, \"Unexpected indentation (4) (should be 8)\"),\n+ LintViolation(6, 1, \"Unexpected indentation (0) (should be 4)\"),\n+ LintViolation(7, 1, \"Unexpected indentation (4) (should be 8)\"),\n+ LintViolation(8, 1, \"Unexpected indentation (4) (should be 8)\"),\n+ LintViolation(9, 1, \"Unexpected indentation (0) (should be 4)\"),\n+ LintViolation(10, 1, \"Unexpected indentation (4) (should be 8)\"),\n+ LintViolation(11, 1, \"Unexpected indentation (0) (should be 4)\"),\n+ ).isFormattedAs(formattedCode)\n+ }\n+\n private companion object {\n val INDENT_STYLE_TAB =\n INDENT_STYLE_PROPERTY to PropertyType.IndentStyleValue.tab\ndiff --git a/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/TypeArgumentListSpacingRuleTest.kt b/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/TypeArgumentListSpacingRuleTest.kt\nindex a821781666..842b162961 100644\n--- a/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/TypeArgumentListSpacingRuleTest.kt\n+++ b/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/TypeArgumentListSpacingRuleTest.kt\n@@ -68,4 +68,18 @@ class TypeArgumentListSpacingRuleTest {\n \"\"\".trimIndent()\n typeArgumentListSpacingRuleAssertThat(code).hasNoLintViolations()\n }\n+\n+ @Test\n+ fun `Given an multiline type argument list then do not report a violation`() {\n+ val code =\n+ \"\"\"\n+ class Foo {\n+ val list1: List<\n+ @Serializable(MultiplyingIntSerializer::class)\n+ Int,\n+ >\n+ }\n+ \"\"\".trimIndent()\n+ typeArgumentListSpacingRuleAssertThat(code).hasNoLintViolations()\n+ }\n }\ndiff --git a/ktlint-ruleset-test-tooling/src/main/kotlin/com/pinterest/ruleset/testtooling/DumpASTRule.kt b/ktlint-ruleset-test-tooling/src/main/kotlin/com/pinterest/ruleset/testtooling/DumpASTRule.kt\nindex 9cd48b6cf1..b44fafc86a 100644\n--- a/ktlint-ruleset-test-tooling/src/main/kotlin/com/pinterest/ruleset/testtooling/DumpASTRule.kt\n+++ b/ktlint-ruleset-test-tooling/src/main/kotlin/com/pinterest/ruleset/testtooling/DumpASTRule.kt\n@@ -13,119 +13,121 @@ import org.jetbrains.kotlin.lexer.KtTokens\n import java.io.PrintStream\n import java.util.Locale\n \n-public class DumpASTRule @JvmOverloads constructor(\n- private val out: PrintStream = System.err,\n- private val color: Boolean = false,\n-) : Rule(\n- ruleId = RuleId(\"$TEST_TOOLING_RULESET_ID:dump-ast\"),\n- about =\n- About(\n- maintainer = \"Ktlint\",\n- repositoryUrl = \"https://github.com/pinterest/ktlint\",\n- issueTrackerUrl = \"https://github.com/pinterest/ktlint/issues\",\n- ),\n-) {\n- private companion object {\n- val ELEMENT_TYPE_SET = ElementType::class.members.map { it.name }.toSet()\n- }\n-\n- private var lineNumberColumnLength: Int = 0\n- private var lastNode: ASTNode? = null\n-\n- override fun beforeVisitChildNodes(\n- node: ASTNode,\n- autoCorrect: Boolean,\n- emit: (offset: Int, errorMessage: String, corrected: Boolean) -> Unit,\n+public class DumpASTRule\n+ @JvmOverloads\n+ constructor(\n+ private val out: PrintStream = System.err,\n+ private val color: Boolean = false,\n+ ) : Rule(\n+ ruleId = RuleId(\"$TEST_TOOLING_RULESET_ID:dump-ast\"),\n+ about =\n+ About(\n+ maintainer = \"Ktlint\",\n+ repositoryUrl = \"https://github.com/pinterest/ktlint\",\n+ issueTrackerUrl = \"https://github.com/pinterest/ktlint/issues\",\n+ ),\n ) {\n- if (node.isRoot()) {\n- lineNumberColumnLength = node\n- .lastChildLeafOrSelf()\n- .lineNumberOrUnknown()\n- .length\n- lastNode = node.lastChildLeafOrSelf()\n+ private companion object {\n+ val ELEMENT_TYPE_SET = ElementType::class.members.map { it.name }.toSet()\n }\n- var level = -1\n- var parent: ASTNode? = node\n- do {\n- level++\n- parent = parent?.treeParent\n- } while (parent != null)\n \n- out.println(\n- (\n- node\n+ private var lineNumberColumnLength: Int = 0\n+ private var lastNode: ASTNode? = null\n+\n+ override fun beforeVisitChildNodes(\n+ node: ASTNode,\n+ autoCorrect: Boolean,\n+ emit: (offset: Int, errorMessage: String, corrected: Boolean) -> Unit,\n+ ) {\n+ if (node.isRoot()) {\n+ lineNumberColumnLength = node\n+ .lastChildLeafOrSelf()\n .lineNumberOrUnknown()\n- .let { String.format(\"%${lineNumberColumnLength}s: \", it).dim() }\n- ) +\n- \" \".repeat(level).dim() +\n- colorClassName(node.psi.className) +\n- \" (\".dim() + colorClassName(elementTypeClassName(node.elementType)) + \")\".dim() +\n- if (node.getChildren(null).isEmpty()) \" \\\"\" + node.text.escape().brighten() + \"\\\"\" else \"\",\n- )\n- if (lastNode == node) {\n- out.println()\n+ .length\n+ lastNode = node.lastChildLeafOrSelf()\n+ }\n+ var level = -1\n+ var parent: ASTNode? = node\n+ do {\n+ level++\n+ parent = parent?.treeParent\n+ } while (parent != null)\n+\n out.println(\n- \" \".repeat(lineNumberColumnLength) +\n- \" format: () \\\"\\\"\".dim(),\n+ (\n+ node\n+ .lineNumberOrUnknown()\n+ .let { String.format(\"%${lineNumberColumnLength}s: \", it).dim() }\n+ ) +\n+ \" \".repeat(level).dim() +\n+ colorClassName(node.psi.className) +\n+ \" (\".dim() + colorClassName(elementTypeClassName(node.elementType)) + \")\".dim() +\n+ if (node.getChildren(null).isEmpty()) \" \\\"\" + node.text.escape().brighten() + \"\\\"\" else \"\",\n )\n- if (node.lineNumberOrUnknown() == \"Unknown\") {\n+ if (lastNode == node) {\n+ out.println()\n out.println(\n \" \".repeat(lineNumberColumnLength) +\n- \" line_number 'Unknown' is caused by mutations in the AST during formatting\".dim(),\n+ \" format: () \\\"\\\"\".dim(),\n )\n+ if (node.lineNumberOrUnknown() == \"Unknown\") {\n+ out.println(\n+ \" \".repeat(lineNumberColumnLength) +\n+ \" line_number 'Unknown' is caused by mutations in the AST during formatting\".dim(),\n+ )\n+ }\n+ out.println(\n+ \" \".repeat(lineNumberColumnLength) +\n+ \" legend: ~ = org.jetbrains.kotlin, c.i.p = com.intellij.psi\".dim(),\n+ )\n+ out.println()\n }\n- out.println(\n- \" \".repeat(lineNumberColumnLength) +\n- \" legend: ~ = org.jetbrains.kotlin, c.i.p = com.intellij.psi\".dim(),\n- )\n- out.println()\n }\n- }\n-\n- private fun ASTNode.lineNumberOrUnknown(): String {\n- val lineNumber =\n- try {\n- psi\n- .containingFile\n- ?.viewProvider\n- ?.document\n- ?.getLineNumber(this.startOffset)\n- ?.let { it + 1 }\n- ?.toString()\n- } catch (e: IndexOutOfBoundsException) {\n- // Due to autocorrect mutations in the AST it can happen that the node's offset becomes invalid. As a result\n- // the line number can not be determined.\n- null\n- }\n- return lineNumber ?: \"Unknown\"\n- }\n \n- private fun elementTypeClassName(elementType: IElementType): String {\n- var name = elementType.toString().substringAfterLast(\".\").uppercase(Locale.getDefault())\n- if (name == \"FLOAT_CONSTANT\" && elementType == KtTokens.FLOAT_LITERAL) {\n- // resolve KtNodeTypes.FLOAT_CONSTANT vs KtTokens.FLOAT_LITERAL(FLOAT_CONSTANT) conflict\n- name = \"FLOAT_LITERAL\"\n+ private fun ASTNode.lineNumberOrUnknown(): String {\n+ val lineNumber =\n+ try {\n+ psi\n+ .containingFile\n+ ?.viewProvider\n+ ?.document\n+ ?.getLineNumber(this.startOffset)\n+ ?.let { it + 1 }\n+ ?.toString()\n+ } catch (e: IndexOutOfBoundsException) {\n+ // Due to autocorrect mutations in the AST it can happen that the node's offset becomes invalid. As a result\n+ // the line number can not be determined.\n+ null\n+ }\n+ return lineNumber ?: \"Unknown\"\n }\n- if (KtTokens.KEYWORDS.contains(elementType) || KtTokens.SOFT_KEYWORDS.contains(elementType)) {\n- name = \"${name}_KEYWORD\"\n+\n+ private fun elementTypeClassName(elementType: IElementType): String {\n+ var name = elementType.toString().substringAfterLast(\".\").uppercase(Locale.getDefault())\n+ if (name == \"FLOAT_CONSTANT\" && elementType == KtTokens.FLOAT_LITERAL) {\n+ // resolve KtNodeTypes.FLOAT_CONSTANT vs KtTokens.FLOAT_LITERAL(FLOAT_CONSTANT) conflict\n+ name = \"FLOAT_LITERAL\"\n+ }\n+ if (KtTokens.KEYWORDS.contains(elementType) || KtTokens.SOFT_KEYWORDS.contains(elementType)) {\n+ name = \"${name}_KEYWORD\"\n+ }\n+ return if (ELEMENT_TYPE_SET.contains(name)) name else elementType.className + \".\" + elementType\n }\n- return if (ELEMENT_TYPE_SET.contains(name)) name else elementType.className + \".\" + elementType\n- }\n \n- private fun colorClassName(className: String): String {\n- val name = className.substringAfterLast(\".\")\n- return className.substring(0, className.length - name.length).dim() + name\n- }\n+ private fun colorClassName(className: String): String {\n+ val name = className.substringAfterLast(\".\")\n+ return className.substring(0, className.length - name.length).dim() + name\n+ }\n \n- private fun String.brighten() = optColor(Color.YELLOW)\n- private fun String.dim() = optColor(Color.DARK_GRAY)\n- private fun String.optColor(foreground: Color) = if (color) this.color(foreground) else this\n+ private fun String.brighten() = optColor(Color.YELLOW)\n+ private fun String.dim() = optColor(Color.DARK_GRAY)\n+ private fun String.optColor(foreground: Color) = if (color) this.color(foreground) else this\n \n- private val Any.className\n- get() =\n- this.javaClass.name\n- .replace(\"org.jetbrains.kotlin.\", \"~.\")\n- .replace(\"com.intellij.psi.\", \"c.i.p.\")\n+ private val Any.className\n+ get() =\n+ this.javaClass.name\n+ .replace(\"org.jetbrains.kotlin.\", \"~.\")\n+ .replace(\"com.intellij.psi.\", \"c.i.p.\")\n \n- private fun String.escape() = this.replace(\"\\\\\", \"\\\\\\\\\").replace(\"\\n\", \"\\\\n\").replace(\"\\t\", \"\\\\t\").replace(\"\\r\", \"\\\\r\")\n-}\n+ private fun String.escape() = this.replace(\"\\\\\", \"\\\\\\\\\").replace(\"\\n\", \"\\\\n\").replace(\"\\t\", \"\\\\t\").replace(\"\\r\", \"\\\\r\")\n+ }\n", "problem_statement": "Wrap annotations before class constructor (ktlint_official)\nAnnotations before the class constructor should be wrapped in same way as other annotations when code style `ktlint_official` is used.\r\n\r\nExample:\r\n```\r\ndata class Foo @Bar1 @Bar2(\"bar\") @Bar3 @Bar4 constructor(private val foobar: Int) {\r\n fun foo(): String = \"foo\"\r\n}\r\n```\r\nshould be formatted as\r\n```\r\ndata class Foo\r\n @Bar1\r\n @Bar2(\"bar\")\r\n @Bar3\r\n @Bar4\r\n constructor(private val foobar: Int) {\r\n fun foo(): String = \"foo\"\r\n}\r\n```\nAnnotations on type projections should be wrapped in same way as other annotations\nGiven a type argument list in which one or more of the type projects are annotation than the same wrapping rules should be applies as with other annotations.\r\n\r\nExampe:\r\n```\r\nval fooBar: FooBar = FooBar()\r\n```\r\nshould be formatted as:\r\n```\r\nval fooBar: FooBar<\r\n String,\r\n @Foo String,\r\n @Foo @Bar\r\n String,\r\n @Bar(\"bar\")\r\n @Foo\r\n String\r\n > = FooBar()\r\n```\r\n\r\nIn case the type argument list only contains type projections without or with a single annotation without parameter than the annotation does not need to be wrapped. So code below will not be changed:\r\n```\r\nval foo1: List<@Foo String> = emptyList()\r\nval foo2 = emptyList<@Foo String>()\r\nval foo3: Map<@Foo String, @Foo String> = emptyMap()\r\nval foo4 = emptyMap<@Foo String, @Foo String>()\r\n```\r\n\n", "hints_text": "\n", "created_at": "2023-04-06T18:13:06Z", "version": "0.49", "FAIL_TO_PASS": [ "gradle_test_execution" ], "PASS_TO_PASS": [], "ERROR_TO_PASS": [], "environment_setup_commit": "410d8849874f4d3600f9d4572e0850adccce4f2d" }, { "repo": "pinterest/ktlint", "pull_number": 2144, "instance_id": "pinterest__ktlint-2144", "issue_numbers": [ "2143" ], "base_commit": "2c163c6829dafd0f31b6a91b6f11515521116938", "patch": "diff --git a/CHANGELOG.md b/CHANGELOG.md\nindex 6c63ef32a6..08ff2bd460 100644\n--- a/CHANGELOG.md\n+++ b/CHANGELOG.md\n@@ -25,6 +25,7 @@ This project adheres to [Semantic Versioning](https://semver.org/).\n \n ### Changed\n \n+* Change default code style to `ktlint_official` ([#2143](https://github.com/pinterest/ktlint/pull/2143))\n * Update dependency gradle to v8.2.1 ([#2122](https://github.com/pinterest/ktlint/pull/2122))\n * Update dependency org.codehaus.janino:janino to v3.1.10 ([#2110](https://github.com/pinterest/ktlint/pull/2110))\n * Update dependency com.google.jimfs:jimfs to v1.3.0 ([#2112](https://github.com/pinterest/ktlint/pull/2112))\ndiff --git a/ktlint-rule-engine-core/src/main/kotlin/com/pinterest/ktlint/rule/engine/core/api/editorconfig/CodeStyleEditorConfigProperty.kt b/ktlint-rule-engine-core/src/main/kotlin/com/pinterest/ktlint/rule/engine/core/api/editorconfig/CodeStyleEditorConfigProperty.kt\nindex ba882b1752..131b2d2fa6 100644\n--- a/ktlint-rule-engine-core/src/main/kotlin/com/pinterest/ktlint/rule/engine/core/api/editorconfig/CodeStyleEditorConfigProperty.kt\n+++ b/ktlint-rule-engine-core/src/main/kotlin/com/pinterest/ktlint/rule/engine/core/api/editorconfig/CodeStyleEditorConfigProperty.kt\n@@ -37,9 +37,8 @@ public enum class CodeStyleValue {\n public val CODE_STYLE_PROPERTY_TYPE: PropertyType.LowerCasingPropertyType =\n PropertyType.LowerCasingPropertyType(\n \"ktlint_code_style\",\n- \"The code style ('intellij_idea', 'android_studio' or 'ktlint_official') to be applied. Currently, the \" +\n- \"value is defaulted to 'intellij_idea' when not set. However, in the future the default code style \" +\n- \"will be changed to 'ktlint_official'.\",\n+ \"The code style ('ktlint_official', 'intellij_idea' or 'android_studio') to be applied. By default the 'ktlint_official' code \" +\n+ \"style is used\",\n SafeEnumValueParser(CodeStyleValue::class.java),\n CodeStyleValue.values().map { it.name }.toSet(),\n )\n@@ -47,11 +46,7 @@ public val CODE_STYLE_PROPERTY_TYPE: PropertyType.LowerCasingPropertyType =\n EditorConfigProperty(\n type = CODE_STYLE_PROPERTY_TYPE,\n- /*\n- * Once the [CodeStyleValue.ktlint_official] is matured, it will become the default code style of ktlint. Until\n- * then the [CodeStyleValue.intellij_idea] is used to remain backwards compatible.\n- */\n- defaultValue = CodeStyleValue.intellij_idea,\n+ defaultValue = CodeStyleValue.ktlint_official,\n androidStudioCodeStyleDefaultValue = CodeStyleValue.android_studio,\n intellijIdeaCodeStyleDefaultValue = CodeStyleValue.intellij_idea,\n ktlintOfficialCodeStyleDefaultValue = CodeStyleValue.ktlint_official,\ndiff --git a/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/ClassSignatureRule.kt b/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/ClassSignatureRule.kt\nindex f820ef6d4a..f5ccac71a2 100644\n--- a/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/ClassSignatureRule.kt\n+++ b/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/ClassSignatureRule.kt\n@@ -151,7 +151,7 @@ public class ClassSignatureRule :\n require(node.elementType == CLASS)\n \n val wrapPrimaryConstructorParameters =\n- node.hasMinimumNumberOfParameters() ||\n+ node.hasTooManyParameters() ||\n node.containsMultilineParameter() ||\n (codeStyle == ktlint_official && node.containsAnnotatedParameter()) ||\n (isMaxLineLengthSet() && classSignatureExcludingSuperTypesExceedsMaxLineLength(node, emit, autoCorrect)) ||\n@@ -648,7 +648,7 @@ public class ClassSignatureRule :\n \n private fun List.joinTextToString(): String = collectLeavesRecursively().joinToString(separator = \"\") { it.text }\n \n- private fun ASTNode.hasMinimumNumberOfParameters(): Boolean = countParameters() >= classSignatureWrappingMinimumParameters\n+ private fun ASTNode.hasTooManyParameters(): Boolean = countParameters() >= classSignatureWrappingMinimumParameters\n \n private fun ASTNode.countParameters() =\n getPrimaryConstructorParameterListOrNull()\n", "test_patch": "diff --git a/ktlint-rule-engine-core/src/test/kotlin/com/pinterest/ktlint/rule/engine/core/api/editorconfig/EditorConfigTest.kt b/ktlint-rule-engine-core/src/test/kotlin/com/pinterest/ktlint/rule/engine/core/api/editorconfig/EditorConfigTest.kt\nindex 9f344e36e2..2fea1866db 100644\n--- a/ktlint-rule-engine-core/src/test/kotlin/com/pinterest/ktlint/rule/engine/core/api/editorconfig/EditorConfigTest.kt\n+++ b/ktlint-rule-engine-core/src/test/kotlin/com/pinterest/ktlint/rule/engine/core/api/editorconfig/EditorConfigTest.kt\n@@ -36,8 +36,7 @@ class EditorConfigTest {\n \n val actual = editorConfig[SOME_EDITOR_CONFIG_PROPERTY]\n \n- // Note that IntelliJ IDEA is the default code style for now, this will change to KTLINT_OFFICIAL in the future\n- assertThat(actual).isEqualTo(SOME_PROPERTY_VALUE_INTELLIJ_IDEA)\n+ assertThat(actual).isEqualTo(SOME_PROPERTY_VALUE_KTLINT_OFFICIAL)\n }\n \n @ParameterizedTest(name = \"Code style: {0}, expected result: {1}\")\n@@ -45,7 +44,7 @@ class EditorConfigTest {\n value = [\n \"android_studio, $SOME_PROPERTY_VALUE_ANDROID_STUDIO\",\n \"intellij_idea, $SOME_PROPERTY_VALUE_INTELLIJ_IDEA\",\n- \"ktlint_official, $SOME_PROPERTY_VALUE_OFFICIAL\",\n+ \"ktlint_official, $SOME_PROPERTY_VALUE_KTLINT_OFFICIAL\",\n ],\n )\n fun `Given an EditorConfig with a defined code style and add a property with default value then the default value can be retrieved for the default code style`(\n@@ -119,8 +118,8 @@ class EditorConfigTest {\n val editorConfig =\n EditorConfig()\n .addPropertiesWithDefaultValueIfMissing(\n- SOME_EDITOR_CONFIG_PROPERTY.copy(name = propertyName1, intellijIdeaCodeStyleDefaultValue = propertyValue1),\n- SOME_EDITOR_CONFIG_PROPERTY.copy(name = propertyName2, intellijIdeaCodeStyleDefaultValue = propertyValue2),\n+ SOME_EDITOR_CONFIG_PROPERTY.copy(name = propertyName1, ktlintOfficialCodeStyleDefaultValue = propertyValue1),\n+ SOME_EDITOR_CONFIG_PROPERTY.copy(name = propertyName2, ktlintOfficialCodeStyleDefaultValue = propertyValue2),\n )\n \n val actual = editorConfig.map { property -> property.name.uppercase() to property.sourceValue.uppercase() }\n@@ -198,7 +197,7 @@ class EditorConfigTest {\n val editorConfigPropertyWithPropertyMapper =\n SOME_EDITOR_CONFIG_PROPERTY\n .copy(\n- propertyMapper = { _, _ -> SOME_PROPERTY_VALUE_OFFICIAL },\n+ propertyMapper = { _, _ -> SOME_PROPERTY_VALUE_KTLINT_OFFICIAL },\n defaultValue = SOME_PROPERTY_VALUE,\n androidStudioCodeStyleDefaultValue = null,\n intellijIdeaCodeStyleDefaultValue = null,\n@@ -208,7 +207,7 @@ class EditorConfigTest {\n \n val actual = editorConfig[editorConfigPropertyWithPropertyMapper]\n \n- assertThat(actual).isEqualTo(SOME_PROPERTY_VALUE_OFFICIAL)\n+ assertThat(actual).isEqualTo(SOME_PROPERTY_VALUE_KTLINT_OFFICIAL)\n }\n \n @Test\n@@ -220,7 +219,7 @@ class EditorConfigTest {\n \n val actual = editorConfig[SOME_EDITOR_CONFIG_PROPERTY]\n \n- assertThat(actual).isEqualTo(SOME_PROPERTY_VALUE_INTELLIJ_IDEA)\n+ assertThat(actual).isEqualTo(SOME_PROPERTY_VALUE_KTLINT_OFFICIAL)\n }\n \n @Test\n@@ -324,7 +323,7 @@ class EditorConfigTest {\n const val SOME_PROPERTY_VALUE_ANDROID_STUDIO = \"some-property-value-android\"\n const val SOME_PROPERTY_VALUE_DEFAULT = \"some-property-value-default\"\n const val SOME_PROPERTY_VALUE_INTELLIJ_IDEA = \"some-property-value-intellij-idea\"\n- const val SOME_PROPERTY_VALUE_OFFICIAL = \"some-property-value-official\"\n+ const val SOME_PROPERTY_VALUE_KTLINT_OFFICIAL = \"some-property-value-ktlint-official\"\n val SOME_EDITOR_CONFIG_PROPERTY =\n EditorConfigProperty(\n name = SOME_PROPERTY_NAME,\n@@ -337,7 +336,7 @@ class EditorConfigTest {\n ),\n defaultValue = SOME_PROPERTY_VALUE_DEFAULT,\n androidStudioCodeStyleDefaultValue = SOME_PROPERTY_VALUE_ANDROID_STUDIO,\n- ktlintOfficialCodeStyleDefaultValue = SOME_PROPERTY_VALUE_OFFICIAL,\n+ ktlintOfficialCodeStyleDefaultValue = SOME_PROPERTY_VALUE_KTLINT_OFFICIAL,\n intellijIdeaCodeStyleDefaultValue = SOME_PROPERTY_VALUE_INTELLIJ_IDEA,\n )\n }\ndiff --git a/ktlint-rule-engine/src/test/kotlin/com/pinterest/ktlint/rule/engine/internal/EditorConfigLoaderTest.kt b/ktlint-rule-engine/src/test/kotlin/com/pinterest/ktlint/rule/engine/internal/EditorConfigLoaderTest.kt\nindex bee085c69d..2968c27679 100644\n--- a/ktlint-rule-engine/src/test/kotlin/com/pinterest/ktlint/rule/engine/internal/EditorConfigLoaderTest.kt\n+++ b/ktlint-rule-engine/src/test/kotlin/com/pinterest/ktlint/rule/engine/internal/EditorConfigLoaderTest.kt\n@@ -229,7 +229,7 @@ internal class EditorConfigLoaderTest {\n \"ij_formatter_tags_enabled = false\",\n \"ij_formatter_off_tag = @formatter:off\",\n \"ij_formatter_on_tag = @formatter:on\",\n- \"ktlint_code_style = intellij_idea\",\n+ \"ktlint_code_style = ktlint_official\",\n \"ktlint_experimental = disabled\",\n )\n }\n@@ -306,7 +306,7 @@ internal class EditorConfigLoaderTest {\n \"ij_formatter_tags_enabled = false\",\n \"ij_formatter_off_tag = @formatter:off\",\n \"ij_formatter_on_tag = @formatter:on\",\n- \"ktlint_code_style = intellij_idea\",\n+ \"ktlint_code_style = ktlint_official\",\n \"ktlint_experimental = disabled\",\n )\n }\n@@ -357,7 +357,7 @@ internal class EditorConfigLoaderTest {\n \"ij_formatter_tags_enabled = false\",\n \"ij_formatter_off_tag = @formatter:off\",\n \"ij_formatter_on_tag = @formatter:on\",\n- \"ktlint_code_style = intellij_idea\",\n+ \"ktlint_code_style = ktlint_official\",\n \"ktlint_experimental = disabled\",\n )\n }\ndiff --git a/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/AnnotationRuleTest.kt b/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/AnnotationRuleTest.kt\nindex d1dd929b5b..6a679198c0 100644\n--- a/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/AnnotationRuleTest.kt\n+++ b/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/AnnotationRuleTest.kt\n@@ -1,6 +1,7 @@\n package com.pinterest.ktlint.ruleset.standard.rules\n \n import com.pinterest.ktlint.rule.engine.core.api.editorconfig.CODE_STYLE_PROPERTY\n+import com.pinterest.ktlint.rule.engine.core.api.editorconfig.CodeStyleValue\n import com.pinterest.ktlint.rule.engine.core.api.editorconfig.CodeStyleValue.ktlint_official\n import com.pinterest.ktlint.test.KtLintAssertThat.Companion.assertThatRule\n import com.pinterest.ktlint.test.LintViolation\n@@ -806,12 +807,14 @@ class AnnotationRuleTest {\n @Nested\n inner class `Given a class with a primary constructor` {\n @Test\n- fun `Issue 628 - Given an annotation followed by other modifier before the primary constructor (non ktlint_official code style)`() {\n+ fun `Issue 628 - Given a non-ktlint_official code style and an annotation followed by other modifier before the primary constructor (non ktlint_official code style)`() {\n val code =\n \"\"\"\n class Foo @Inject internal constructor()\n \"\"\".trimIndent()\n- annotationRuleAssertThat(code).hasNoLintViolations()\n+ annotationRuleAssertThat(code)\n+ .withEditorConfigOverride(CODE_STYLE_PROPERTY to CodeStyleValue.intellij_idea)\n+ .hasNoLintViolations()\n }\n \n @Nested\ndiff --git a/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/ClassSignatureRuleTest.kt b/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/ClassSignatureRuleTest.kt\nindex 5e6df062af..cc054f425d 100644\n--- a/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/ClassSignatureRuleTest.kt\n+++ b/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/ClassSignatureRuleTest.kt\n@@ -41,6 +41,7 @@ class ClassSignatureRuleTest {\n \"\"\".trimIndent()\n classSignatureWrappingRuleAssertThat(code)\n .setMaxLineLength()\n+ .withEditorConfigOverride(FORCE_MULTILINE_WHEN_PARAMETER_COUNT_GREATER_OR_EQUAL_THAN_PROPERTY to \"unset\")\n .hasNoLintViolations()\n }\n \n@@ -81,6 +82,7 @@ class ClassSignatureRuleTest {\n classSignatureWrappingRuleAssertThat(code)\n .setMaxLineLength()\n .addAdditionalRuleProvider { FunctionStartOfBodySpacingRule() }\n+ .withEditorConfigOverride(FORCE_MULTILINE_WHEN_PARAMETER_COUNT_GREATER_OR_EQUAL_THAN_PROPERTY to \"unset\")\n .hasLintViolation(2, 34, \"Expected a single space before class body\")\n .isFormattedAs(formattedCode)\n }\n@@ -357,6 +359,7 @@ class ClassSignatureRuleTest {\n \"\"\".trimIndent()\n classSignatureWrappingRuleAssertThat(code)\n .setMaxLineLength()\n+ .withEditorConfigOverride(FORCE_MULTILINE_WHEN_PARAMETER_COUNT_GREATER_OR_EQUAL_THAN_PROPERTY to \"unset\")\n .hasLintViolations(\n LintViolation(3, 5, \"No whitespace expected between opening parenthesis and first parameter name\"),\n LintViolation(4, 5, \"Single whitespace expected before parameter\"),\n@@ -485,6 +488,7 @@ class ClassSignatureRuleTest {\n \"\"\".trimIndent()\n classSignatureWrappingRuleAssertThat(code)\n .setMaxLineLength()\n+ .withEditorConfigOverride(FORCE_MULTILINE_WHEN_PARAMETER_COUNT_GREATER_OR_EQUAL_THAN_PROPERTY to \"unset\")\n .hasNoLintViolations()\n }\n \n@@ -515,6 +519,7 @@ class ClassSignatureRuleTest {\n \"\"\".trimIndent()\n classSignatureWrappingRuleAssertThat(code)\n .addAdditionalRuleProvider { NullableTypeSpacingRule() }\n+ .withEditorConfigOverride(FORCE_MULTILINE_WHEN_PARAMETER_COUNT_GREATER_OR_EQUAL_THAN_PROPERTY to \"unset\")\n .hasNoLintViolationsExceptInAdditionalRules()\n .isFormattedAs(formattedCode)\n }\n@@ -583,7 +588,8 @@ class ClassSignatureRuleTest {\n { SpacingAroundParensRule() },\n { SpacingAroundCommaRule() },\n { SpacingAroundColonRule() },\n- ).hasLintViolations(\n+ ).withEditorConfigOverride(FORCE_MULTILINE_WHEN_PARAMETER_COUNT_GREATER_OR_EQUAL_THAN_PROPERTY to \"unset\")\n+ .hasLintViolations(\n LintViolation(3, 14, \"No whitespace expected between opening parenthesis and first parameter name\"),\n LintViolation(7, 21, \"Single whitespace expected before parameter\"),\n LintViolation(8, 26, \"No whitespace expected between last parameter and closing parenthesis\"),\n@@ -625,7 +631,8 @@ class ClassSignatureRuleTest {\n { SpacingAroundColonRule() },\n { SpacingAroundCommaRule() },\n { SpacingAroundOperatorsRule() },\n- ).hasLintViolations(\n+ ).withEditorConfigOverride(FORCE_MULTILINE_WHEN_PARAMETER_COUNT_GREATER_OR_EQUAL_THAN_PROPERTY to \"unset\")\n+ .hasLintViolations(\n LintViolation(2, 19, \"Single whitespace expected before parameter\"),\n LintViolation(4, 13, \"Expected single space before the super type\"),\n ).isFormattedAs(formattedCode)\n@@ -725,6 +732,7 @@ class ClassSignatureRuleTest {\n \"\"\".trimIndent()\n classSignatureWrappingRuleAssertThat(code)\n .setMaxLineLength()\n+ .withEditorConfigOverride(FORCE_MULTILINE_WHEN_PARAMETER_COUNT_GREATER_OR_EQUAL_THAN_PROPERTY to \"unset\")\n .hasNoLintViolations()\n }\n \n@@ -743,6 +751,7 @@ class ClassSignatureRuleTest {\n \"\"\".trimIndent()\n classSignatureWrappingRuleAssertThat(code)\n .setMaxLineLength()\n+ .withEditorConfigOverride(FORCE_MULTILINE_WHEN_PARAMETER_COUNT_GREATER_OR_EQUAL_THAN_PROPERTY to \"unset\")\n .hasLintViolation(2, 37, \"Super type should start on a newline\")\n .isFormattedAs(formattedCode)\n }\n@@ -1324,6 +1333,7 @@ class ClassSignatureRuleTest {\n \"\"\".trimIndent()\n classSignatureWrappingRuleAssertThat(code)\n .setMaxLineLength()\n+ .withEditorConfigOverride(FORCE_MULTILINE_WHEN_PARAMETER_COUNT_GREATER_OR_EQUAL_THAN_PROPERTY to \"unset\")\n .hasLintViolations(\n LintViolation(3, 5, \"No whitespace expected between opening parenthesis and first parameter name\"),\n LintViolation(4, 5, \"Single whitespace expected before parameter\"),\n@@ -1355,6 +1365,7 @@ class ClassSignatureRuleTest {\n \"\"\".trimIndent()\n classSignatureWrappingRuleAssertThat(code)\n .setMaxLineLength()\n+ .withEditorConfigOverride(FORCE_MULTILINE_WHEN_PARAMETER_COUNT_GREATER_OR_EQUAL_THAN_PROPERTY to \"unset\")\n .hasLintViolations(\n LintViolation(2, 37, \"Super type should start on a newline\"),\n LintViolation(2, 49, \"Super type should start on a newline\"),\n@@ -1383,6 +1394,7 @@ class ClassSignatureRuleTest {\n \"\"\".trimIndent()\n classSignatureWrappingRuleAssertThat(code)\n .setMaxLineLength()\n+ .withEditorConfigOverride(FORCE_MULTILINE_WHEN_PARAMETER_COUNT_GREATER_OR_EQUAL_THAN_PROPERTY to \"unset\")\n .hasLintViolations(\n LintViolation(2, 37, \"Super type should start on a newline\"),\n LintViolation(2, 43, \"Super type call must be first super type\"),\n@@ -1412,6 +1424,7 @@ class ClassSignatureRuleTest {\n \"\"\".trimIndent()\n classSignatureWrappingRuleAssertThat(code)\n .setMaxLineLength()\n+ .withEditorConfigOverride(FORCE_MULTILINE_WHEN_PARAMETER_COUNT_GREATER_OR_EQUAL_THAN_PROPERTY to \"unset\")\n .hasLintViolations(\n LintViolation(2, 37, \"Super type should start on a newline\"),\n LintViolation(2, 43, \"Super type should start on a newline\"),\n@@ -1440,6 +1453,7 @@ class ClassSignatureRuleTest {\n \"\"\".trimIndent()\n classSignatureWrappingRuleAssertThat(code)\n .setMaxLineLength()\n+ .withEditorConfigOverride(FORCE_MULTILINE_WHEN_PARAMETER_COUNT_GREATER_OR_EQUAL_THAN_PROPERTY to \"unset\")\n .hasLintViolation(2, 23, \"Super type should start on a newline\")\n .isFormattedAs(formattedCode)\n }\n@@ -1470,6 +1484,7 @@ class ClassSignatureRuleTest {\n classSignatureWrappingRuleAssertThat(code)\n .setMaxLineLength()\n .addAdditionalRuleProvider { IndentationRule() }\n+ .withEditorConfigOverride(FORCE_MULTILINE_WHEN_PARAMETER_COUNT_GREATER_OR_EQUAL_THAN_PROPERTY to \"unset\")\n .hasLintViolation(2, 37, \"Super type should start on a newline\")\n .isFormattedAs(formattedCode)\n }\n@@ -1494,9 +1509,9 @@ class ClassSignatureRuleTest {\n b: Any,\n c: Any\n ) : Bar(\n- a,\n- c\n- ) {\n+ a,\n+ c\n+ ) {\n // body\n }\n \"\"\".trimIndent()\ndiff --git a/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/FunctionSignatureRuleTest.kt b/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/FunctionSignatureRuleTest.kt\nindex b965d01431..d238c8fe3d 100644\n--- a/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/FunctionSignatureRuleTest.kt\n+++ b/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/FunctionSignatureRuleTest.kt\n@@ -35,6 +35,7 @@ class FunctionSignatureRuleTest {\n \"\"\".trimIndent()\n functionSignatureWrappingRuleAssertThat(code)\n .setMaxLineLength()\n+ .withEditorConfigOverride(FORCE_MULTILINE_WHEN_PARAMETER_COUNT_GREATER_OR_EQUAL_THAN_PROPERTY to \"unset\")\n .hasNoLintViolations()\n }\n \n@@ -96,6 +97,7 @@ class FunctionSignatureRuleTest {\n \"\"\".trimIndent()\n functionSignatureWrappingRuleAssertThat(code)\n .setMaxLineLength()\n+ .withEditorConfigOverride(FORCE_MULTILINE_WHEN_PARAMETER_COUNT_GREATER_OR_EQUAL_THAN_PROPERTY to \"unset\")\n .hasLintViolations(\n LintViolation(2, 7, \"Newline expected after opening parenthesis\"),\n LintViolation(2, 15, \"Parameter should start on a newline\"),\n@@ -263,6 +265,7 @@ class FunctionSignatureRuleTest {\n \"\"\".trimIndent()\n functionSignatureWrappingRuleAssertThat(code)\n .setMaxLineLength()\n+ .withEditorConfigOverride(FORCE_MULTILINE_WHEN_PARAMETER_COUNT_GREATER_OR_EQUAL_THAN_PROPERTY to \"unset\")\n .hasLintViolation(2, 32, \"Newline expected before expression body\")\n .isFormattedAs(formattedCode)\n }\n@@ -282,6 +285,7 @@ class FunctionSignatureRuleTest {\n \"\"\".trimIndent()\n functionSignatureWrappingRuleAssertThat(code)\n .setMaxLineLength()\n+ .withEditorConfigOverride(FORCE_MULTILINE_WHEN_PARAMETER_COUNT_GREATER_OR_EQUAL_THAN_PROPERTY to \"unset\")\n .hasLintViolation(2, 32, \"First line of body expression fits on same line as function signature\")\n .isFormattedAs(formattedCode)\n }\n@@ -379,6 +383,7 @@ class FunctionSignatureRuleTest {\n \"\"\".trimIndent()\n functionSignatureWrappingRuleAssertThat(code)\n .setMaxLineLength()\n+ .withEditorConfigOverride(FORCE_MULTILINE_WHEN_PARAMETER_COUNT_GREATER_OR_EQUAL_THAN_PROPERTY to \"unset\")\n .hasLintViolations(\n LintViolation(5, 5, \"No whitespace expected between opening parenthesis and first parameter name\"),\n LintViolation(6, 5, \"Single whitespace expected before parameter\"),\n@@ -415,6 +420,7 @@ class FunctionSignatureRuleTest {\n \"\"\".trimIndent()\n functionSignatureWrappingRuleAssertThat(code)\n .setMaxLineLength()\n+ .withEditorConfigOverride(FORCE_MULTILINE_WHEN_PARAMETER_COUNT_GREATER_OR_EQUAL_THAN_PROPERTY to \"unset\")\n .hasLintViolations(\n LintViolation(6, 9, \"No whitespace expected between opening parenthesis and first parameter name\"),\n LintViolation(7, 9, \"Single whitespace expected before parameter\"),\n@@ -497,6 +503,7 @@ class FunctionSignatureRuleTest {\n \"\"\".trimIndent()\n functionSignatureWrappingRuleAssertThat(code)\n .setMaxLineLength()\n+ .withEditorConfigOverride(FORCE_MULTILINE_WHEN_PARAMETER_COUNT_GREATER_OR_EQUAL_THAN_PROPERTY to \"unset\")\n .hasNoLintViolations()\n }\n \n@@ -511,6 +518,7 @@ class FunctionSignatureRuleTest {\n \"\"\".trimIndent()\n functionSignatureWrappingRuleAssertThat(code)\n .setMaxLineLength()\n+ .withEditorConfigOverride(FORCE_MULTILINE_WHEN_PARAMETER_COUNT_GREATER_OR_EQUAL_THAN_PROPERTY to \"unset\")\n .hasNoLintViolations()\n }\n \n@@ -623,7 +631,8 @@ class FunctionSignatureRuleTest {\n { SpacingAroundDotRule() },\n { SpacingAroundCommaRule() },\n { SpacingAroundColonRule() },\n- ).hasLintViolations(\n+ ).withEditorConfigOverride(FORCE_MULTILINE_WHEN_PARAMETER_COUNT_GREATER_OR_EQUAL_THAN_PROPERTY to \"unset\")\n+ .hasLintViolations(\n LintViolation(3, 10, \"No whitespace expected between opening parenthesis and first parameter name\"),\n LintViolation(7, 17, \"Single whitespace expected before parameter\"),\n LintViolation(8, 22, \"No whitespace expected between last parameter and closing parenthesis\"),\n@@ -669,7 +678,8 @@ class FunctionSignatureRuleTest {\n { SpacingAroundColonRule() },\n { SpacingAroundCommaRule() },\n { SpacingAroundOperatorsRule() },\n- ).hasLintViolation(2, 15, \"Single whitespace expected before parameter\")\n+ ).withEditorConfigOverride(FORCE_MULTILINE_WHEN_PARAMETER_COUNT_GREATER_OR_EQUAL_THAN_PROPERTY to \"unset\")\n+ .hasLintViolation(2, 15, \"Single whitespace expected before parameter\")\n .isFormattedAs(formattedCode)\n }\n }\n@@ -692,6 +702,7 @@ class FunctionSignatureRuleTest {\n \"\"\".trimIndent()\n functionSignatureWrappingRuleAssertThat(code)\n .setMaxLineLength()\n+ .withEditorConfigOverride(FORCE_MULTILINE_WHEN_PARAMETER_COUNT_GREATER_OR_EQUAL_THAN_PROPERTY to \"unset\")\n .withEditorConfigOverride(FUNCTION_BODY_EXPRESSION_WRAPPING_PROPERTY to bodyExpressionWrapping)\n .hasNoLintViolations()\n }\n@@ -717,6 +728,7 @@ class FunctionSignatureRuleTest {\n \"\"\".trimIndent()\n functionSignatureWrappingRuleAssertThat(code)\n .setMaxLineLength()\n+ .withEditorConfigOverride(FORCE_MULTILINE_WHEN_PARAMETER_COUNT_GREATER_OR_EQUAL_THAN_PROPERTY to \"unset\")\n .withEditorConfigOverride(FUNCTION_BODY_EXPRESSION_WRAPPING_PROPERTY to bodyExpressionWrapping)\n .addAdditionalRuleProvider { IndentationRule() }\n .hasLintViolation(2, 33, \"Newline expected before expression body\")\n@@ -746,6 +758,7 @@ class FunctionSignatureRuleTest {\n \"\"\".trimIndent()\n functionSignatureWrappingRuleAssertThat(code)\n .setMaxLineLength()\n+ .withEditorConfigOverride(FORCE_MULTILINE_WHEN_PARAMETER_COUNT_GREATER_OR_EQUAL_THAN_PROPERTY to \"unset\")\n .withEditorConfigOverride(FUNCTION_BODY_EXPRESSION_WRAPPING_PROPERTY to bodyExpressionWrapping)\n .addAdditionalRuleProvider { IndentationRule() }\n .hasLintViolation(2, 33, \"Newline expected before expression body\")\n@@ -780,6 +793,7 @@ class FunctionSignatureRuleTest {\n \"\"\".trimIndent()\n functionSignatureWrappingRuleAssertThat(code)\n .setMaxLineLength()\n+ .withEditorConfigOverride(FORCE_MULTILINE_WHEN_PARAMETER_COUNT_GREATER_OR_EQUAL_THAN_PROPERTY to \"unset\")\n .withEditorConfigOverride(FUNCTION_BODY_EXPRESSION_WRAPPING_PROPERTY to bodyExpressionWrapping)\n .addAdditionalRuleProvider { IndentationRule() }\n .hasLintViolations(\n@@ -814,6 +828,7 @@ class FunctionSignatureRuleTest {\n \"\"\".trimIndent()\n functionSignatureWrappingRuleAssertThat(code)\n .setMaxLineLength()\n+ .withEditorConfigOverride(FORCE_MULTILINE_WHEN_PARAMETER_COUNT_GREATER_OR_EQUAL_THAN_PROPERTY to \"unset\")\n .withEditorConfigOverride(FUNCTION_BODY_EXPRESSION_WRAPPING_PROPERTY to bodyExpressionWrapping)\n .addAdditionalRuleProvider { IndentationRule() }\n .hasLintViolations(\n@@ -851,6 +866,7 @@ class FunctionSignatureRuleTest {\n \"\"\".trimIndent()\n functionSignatureWrappingRuleAssertThat(code)\n .setMaxLineLength()\n+ .withEditorConfigOverride(FORCE_MULTILINE_WHEN_PARAMETER_COUNT_GREATER_OR_EQUAL_THAN_PROPERTY to \"unset\")\n .withEditorConfigOverride(FUNCTION_BODY_EXPRESSION_WRAPPING_PROPERTY to bodyExpressionWrapping)\n .addAdditionalRuleProvider { IndentationRule() }\n .hasLintViolations(\n@@ -886,6 +902,7 @@ class FunctionSignatureRuleTest {\n \"\"\".trimIndent()\n functionSignatureWrappingRuleAssertThat(code)\n .setMaxLineLength()\n+ .withEditorConfigOverride(FORCE_MULTILINE_WHEN_PARAMETER_COUNT_GREATER_OR_EQUAL_THAN_PROPERTY to \"unset\")\n .withEditorConfigOverride(FUNCTION_BODY_EXPRESSION_WRAPPING_PROPERTY to bodyExpressionWrapping)\n .addAdditionalRuleProvider { IndentationRule() }\n .hasLintViolations(\n@@ -923,6 +940,7 @@ class FunctionSignatureRuleTest {\n \"\"\".trimIndent()\n functionSignatureWrappingRuleAssertThat(code)\n .setMaxLineLength()\n+ .withEditorConfigOverride(FORCE_MULTILINE_WHEN_PARAMETER_COUNT_GREATER_OR_EQUAL_THAN_PROPERTY to \"unset\")\n .withEditorConfigOverride(FUNCTION_BODY_EXPRESSION_WRAPPING_PROPERTY to bodyExpressionWrapping)\n .addAdditionalRuleProvider { IndentationRule() }\n .hasLintViolations(\n@@ -1097,6 +1115,7 @@ class FunctionSignatureRuleTest {\n \"\"\".trimIndent()\n functionSignatureWrappingRuleAssertThat(code)\n .setMaxLineLength()\n+ .withEditorConfigOverride(FORCE_MULTILINE_WHEN_PARAMETER_COUNT_GREATER_OR_EQUAL_THAN_PROPERTY to \"unset\")\n .hasNoLintViolations()\n }\n \ndiff --git a/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/IndentationRuleTest.kt b/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/IndentationRuleTest.kt\nindex 8136d881a5..65909b8edd 100644\n--- a/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/IndentationRuleTest.kt\n+++ b/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/IndentationRuleTest.kt\n@@ -1494,7 +1494,7 @@ internal class IndentationRuleTest {\n @Nested\n inner class `Given a nested conditional` {\n @Test\n- fun `Given a simple nested conditional`() {\n+ fun `Given a non-ktlint_official code style and a simple nested conditional`() {\n val code =\n \"\"\"\n val foo =\n@@ -1514,6 +1514,7 @@ internal class IndentationRuleTest {\n )\n \"\"\".trimIndent()\n indentationRuleAssertThat(code)\n+ .withEditorConfigOverride(CODE_STYLE_PROPERTY to intellij_idea)\n .hasLintViolations(\n LintViolation(2, 1, \"Unexpected indentation (0) (should be 4)\"),\n LintViolation(3, 1, \"Unexpected indentation (0) (should be 8)\"),\n@@ -1524,7 +1525,7 @@ internal class IndentationRuleTest {\n }\n \n @Test\n- fun `Given a method chain combined with nested conditionals`() {\n+ fun `Given a non-ktlint_official code style and a method chain combined with nested conditionals`() {\n val code =\n \"\"\"\n val foo =\n@@ -1558,6 +1559,7 @@ internal class IndentationRuleTest {\n false\n \"\"\".trimIndent()\n indentationRuleAssertThat(code)\n+ .withEditorConfigOverride(CODE_STYLE_PROPERTY to intellij_idea)\n .hasLintViolations(\n LintViolation(2, 1, \"Unexpected indentation (0) (should be 4)\"),\n LintViolation(3, 1, \"Unexpected indentation (0) (should be 8)\"),\n@@ -1575,7 +1577,7 @@ internal class IndentationRuleTest {\n }\n \n @Test\n- fun `Given a while statement with method chain combined with nested conditionals`() {\n+ fun `Given a non-ktlint_official code style and a while statement with method chain combined with nested conditionals`() {\n val code =\n \"\"\"\n fun foo() {\n@@ -1619,6 +1621,7 @@ internal class IndentationRuleTest {\n }\n \"\"\".trimIndent()\n indentationRuleAssertThat(code)\n+ .withEditorConfigOverride(CODE_STYLE_PROPERTY to intellij_idea)\n .hasLintViolations(\n LintViolation(2, 1, \"Unexpected indentation (0) (should be 4)\"),\n LintViolation(3, 1, \"Unexpected indentation (0) (should be 8)\"),\n@@ -1640,7 +1643,7 @@ internal class IndentationRuleTest {\n }\n \n @Test\n- fun `Given an if-statement with method chain combined with nested conditionals`() {\n+ fun `Given a non-ktlint_official code style and an if-statement with method chain combined with nested conditionals`() {\n val code =\n \"\"\"\n fun foo() {\n@@ -1684,6 +1687,7 @@ internal class IndentationRuleTest {\n }\n \"\"\".trimIndent()\n indentationRuleAssertThat(code)\n+ .withEditorConfigOverride(CODE_STYLE_PROPERTY to intellij_idea)\n .hasLintViolations(\n LintViolation(2, 1, \"Unexpected indentation (0) (should be 4)\"),\n LintViolation(3, 1, \"Unexpected indentation (0) (should be 8)\"),\n@@ -2171,7 +2175,7 @@ internal class IndentationRuleTest {\n }\n \n @Test\n- fun `Given if-else-statement for which branches are wrapped between parenthesis`() {\n+ fun `Given non-ktlint_official code style and if-else-statement for which branches are wrapped between parenthesis`() {\n val code =\n \"\"\"\n val foo = if (true) (\n@@ -2180,7 +2184,9 @@ internal class IndentationRuleTest {\n 3 + 4\n ) // IDEA quirk\n \"\"\".trimIndent()\n- indentationRuleAssertThat(code).hasNoLintViolations()\n+ indentationRuleAssertThat(code)\n+ .withEditorConfigOverride(CODE_STYLE_PROPERTY to intellij_idea)\n+ .hasNoLintViolations()\n }\n \n @Test\n@@ -3579,7 +3585,7 @@ internal class IndentationRuleTest {\n }\n \n @Test\n- fun `Issue 1003 - Given multiple interfaces`() {\n+ fun `Issue 1003 - Given non-ktlint_official code style and multiple interfaces`() {\n val code =\n \"\"\"\n abstract class Parent(a: Int, b: Int)\n@@ -3595,7 +3601,9 @@ internal class IndentationRuleTest {\n ),\n Parent2\n \"\"\".trimIndent()\n- indentationRuleAssertThat(code).hasNoLintViolations()\n+ indentationRuleAssertThat(code)\n+ .withEditorConfigOverride(CODE_STYLE_PROPERTY to intellij_idea)\n+ .hasNoLintViolations()\n }\n \n @Test\ndiff --git a/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/NoWildcardImportsRuleTest.kt b/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/NoWildcardImportsRuleTest.kt\nindex f87600faf3..0e0c5f23d3 100644\n--- a/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/NoWildcardImportsRuleTest.kt\n+++ b/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/NoWildcardImportsRuleTest.kt\n@@ -1,7 +1,8 @@\n package com.pinterest.ktlint.ruleset.standard.rules\n \n import com.pinterest.ktlint.rule.engine.core.api.editorconfig.CODE_STYLE_PROPERTY\n-import com.pinterest.ktlint.rule.engine.core.api.editorconfig.CodeStyleValue\n+import com.pinterest.ktlint.rule.engine.core.api.editorconfig.CodeStyleValue.intellij_idea\n+import com.pinterest.ktlint.rule.engine.core.api.editorconfig.CodeStyleValue.ktlint_official\n import com.pinterest.ktlint.ruleset.standard.rules.NoWildcardImportsRule.Companion.IJ_KOTLIN_PACKAGES_TO_USE_IMPORT_ON_DEMAND\n import com.pinterest.ktlint.test.KtLintAssertThat.Companion.assertThatRule\n import com.pinterest.ktlint.test.LintViolation\n@@ -12,9 +13,9 @@ class NoWildcardImportsRuleTest {\n private val noWildcardImportsRuleAssertThat = assertThatRule { NoWildcardImportsRule() }\n \n @Nested\n- inner class `Given that editorconfig property packagesToUseImportOnDemandProperty is not set` {\n+ inner class `Given that editorconfig property ij_kotlin_packages_to_use_import_on_demand is not set` {\n @Test\n- fun `Wildcard imports are detected`() {\n+ fun `Given the ktlint_official codestyle then the default wildcard imports allowed in other code styles are no longer allowed`() {\n val code =\n \"\"\"\n import a\n@@ -22,29 +23,44 @@ class NoWildcardImportsRuleTest {\n import a.b.c\n import a.d.*\n import foo.bar.`**`\n+ import java.util.*\n+ import kotlinx.android.synthetic.*\n \"\"\".trimIndent()\n noWildcardImportsRuleAssertThat(code)\n+ .withEditorConfigOverride(CODE_STYLE_PROPERTY to ktlint_official)\n .hasLintViolationsWithoutAutoCorrect(\n LintViolation(2, 1, \"Wildcard import\"),\n LintViolation(4, 1, \"Wildcard import\"),\n+ LintViolation(6, 1, \"Wildcard import\"),\n+ LintViolation(7, 1, \"Wildcard import\"),\n )\n }\n \n @Test\n- fun `Wildcard imports on packages which are accepted by IntelliJ Default are not detected`() {\n+ fun `Given a non-ktlint_official codestyle then the default wildcard imports allowed in other code styles are no longer allowed`() {\n val code =\n \"\"\"\n- import a.b\n- import kotlinx.android.synthetic.main.layout_name.*\n+ import a\n+ import a.b.*\n+ import a.b.c\n+ import a.d.*\n+ import foo.bar.`**`\n+ import java.util.*\n+ import kotlinx.android.synthetic.*\n \"\"\".trimIndent()\n- noWildcardImportsRuleAssertThat(code).hasNoLintViolations()\n+ noWildcardImportsRuleAssertThat(code)\n+ .withEditorConfigOverride(CODE_STYLE_PROPERTY to intellij_idea)\n+ .hasLintViolationsWithoutAutoCorrect(\n+ LintViolation(2, 1, \"Wildcard import\"),\n+ LintViolation(4, 1, \"Wildcard import\"),\n+ )\n }\n }\n \n @Nested\n- inner class `Given that editorconfig property packagesToUseImportOnDemandProperty is set` {\n+ inner class `Given that editorconfig property ij_kotlin_packages_to_use_import_on_demand is set` {\n @Test\n- fun `Given that the property is set with value 'unset' then packages which are accepted by IntelliJ Default are not detected`() {\n+ fun `Given ktlint_official code style and the property is set with value 'unset' then packages which are accepted by IntelliJ Default are detected`() {\n val code =\n \"\"\"\n import a.b\n@@ -53,6 +69,26 @@ class NoWildcardImportsRuleTest {\n import react.dom.*\n \"\"\".trimIndent()\n noWildcardImportsRuleAssertThat(code)\n+ .withEditorConfigOverride(CODE_STYLE_PROPERTY to ktlint_official)\n+ .withEditorConfigOverride(IJ_KOTLIN_PACKAGES_TO_USE_IMPORT_ON_DEMAND to \"unset\")\n+ .hasLintViolationsWithoutAutoCorrect(\n+ LintViolation(2, 1, \"Wildcard import\"),\n+ LintViolation(3, 1, \"Wildcard import\"),\n+ LintViolation(4, 1, \"Wildcard import\"),\n+ )\n+ }\n+\n+ @Test\n+ fun `Given non-ktlint_official code style and the property is set with value 'unset' then packages which are accepted by IntelliJ Default are not detected`() {\n+ val code =\n+ \"\"\"\n+ import a.b\n+ import kotlinx.android.synthetic.main.layout_name.*\n+ import react.*\n+ import react.dom.*\n+ \"\"\".trimIndent()\n+ noWildcardImportsRuleAssertThat(code)\n+ .withEditorConfigOverride(CODE_STYLE_PROPERTY to intellij_idea)\n .withEditorConfigOverride(IJ_KOTLIN_PACKAGES_TO_USE_IMPORT_ON_DEMAND to \"unset\")\n .hasLintViolationsWithoutAutoCorrect(\n LintViolation(3, 1, \"Wildcard import\"),\n@@ -100,19 +136,4 @@ class NoWildcardImportsRuleTest {\n .hasLintViolationWithoutAutoCorrect(2, 1, \"Wildcard import\")\n }\n }\n-\n- @Test\n- fun `Given the ktlint_official codestyle then the default wildcard imports allowed in other code styles are no longer allowed`() {\n- val code =\n- \"\"\"\n- import java.util.*\n- import kotlinx.android.synthetic.*\n- \"\"\".trimIndent()\n- noWildcardImportsRuleAssertThat(code)\n- .withEditorConfigOverride(CODE_STYLE_PROPERTY to CodeStyleValue.ktlint_official)\n- .hasLintViolationsWithoutAutoCorrect(\n- LintViolation(1, 1, \"Wildcard import\"),\n- LintViolation(2, 1, \"Wildcard import\"),\n- )\n- }\n }\ndiff --git a/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/ParameterWrappingRuleTest.kt b/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/ParameterWrappingRuleTest.kt\nindex ed1fc33bcd..4518554d8f 100644\n--- a/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/ParameterWrappingRuleTest.kt\n+++ b/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/ParameterWrappingRuleTest.kt\n@@ -22,17 +22,15 @@ internal class ParameterWrappingRuleTest {\n )\n \"\"\".trimIndent()\n val formattedCode =\n- // TODO: fix test when changing the default code style to 'ktlint_official'. The variable type is not indented for the\n- // current default code style.\n \"\"\"\n // $MAX_LINE_LENGTH_MARKER $EOL_CHAR\n class Bar(\n val foooooooooooooooooTooLong:\n- Foo,\n+ Foo,\n )\n fun bar(\n foooooooooooooooooooooTooLong:\n- Foo,\n+ Foo,\n )\n \"\"\".trimIndent()\n parameterWrappingRuleAssertThat(code)\n@@ -59,18 +57,16 @@ internal class ParameterWrappingRuleTest {\n )\n \"\"\".trimIndent()\n val formattedCode =\n- // TODO: fix test when changing the default code style to 'ktlint_official'. The variable type is not indented for the\n- // current default code style.\n \"\"\"\n // $MAX_LINE_LENGTH_MARKER $EOL_CHAR\n class Bar(\n val foooooooooooooooooTooLong:\n- Foo,\n+ Foo,\n val foooooooooooooNotTooLong: Foo,\n )\n fun bar(\n foooooooooooooooooooooTooLong:\n- Foo,\n+ Foo,\n foooooooooooooooooNotTooLong: Foo,\n )\n \"\"\".trimIndent()\n", "problem_statement": "Change default code style to `ktlint_official`\nStarting of ktlint `1.0` the default code style changes from `intellij_idea` (former `kotlin_official`) to `ktlint_official`. The `ktlint_official` codestyle adheres to the best parts of the [Kotlin Coding Conventions](https://kotlinlang.org/docs/coding-conventions.html) and [Android Kotlint styleguid](https://developer.android.com/kotlin/style-guide). But it no longer is restricted to produce code compatible with the default IntelliJ IDEA formatter which lacks from bug which still are not resolved after multiple years.\r\n\n", "hints_text": "", "created_at": "2023-07-22T18:55:58Z", "version": "0.50", "FAIL_TO_PASS": [ "gradle_test_execution" ], "PASS_TO_PASS": [], "ERROR_TO_PASS": [], "environment_setup_commit": "0a2500665d514f27ad06828544c43a6f28924426" }, { "repo": "pinterest/ktlint", "pull_number": 2141, "instance_id": "pinterest__ktlint-2141", "issue_numbers": [ "2140" ], "base_commit": "b139c14dcf4c9b97d063b55a33504872da860cc8", "patch": "diff --git a/CHANGELOG.md b/CHANGELOG.md\nindex 2770232846..6c8f94e2e5 100644\n--- a/CHANGELOG.md\n+++ b/CHANGELOG.md\n@@ -21,6 +21,7 @@ This project adheres to [Semantic Versioning](https://semver.org/).\n * Fix spacing around colon in annotations `spacing-around-colon` ([#2093](https://github.com/pinterest/ktlint/issues/2093))\n * Do not wrap a binary expression after an elvis operator in case the max line length is exceeded ([#2128](https://github.com/pinterest/ktlint/issues/2128))\n * Fix indent of IS_EXPRESSION, PREFIX_EXPRESSION and POSTFIX_EXPRESSION in case it contains a linebreak `indent` [#2094](https://github.com/pinterest/ktlint/issues/2094)\n+* Fix false positive regarding property that potentially can contain data which is mutable. `property-naming` [#2140](https://github.com/pinterest/ktlint/issues/2140)\n * Add new experimental rule `function-literal`. This rule enforces the parameter list of a function literal to be formatted consistently. `function-literal` [#2121](https://github.com/pinterest/ktlint/issues/2121)\n * Fix null pointer exception for if-else statement with empty THEN block `if-else-bracing` [#2135](https://github.com/pinterest/ktlint/issues/2135)\n \ndiff --git a/documentation/snapshot/docs/rules/experimental.md b/documentation/snapshot/docs/rules/experimental.md\nindex 5e57426856..0c64d7cc75 100644\n--- a/documentation/snapshot/docs/rules/experimental.md\n+++ b/documentation/snapshot/docs/rules/experimental.md\n@@ -637,20 +637,26 @@ Rule id: `package-naming` (`standard` rule set)\n \n Enforce naming of property.\n \n+!!! note\n+ This rule can not reliably detect all situations in which incorrect property naming is used. So it only detects in which it is certain that naming is incorrect.\n+\n === \"[:material-heart:](#) Ktlint\"\n \n ```kotlin\n- val FOO_1 = Foo()\n- val FOO_BAR_1 = \"FOO-BAR\"\n+ val foo1 = Foo() // In case developer want to communicate that Foo is mutable\n+ val FOO1 = Foo() // In case developer want to communicate that Foo is deeply immutable\n \n- var foo1: Foo = Foo()\n+ const val FOO_BAR = \"FOO-BAR\" // By definition deeply immutable\n+\n+ var foo2: Foo = Foo() // By definition not immutable\n \n class Bar {\n- const val FOO_2 = \"foo\"\n- const val FOO_BAR_2 = \"FOO-BAR\"\n+ val foo1 = Foo() // In case developer want to communicate that Foo is mutable\n+ val FOO1 = Foo() // In case developer want to communicate that Foo is deeply immutable\n+\n+ const val FOO_BAR = \"FOO-BAR\" // By definition deeply immutable\n \n- val foo2 = \"foo\"\n- val fooBar2 = \"foo-bar\"\n+ var foo2: Foo = Foo() // By definition not immutable\n \n // Backing property\n private val _elementList = mutableListOf()\n@@ -661,17 +667,12 @@ Enforce naming of property.\n === \"[:material-heart-off-outline:](#) Disallowed\"\n \n ```kotlin\n- val Foo1 = Foo()\n- val FooBar1 = \"FOO-BAR\"\n+ const val fooBar = \"FOO-BAR\" // By definition deeply immutable\n \n- var FOO_1: Foo = Foo()\n+ var FOO2: Foo = Foo() // By definition not immutable\n \n class Bar {\n- const val foo2 = \"foo\"\n- const val fooBar2 = \"FOO-BAR\"\n-\n- val FOO2 = \"foo\"\n- val FOO_BAR_2 = \"foo-bar\"\n+ val FOO_BAR = \"FOO-BAR\" // Class properties always start with lowercase, const is not allowed\n \n // Incomplete backing property as public property 'elementList1' is missing\n private val _elementList1 = mutableListOf()\n@@ -683,9 +684,6 @@ Enforce naming of property.\n }\n ```\n \n-!!! note\n- Top level `val` properties and `const val` properties have to be written in screaming snake notation. Local `val` and `const val` are written in lower camel case.\n-\n This rule can also be suppressed with the IntelliJ IDEA inspection suppression `PropertyName`.\n \n Rule id: `property-naming` (`standard` rule set)\ndiff --git a/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/PropertyNamingRule.kt b/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/PropertyNamingRule.kt\nindex 79f1e477a7..0e5d2f7120 100644\n--- a/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/PropertyNamingRule.kt\n+++ b/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/PropertyNamingRule.kt\n@@ -45,17 +45,15 @@ public class PropertyNamingRule :\n .findChildByType(IDENTIFIER)\n ?.let { identifier ->\n when {\n- property.hasCustomGetter() -> {\n+ property.hasConstModifier() -> {\n+ visitConstProperty(identifier, emit)\n+ }\n+ property.hasCustomGetter() || property.isTopLevelValue() || property.isObjectValue() -> {\n // Can not reliably determine whether the value is immutable or not\n }\n property.isBackingProperty() -> {\n visitBackingProperty(identifier, emit)\n }\n- property.hasConstModifier() ||\n- property.isTopLevelValue() ||\n- property.isObjectValue() -> {\n- visitConstProperty(identifier, emit)\n- }\n else -> {\n visitNonConstProperty(identifier, emit)\n }\n", "test_patch": "diff --git a/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/PropertyNamingRuleTest.kt b/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/PropertyNamingRuleTest.kt\nindex 1fbf6136f9..2963208bbd 100644\n--- a/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/PropertyNamingRuleTest.kt\n+++ b/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/PropertyNamingRuleTest.kt\n@@ -1,14 +1,15 @@\n package com.pinterest.ktlint.ruleset.standard.rules\n \n-import com.pinterest.ktlint.test.KtLintAssertThat\n+import com.pinterest.ktlint.test.KtLintAssertThat.Companion.assertThatRule\n+import com.pinterest.ktlint.test.KtlintDocumentationTest\n+import com.pinterest.ktlint.test.LintViolation\n import org.junit.jupiter.api.Nested\n import org.junit.jupiter.api.Test\n import org.junit.jupiter.params.ParameterizedTest\n import org.junit.jupiter.params.provider.ValueSource\n \n class PropertyNamingRuleTest {\n- private val propertyNamingRuleAssertThat =\n- KtLintAssertThat.assertThatRule { PropertyNamingRule() }\n+ private val propertyNamingRuleAssertThat = assertThatRule { PropertyNamingRule() }\n \n @Test\n fun `Given a valid property name then do not emit`() {\n@@ -49,19 +50,18 @@ class PropertyNamingRuleTest {\n }\n \n @Test\n- fun `Given a top level val property name not in screaming case notation then do emit`() {\n+ fun `Issue 2140 - Given a top level val property name not in screaming case notation then do not emit as it can not be reliably be determined whether the value is (deeply) immutable`() {\n val code =\n \"\"\"\n val foo = Foo()\n val FOO_BAR = FooBar()\n \"\"\".trimIndent()\n @Suppress(\"ktlint:standard:argument-list-wrapping\", \"ktlint:standard:max-line-length\")\n- propertyNamingRuleAssertThat(code)\n- .hasLintViolationWithoutAutoCorrect(1, 5, \"Property name should use the screaming snake case notation when the value can not be changed\")\n+ propertyNamingRuleAssertThat(code).hasNoLintViolations()\n }\n \n @Test\n- fun `Given an object val property name not having a custom get function and not in screaming case notation then do emit`() {\n+ fun `Issue 2140 - Given an object val property name not having a custom get function and not in screaming case notation then do not emit as it can not be reliably be determined whether the value is (deeply) immutable`() {\n val code =\n \"\"\"\n class Foo {\n@@ -72,8 +72,7 @@ class PropertyNamingRuleTest {\n }\n \"\"\".trimIndent()\n @Suppress(\"ktlint:standard:argument-list-wrapping\", \"ktlint:standard:max-line-length\")\n- propertyNamingRuleAssertThat(code)\n- .hasLintViolationWithoutAutoCorrect(3, 13, \"Property name should use the screaming snake case notation when the value can not be changed\")\n+ propertyNamingRuleAssertThat(code).hasNoLintViolations()\n }\n \n @Test\n@@ -208,4 +207,67 @@ class PropertyNamingRuleTest {\n propertyNamingRuleAssertThat(code).hasNoLintViolations()\n }\n }\n+\n+ @KtlintDocumentationTest\n+ fun `Ktlint allowed examples`() {\n+ val code =\n+ \"\"\"\n+ val foo1 = Foo() // In case developer want to communicate that Foo is mutable\n+ val FOO1 = Foo() // In case developer want to communicate that Foo is deeply immutable\n+\n+ const val FOO_BAR = \"FOO-BAR\" // By definition deeply immutable\n+\n+ var foo2: Foo = Foo() // By definition not immutable\n+\n+ class Bar {\n+ val foo1 = \"foo1\" // Class properties always start with lowercase, const is not allowed\n+\n+ const val FOO_BAR = \"FOO-BAR\" // By definition deeply immutable\n+\n+ var foo2: Foo = Foo() // By definition not immutable\n+\n+ // Backing property\n+ private val _elementList = mutableListOf()\n+ val elementList: List\n+ get() = _elementList\n+\n+ companion object {\n+ val foo1 = Foo() // In case developer want to communicate that Foo is mutable\n+ val FOO1 = Foo() // In case developer want to communicate that Foo is deeply immutable\n+ }\n+ }\n+ \"\"\".trimIndent()\n+ propertyNamingRuleAssertThat(code).hasNoLintViolations()\n+ }\n+\n+ @KtlintDocumentationTest\n+ fun `Ktlint disallowed examples`() {\n+ val code =\n+ \"\"\"\n+ const val fooBar = \"FOO-BAR\" // By definition deeply immutable\n+\n+ var FOO2: Foo = Foo() // By definition not immutable\n+\n+ class Bar {\n+ val FOO_BAR = \"FOO-BAR\" // Class properties always start with lowercase, const is not allowed\n+\n+ // Incomplete backing property as public property 'elementList1' is missing\n+ private val _elementList1 = mutableListOf()\n+\n+ // Invalid backing property as '_elementList2' is not a private property\n+ val _elementList2 = mutableListOf()\n+ val elementList2: List\n+ get() = _elementList2\n+ }\n+ \"\"\".trimIndent()\n+ @Suppress(\"ktlint:standard:argument-list-wrapping\", \"ktlint:standard:max-line-length\")\n+ propertyNamingRuleAssertThat(code)\n+ .hasLintViolations(\n+ LintViolation(1, 11, \"Property name should use the screaming snake case notation when the value can not be changed\", canBeAutoCorrected = false),\n+ LintViolation(3, 5, \"Property name should start with a lowercase letter and use camel case\", canBeAutoCorrected = false),\n+ LintViolation(6, 9, \"Property name should start with a lowercase letter and use camel case\", canBeAutoCorrected = false),\n+ LintViolation(9, 17, \"Property name should start with a lowercase letter and use camel case\", canBeAutoCorrected = false),\n+ LintViolation(12, 9, \"Property name should start with a lowercase letter and use camel case\", canBeAutoCorrected = false),\n+ )\n+ }\n }\n", "problem_statement": "Mutable collection property name should not be SCREAMING_SNAKE_CASE\n\r\n\r\n## Expected Behavior\r\nMutable collection property name should not be SCREAMING_SNAKE_CASE - https://developer.android.com/kotlin/style-guide#non-constant_names\r\n```kotlint\r\nobject : DumObjectName {\r\n val someMap: MutableMap = ...\r\n}\r\n```\r\n\r\n## Observed Behavior\r\nktlint require SCREAMING_SNAKE_CASE:\r\n```kotlint\r\nobject : DumObjectName {\r\n val SOME_MAP: MutableMap = ...\r\n}\r\n```\r\n\r\n## Steps to Reproduce\r\nCreate object, with mutable collection property. \r\n\r\n## Your Environment\r\n\r\n* Version of ktlint used: 0.50.0\r\n\n", "hints_text": "You're right. Can you provide a little more context where this variable is declared? Is it at top level, or in a companion object or class?\nI have edited the issue, so you can see where the property is declared. \r\n\r\nIn my case it is an object's property. I did not check for other cases as top level or companion object's variables (SCREAMING_SNAKE_CASE naming should not be applied to class properties according to https://developer.android.com/kotlin/style-guide#constant_names).", "created_at": "2023-07-21T19:50:09Z", "version": "0.50", "FAIL_TO_PASS": [ "gradle_test_execution" ], "PASS_TO_PASS": [], "ERROR_TO_PASS": [], "environment_setup_commit": "0a2500665d514f27ad06828544c43a6f28924426" }, { "repo": "pinterest/ktlint", "pull_number": 1851, "instance_id": "pinterest__ktlint-1851", "issue_numbers": [ "1788" ], "base_commit": "4b62df581dac1ab05839c7f7b76e7083da50d68f", "patch": "diff --git a/CHANGELOG.md b/CHANGELOG.md\nindex d8b697c3f7..d6644ea4f0 100644\n--- a/CHANGELOG.md\n+++ b/CHANGELOG.md\n@@ -224,9 +224,10 @@ Previously the default value for `.editorconfig` property `max_line_length` was\n \n ### Added\n \n-* Add new experimental rule for `ktlint_official` code style that disallows a class to start with a blank line `no-empty-first-line-in-class-body`.\n-* Add new experimental rule for `ktlint_official` code style that enforces consistent usage of braces in all branches of a singe if or if-else-if statement `if-else-bracing`.\n-* Add new experimental rule for `ktlint_official` code style that disallows consecutive comments except EOL comments `no-consecutive-comments`\n+* Add new experimental rule `no-empty-first-line-in-class-body` for `ktlint_official` code style. This rule disallows a class to start with a blank line. This rule can also be run for other code styles but then its needs to be explicitly enabled.\n+* Add new experimental rule `if-else-bracing` for `ktlint_official` code style. This rules enforces consistent usage of braces in all branches of a singe if or if-else-if statement. This rule can also be run for other code styles but then its needs to be explicitly enabled.\n+* Add new experimental rule `no-consecutive-comments` for `ktlint_official` code style. This rule disallows consecutive comments except EOL comments. This rule can also be run for other code styles but then its needs to be explicitly enabled.\n+* Add new experimental rule `try-catch-finally-spacing` for `ktlint_official` code style. This rule enforces consistent spacing in try-catch, try-finally and try-catch-finally statement. This rule can also be run for other code styles but then its needs to be explicitly enabled.\n * Wrap the type or value of a function or class parameter in case the maximum line length is exceeded `parameter-wrapping` ([#1846](https://github.com/pinterest/ktlint/pull/1846))\n * Wrap the type or value of a property in case the maximum line length is exceeded `property-wrapping` ([#1846](https://github.com/pinterest/ktlint/pull/1846))\n \n@@ -247,6 +248,8 @@ Previously the default value for `.editorconfig` property `max_line_length` was\n * Do not report an \"unnecessary semicolon\" after adding a trailing comma to an enum class containing a code element after the last enum entry `trailing-comma-on-declaration-site` ([#1786](https://github.com/pinterest/ktlint/issues/1786))\n * A newline before a function return type should not be removed in case that leads to exceeding the maximum line length `function-return-type-spacing` ([#1764](https://github.com/pinterest/ktlint/issues/1764))\n * Wrap annotations on type arguments in same way as with other constructs `annotation`, `wrapping` ([#1725](https://github.com/pinterest/ktlint/issues/1725))\n+* Fix indentation of try-catch-finally when catch or finally starts on a newline `indent` ([#1788](https://github.com/pinterest/ktlint/issues/1788))\n+* Fix indentation of a multiline typealias `indent` ([#1788](https://github.com/pinterest/ktlint/issues/1788))\n \n ### Changed\n * Wrap the parameters of a function literal containing a multiline parameter list (only in `ktlint_official` code style) `parameter-list-wrapping` ([#1681](https://github.com/pinterest/ktlint/issues/1681)).\ndiff --git a/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/IndentationRule.kt b/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/IndentationRule.kt\nindex 737e9a6280..3694bedae5 100644\n--- a/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/IndentationRule.kt\n+++ b/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/IndentationRule.kt\n@@ -12,6 +12,7 @@ import com.pinterest.ktlint.rule.engine.core.api.ElementType.BLOCK\n import com.pinterest.ktlint.rule.engine.core.api.ElementType.BLOCK_COMMENT\n import com.pinterest.ktlint.rule.engine.core.api.ElementType.BODY\n import com.pinterest.ktlint.rule.engine.core.api.ElementType.CALL_EXPRESSION\n+import com.pinterest.ktlint.rule.engine.core.api.ElementType.CATCH\n import com.pinterest.ktlint.rule.engine.core.api.ElementType.CLASS\n import com.pinterest.ktlint.rule.engine.core.api.ElementType.CLASS_BODY\n import com.pinterest.ktlint.rule.engine.core.api.ElementType.CLOSING_QUOTE\n@@ -26,6 +27,7 @@ import com.pinterest.ktlint.rule.engine.core.api.ElementType.DOT_QUALIFIED_EXPRE\n import com.pinterest.ktlint.rule.engine.core.api.ElementType.ELSE\n import com.pinterest.ktlint.rule.engine.core.api.ElementType.ELVIS\n import com.pinterest.ktlint.rule.engine.core.api.ElementType.EQ\n+import com.pinterest.ktlint.rule.engine.core.api.ElementType.FINALLY\n import com.pinterest.ktlint.rule.engine.core.api.ElementType.FOR\n import com.pinterest.ktlint.rule.engine.core.api.ElementType.FUN\n import com.pinterest.ktlint.rule.engine.core.api.ElementType.FUNCTION_LITERAL\n@@ -61,6 +63,8 @@ import com.pinterest.ktlint.rule.engine.core.api.ElementType.SUPER_TYPE_CALL_ENT\n import com.pinterest.ktlint.rule.engine.core.api.ElementType.SUPER_TYPE_ENTRY\n import com.pinterest.ktlint.rule.engine.core.api.ElementType.SUPER_TYPE_LIST\n import com.pinterest.ktlint.rule.engine.core.api.ElementType.THEN\n+import com.pinterest.ktlint.rule.engine.core.api.ElementType.TRY\n+import com.pinterest.ktlint.rule.engine.core.api.ElementType.TYPEALIAS\n import com.pinterest.ktlint.rule.engine.core.api.ElementType.TYPE_ARGUMENT_LIST\n import com.pinterest.ktlint.rule.engine.core.api.ElementType.TYPE_CONSTRAINT\n import com.pinterest.ktlint.rule.engine.core.api.ElementType.TYPE_CONSTRAINT_LIST\n@@ -109,8 +113,7 @@ import org.jetbrains.kotlin.com.intellij.psi.impl.source.tree.LeafPsiElement\n import org.jetbrains.kotlin.psi.KtStringTemplateExpression\n import org.jetbrains.kotlin.psi.psiUtil.leaves\n import org.jetbrains.kotlin.psi.psiUtil.parents\n-import java.util.Deque\n-import java.util.LinkedList\n+import java.util.*\n \n private val LOGGER = KotlinLogging.logger {}.initKtLintKLogger()\n \n@@ -296,7 +299,8 @@ public class IndentationRule :\n node.elementType == KDOC ->\n visitKdoc(node)\n \n- node.elementType == PROPERTY_ACCESSOR ->\n+ node.elementType == PROPERTY_ACCESSOR ||\n+ node.elementType == TYPEALIAS ->\n visitPropertyAccessor(node)\n \n node.elementType == FOR ||\n@@ -309,7 +313,11 @@ public class IndentationRule :\n node.elementType == NULLABLE_TYPE ->\n visitNullableType(node)\n \n- node.elementType == DESTRUCTURING_DECLARATION -> visitDestructuringDeclaration(node)\n+ node.elementType == DESTRUCTURING_DECLARATION ->\n+ visitDestructuringDeclaration(node)\n+\n+ node.elementType == TRY ->\n+ visitTryCatchFinally(node)\n \n else -> {\n LOGGER.trace { \"No processing for ${node.elementType}: ${node.textWithEscapedTabAndNewline()}\" }\n@@ -765,6 +773,36 @@ public class IndentationRule :\n }\n }\n \n+ private fun visitTryCatchFinally(node: ASTNode) {\n+ // Inner indent contexts in reversed order\n+ var nextToAstNode = node.lastChildLeafOrSelf()\n+ node\n+ .findChildByType(FINALLY)\n+ ?.let { finally ->\n+ nextToAstNode = startIndentContext(\n+ fromAstNode = finally,\n+ toAstNode = nextToAstNode,\n+ childIndent = \"\",\n+ ).prevCodeLeaf()\n+ }\n+\n+ node\n+ .findChildByType(CATCH)\n+ ?.let { catch ->\n+ nextToAstNode = startIndentContext(\n+ fromAstNode = catch,\n+ toAstNode = nextToAstNode,\n+ childIndent = \"\",\n+ ).prevCodeLeaf()\n+ }\n+\n+ startIndentContext(\n+ fromAstNode = node,\n+ toAstNode = nextToAstNode,\n+ lastChildIndent = \"\",\n+ )\n+ }\n+\n private fun ASTNode.skipLeadingWhitespaceCommentsAndAnnotations(): ASTNode {\n require(elementType == SECONDARY_CONSTRUCTOR || elementType == VALUE_PARAMETER)\n return findChildByType(MODIFIER_LIST)\n", "test_patch": "diff --git a/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/IndentationRuleTest.kt b/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/IndentationRuleTest.kt\nindex 79d0d3a49c..eb21667346 100644\n--- a/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/IndentationRuleTest.kt\n+++ b/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/IndentationRuleTest.kt\n@@ -4876,6 +4876,51 @@ internal class IndentationRuleTest {\n }\n }\n \n+ @Nested\n+ inner class `Given a try-catch-finally` {\n+ @Test\n+ fun `Given a try catch finally which if properly formatted`() {\n+ val code =\n+ \"\"\"\n+ fun foo() = try {\n+ 1\n+ } catch(_: Throwable) {\n+ 2\n+ } finally {\n+ 3\n+ }\n+ \"\"\".trimIndent()\n+ indentationRuleAssertThat(code).hasNoLintViolations()\n+ }\n+\n+ @Test\n+ fun `Issue 1788 - Given a try catch finally where catch and finally starts on a new line`() {\n+ val code =\n+ \"\"\"\n+ fun foo() = try {\n+ 1\n+ }\n+ catch(_: Throwable) {\n+ 2\n+ }\n+ finally {\n+ 3\n+ }\n+ \"\"\".trimIndent()\n+ indentationRuleAssertThat(code).hasNoLintViolations()\n+ }\n+ }\n+\n+ @Test\n+ fun `Given a type alias with the value on a separate line`() {\n+ val code =\n+ \"\"\"\n+ typealias FooBar =\n+ HashMap\n+ \"\"\".trimIndent()\n+ indentationRuleAssertThat(code).hasNoLintViolations()\n+ }\n+\n private companion object {\n val INDENT_STYLE_TAB =\n INDENT_STYLE_PROPERTY to PropertyType.IndentStyleValue.tab\n", "problem_statement": "False positive on indent with try/catch and typealias\n## Expected Behavior\r\nThe following code is valid:\r\n\r\n```\r\nfun test() = try {\r\n 1\r\n}\r\ncatch(_: Throwable) {\r\n 2\r\n}\r\n```\r\n\r\nand\r\n\r\n```\r\ntypealias Foo =\r\n HashMap\r\n```\r\n\r\n## Observed Behavior\r\nktlint formats the code like this:\r\n\r\n```\r\nfun test() = try {\r\n 1\r\n}\r\n catch(_: Throwable) {\r\n 2\r\n }\r\n```\r\n\r\nand\r\n\r\n```\r\ntypealias Foo =\r\nHashMap\r\n```\r\n\r\n## Steps to Reproduce\r\nRun `ktlint --format`\r\n\r\n.editorconfig:\r\n\r\n```\r\n[*.{kt,kts}]\r\nij_kotlin_allow_trailing_comma = false\r\nij_kotlin_allow_trailing_comma_on_call_site = false\r\nindent_size = 2\r\nindent_style = space\r\ninsert_final_newline = true\r\nktlint_experimental = enabled\r\nktlint_experimental_comment-wrapping = disabled\r\nktlint_experimental_function-naming = disabled\r\nktlint_experimental_function-signature = disabled\r\nktlint_experimental_property-naming = disabled\r\nktlint_standard_annotation = disabled\r\nktlint_standard_filename = disabled\r\nktlint_standard_keyword-spacing = disabled\r\nktlint_standard_max-line-length = disabled\r\nktlint_standard_no-semi = disabled\r\nktlint_standard_package-name = disabled\r\nktlint_standard_spacing-between-declarations-with-annotations = disabled\r\nktlint_standard_string-template = disabled\r\nmax_line_length = 120\r\n```\r\n\r\nThe formatting is correct when ktlint 0.47.1 is used\r\n\r\n## Your Environment\r\n* Version of ktlint used: 0.48.2\r\n* Operating System and version: Ubuntu 22.04\r\n\n", "hints_text": "", "created_at": "2023-03-12T12:54:39Z", "version": "0.49", "FAIL_TO_PASS": [ "gradle_test_execution" ], "PASS_TO_PASS": [], "ERROR_TO_PASS": [], "environment_setup_commit": "410d8849874f4d3600f9d4572e0850adccce4f2d" }, { "repo": "pinterest/ktlint", "pull_number": 1853, "instance_id": "pinterest__ktlint-1853", "issue_numbers": [ "1802" ], "base_commit": "0fa29ba481ffd942c7d81a46d4fc133939aad83a", "patch": "diff --git a/CHANGELOG.md b/CHANGELOG.md\nindex d6644ea4f0..1b9e68b5a4 100644\n--- a/CHANGELOG.md\n+++ b/CHANGELOG.md\n@@ -250,6 +250,7 @@ Previously the default value for `.editorconfig` property `max_line_length` was\n * Wrap annotations on type arguments in same way as with other constructs `annotation`, `wrapping` ([#1725](https://github.com/pinterest/ktlint/issues/1725))\n * Fix indentation of try-catch-finally when catch or finally starts on a newline `indent` ([#1788](https://github.com/pinterest/ktlint/issues/1788))\n * Fix indentation of a multiline typealias `indent` ([#1788](https://github.com/pinterest/ktlint/issues/1788))\n+* Fix false positive when multiple KDOCs exists between a declaration and another annotated declaration `spacing-between-declarations-with-annotations` ([#1802](https://github.com/pinterest/ktlint/issues/1802))\n \n ### Changed\n * Wrap the parameters of a function literal containing a multiline parameter list (only in `ktlint_official` code style) `parameter-list-wrapping` ([#1681](https://github.com/pinterest/ktlint/issues/1681)).\ndiff --git a/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/SpacingBetweenDeclarationsWithAnnotationsRule.kt b/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/SpacingBetweenDeclarationsWithAnnotationsRule.kt\nindex bb30a5a77a..5d52cd19b2 100644\n--- a/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/SpacingBetweenDeclarationsWithAnnotationsRule.kt\n+++ b/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/SpacingBetweenDeclarationsWithAnnotationsRule.kt\n@@ -3,17 +3,18 @@ package com.pinterest.ktlint.ruleset.standard.rules\n import com.pinterest.ktlint.rule.engine.core.api.ElementType.MODIFIER_LIST\n import com.pinterest.ktlint.rule.engine.core.api.RuleId\n import com.pinterest.ktlint.rule.engine.core.api.children\n+import com.pinterest.ktlint.rule.engine.core.api.indent\n+import com.pinterest.ktlint.rule.engine.core.api.isPartOfComment\n+import com.pinterest.ktlint.rule.engine.core.api.isWhiteSpace\n+import com.pinterest.ktlint.rule.engine.core.api.prevLeaf\n+import com.pinterest.ktlint.rule.engine.core.api.upsertWhitespaceBeforeMe\n import com.pinterest.ktlint.ruleset.standard.StandardRule\n import org.jetbrains.kotlin.com.intellij.lang.ASTNode\n-import org.jetbrains.kotlin.com.intellij.psi.PsiComment\n import org.jetbrains.kotlin.com.intellij.psi.PsiElement\n-import org.jetbrains.kotlin.com.intellij.psi.PsiWhiteSpace\n-import org.jetbrains.kotlin.com.intellij.psi.impl.source.tree.LeafPsiElement\n import org.jetbrains.kotlin.psi.KtAnnotationEntry\n import org.jetbrains.kotlin.psi.KtDeclaration\n import org.jetbrains.kotlin.psi.psiUtil.getPrevSiblingIgnoringWhitespaceAndComments\n-import org.jetbrains.kotlin.psi.psiUtil.prevLeaf\n-import org.jetbrains.kotlin.psi.psiUtil.prevLeafs\n+import org.jetbrains.kotlin.psi.psiUtil.leaves\n \n /**\n * @see https://youtrack.jetbrains.com/issue/KT-35106\n@@ -24,47 +25,50 @@ public class SpacingBetweenDeclarationsWithAnnotationsRule : StandardRule(\"spaci\n autoCorrect: Boolean,\n emit: (offset: Int, errorMessage: String, canBeAutoCorrected: Boolean) -> Unit,\n ) {\n- if (node.elementType == MODIFIER_LIST && node.hasAnnotationsAsChildren()) {\n- val declaration = node.psi.parent as? KtDeclaration\n- val prevDeclaration =\n- declaration?.getPrevSiblingIgnoringWhitespaceAndComments(withItself = false) as? KtDeclaration\n- val whiteSpaceAfterPreviousDeclaration = prevDeclaration?.nextSibling as? PsiWhiteSpace\n- val startOfDeclarationIncludingLeadingComment = node.psi.parent.getPrevLeafIgnoringCommentAndWhitespaceExceptBlankLines()\n- if (whiteSpaceAfterPreviousDeclaration?.text != null &&\n- startOfDeclarationIncludingLeadingComment?.text?.count { it == '\\n' } == 1\n- ) {\n+ if (node.psi is KtDeclaration && node.isAnnotated()) {\n+ visitDeclaration(node, emit, autoCorrect)\n+ }\n+ }\n+\n+ private fun visitDeclaration(\n+ node: ASTNode,\n+ emit: (offset: Int, errorMessage: String, canBeAutoCorrected: Boolean) -> Unit,\n+ autoCorrect: Boolean,\n+ ) {\n+ node\n+ .psi\n+ ?.getPrevSiblingIgnoringWhitespaceAndComments(withItself = false)\n+ ?.takeIf { it is KtDeclaration }\n+ ?.takeIf { prevDeclaration -> hasNoBlankLineBetweenDeclarations(node, prevDeclaration) }\n+ ?.let {\n+ val prevLeaf = node.prevLeaf { it.isWhiteSpace() || it.isPartOfComment() }!!\n emit(\n- node.startOffset,\n+ prevLeaf.startOffset + 1,\n \"Declarations and declarations with annotations should have an empty space between.\",\n true,\n )\n if (autoCorrect) {\n- val indent = whiteSpaceAfterPreviousDeclaration.text.substringAfter('\\n')\n- (whiteSpaceAfterPreviousDeclaration.node as LeafPsiElement).rawReplaceWithText(\"\\n\\n$indent\")\n+ prevLeaf.upsertWhitespaceBeforeMe(\"\\n\".plus(node.indent()))\n }\n }\n- }\n }\n \n- /**\n- * Gets the previous element but ignores white whitespaces (excluding blank lines) and comments. Note the difference\n- * with method [PsiElement.getPrevSiblingIgnoringWhitespaceAndComments] which excludes blank lines as well.\n- */\n- private fun PsiElement.getPrevLeafIgnoringCommentAndWhitespaceExceptBlankLines(): PsiElement? {\n- var prevLeaf: PsiElement? = this.prevLeaf()\n- val iterator = prevLeafs.iterator()\n- while (iterator.hasNext()) {\n- val psiElement = iterator.next()\n- if (psiElement is PsiComment || (psiElement is PsiWhiteSpace && psiElement.text?.count { it == '\\n' } == 1)) {\n- prevLeaf = psiElement\n- } else {\n- break\n- }\n- }\n- return prevLeaf\n- }\n+ private fun ASTNode.isAnnotated(): Boolean =\n+ findChildByType(MODIFIER_LIST)\n+ ?.children()\n+ ?.any { it.psi is KtAnnotationEntry }\n+ ?: false\n+\n+ private fun hasNoBlankLineBetweenDeclarations(\n+ node: ASTNode,\n+ prevDeclaration: PsiElement,\n+ ) = node\n+ .leaves(false)\n+ .takeWhile { it.isWhiteSpace() || it.isPartOfComment() }\n+ .takeWhile { it.psi != prevDeclaration }\n+ .none { it.isBlankLine() }\n \n- private fun ASTNode.hasAnnotationsAsChildren(): Boolean = children().find { it.psi is KtAnnotationEntry } != null\n+ private fun ASTNode.isBlankLine() = isWhiteSpace() && text.count { it == '\\n' } > 1\n }\n \n public val SPACING_BETWEEN_DECLARATIONS_WITH_ANNOTATIONS_RULE_ID: RuleId = SpacingBetweenDeclarationsWithAnnotationsRule().ruleId\n", "test_patch": "diff --git a/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/SpacingBetweenDeclarationsWithAnnotationsRuleTest.kt b/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/SpacingBetweenDeclarationsWithAnnotationsRuleTest.kt\nindex bce051404d..f4e0e9f2fd 100644\n--- a/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/SpacingBetweenDeclarationsWithAnnotationsRuleTest.kt\n+++ b/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/SpacingBetweenDeclarationsWithAnnotationsRuleTest.kt\n@@ -133,7 +133,7 @@ class SpacingBetweenDeclarationsWithAnnotationsRuleTest {\n }\n \"\"\".trimIndent()\n spacingBetweenDeclarationsWithAnnotationsRuleAssertThat(code)\n- .hasLintViolation(5, 5, \"Declarations and declarations with annotations should have an empty space between.\")\n+ .hasLintViolation(5, 1, \"Declarations and declarations with annotations should have an empty space between.\")\n .isFormattedAs(formattedCode)\n }\n \n@@ -204,4 +204,20 @@ class SpacingBetweenDeclarationsWithAnnotationsRuleTest {\n \"\"\".trimIndent()\n spacingBetweenDeclarationsWithAnnotationsRuleAssertThat(code).hasNoLintViolations()\n }\n+\n+ @Test\n+ fun `Issue 1802 - Given a declaration followed by multiple kdocs and an annotated declaration`() {\n+ val code =\n+ \"\"\"\n+ public var foo = \"foo\"\n+\n+ /**\n+ * Kdoc1\n+ */\n+ /** Kdoc2 */\n+ @Bar\n+ public var bar = \"bar\"\n+ \"\"\".trimIndent()\n+ spacingBetweenDeclarationsWithAnnotationsRuleAssertThat(code).hasNoLintViolations()\n+ }\n }\n", "problem_statement": "Accidental double-KDoc reported as consecutive line space problem\n## Expected Behavior\r\n\r\nI have no idea. Maybe there should be a rule for this? Useless KDoc rule?\r\n\r\n\r\n## Observed Behavior\r\n\r\nConsecutive blank line rule triggers despite there not being consecutive blank lines.\r\n\r\n## Steps to Reproduce\r\n\r\n```kotlin\r\n /**\r\n * True to throw a [JsonDataException] on any attempt to call [skipValue].\r\n *\r\n * ## Getting\r\n * Returns true if this parser forbids skipping names and values.\r\n *\r\n * ## Setting\r\n * Configure whether this parser throws a [JsonDataException] when [skipValue] is\r\n * called. By default this parser permits values to be skipped.\r\n *\r\n * Forbid skipping to prevent unrecognized values from being silently ignored. This option is\r\n * useful in development and debugging because it means a typo like \"locatiom\" will be detected\r\n * early. It's potentially harmful in production because it complicates revising a JSON schema.\r\n */\r\n /** Returns true if this parser forbids skipping names and values. */\r\n @get:JvmName(\"failOnUnknown\")\r\n public var failOnUnknown: Boolean = false\r\n```\r\n```\r\nStep 'ktlint' found problem in 'moshi/src/main/java/com/squareup/moshi/JsonReader.kt':\r\nError on line: 219, column: 1\r\nrule: no-consecutive-blank-lines\r\nNeedless blank line(s)\r\n```\r\n\r\n## Your Environment\r\n* Version of ktlint used: 0.48.2\r\n* Name and version (or code for custom task) of integration used (Gradle plugin, Maven plugin, command line, custom Gradle task): Spotless `spotApply` task\r\n\n", "hints_text": "I can not reproduce the problem with ktlint `0.48.2` with the given code sample. Can you try to reproduce with Ktlint CLI instead of spotless?\nUh it may require an additional property below it. Or above it?\r\n\r\nBut yes I'll try.\nOkay here's a problematic snippet:\r\n```kotlin\r\npublic class JsonReader {\r\n public var lenient: Boolean = false\r\n\r\n /**\r\n * Hey\r\n */\r\n /** Sup */\r\n @get:Synchronied\r\n public var failOnUnknown: Boolean = false\r\n}\r\n```\r\n```\r\n$ ktlint JsonReader.kt\r\nJsonReader.kt:8:3: Declarations and declarations with annotations should have an empty space between. (spacing-between-declarations-with-annotations)\r\n\r\nSummary error count (descending) by rule:\r\n spacing-between-declarations-with-annotations: 1\r\n\r\n$ ktlint -F JsonReader.kt\r\nJsonReader.kt:4:1: Needless blank line(s) (no-consecutive-blank-lines)\r\nJsonReader.kt:8:4: Declarations and declarations with annotations should have an empty space between. (spacing-between-declarations-with-annotations)\r\n\r\nSummary error count (descending) by rule:\r\n no-consecutive-blank-lines: 1\r\n spacing-between-declarations-with-annotations: 1\r\n```\r\nThe act of formatting actually added the second blank line between properties because of the double KDoc.\r\n```diff\r\nindex 529ab4c..d931a98 100644\r\n--- JsonReader.kt\r\n+++ JsonReader.kt\r\n@@ -1,6 +1,7 @@\r\n public class JsonReader {\r\n public var lenient: Boolean = false\r\n\r\n+\r\n /**\r\n * Hey\r\n */\nTnx, this is reproducable.\r\n\r\n> Maybe there should be a rule for this? Useless KDoc rule?\r\n\r\nKtlint `0.49.0` will get a new rule `no-consecutive-comments` (#1454) which also detects consecutive KDoc's.", "created_at": "2023-03-12T16:19:48Z", "version": "0.49", "FAIL_TO_PASS": [ "gradle_test_execution" ], "PASS_TO_PASS": [], "ERROR_TO_PASS": [], "environment_setup_commit": "410d8849874f4d3600f9d4572e0850adccce4f2d" }, { "repo": "pinterest/ktlint", "pull_number": 2142, "instance_id": "pinterest__ktlint-2142", "issue_numbers": [ "2135" ], "base_commit": "2c163c6829dafd0f31b6a91b6f11515521116938", "patch": "diff --git a/CHANGELOG.md b/CHANGELOG.md\nindex 6c63ef32a6..7d4abb95bb 100644\n--- a/CHANGELOG.md\n+++ b/CHANGELOG.md\n@@ -22,6 +22,7 @@ This project adheres to [Semantic Versioning](https://semver.org/).\n * Do not wrap a binary expression after an elvis operator in case the max line length is exceeded ([#2128](https://github.com/pinterest/ktlint/issues/2128))\n * Fix indent of IS_EXPRESSION, PREFIX_EXPRESSION and POSTFIX_EXPRESSION in case it contains a linebreak `indent` [#2094](https://github.com/pinterest/ktlint/issues/2094)\n * Add new experimental rule `function-literal`. This rule enforces the parameter list of a function literal to be formatted consistently. `function-literal` [#2121](https://github.com/pinterest/ktlint/issues/2121)\n+* Fix null pointer exception for if-else statement with empty THEN block `if-else-bracing` [#2135](https://github.com/pinterest/ktlint/issues/2135)\n \n ### Changed\n \ndiff --git a/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/IfElseBracingRule.kt b/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/IfElseBracingRule.kt\nindex a88ba9600f..1cfda745e1 100644\n--- a/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/IfElseBracingRule.kt\n+++ b/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/IfElseBracingRule.kt\n@@ -117,7 +117,7 @@ public class IfElseBracingRule :\n emit: (offset: Int, errorMessage: String, canBeAutoCorrected: Boolean) -> Unit,\n ): Boolean {\n emit(\n- node.firstChildNode.startOffset,\n+ node.firstChildNode?.startOffset ?: node.startOffset,\n \"All branches of the if statement should be wrapped between braces if at least one branch is wrapped between braces\",\n true,\n )\n@@ -149,15 +149,26 @@ public class IfElseBracingRule :\n }\n KtBlockExpression(null).apply {\n val previousChild = node.firstChildNode\n- node.replaceChild(node.firstChildNode, this)\n+ if (previousChild == null) {\n+ node.addChild(this, null)\n+ } else {\n+ node.replaceChild(node.firstChildNode, this)\n+ }\n addChild(LeafPsiElement(LBRACE, \"{\"))\n- addChild(PsiWhiteSpaceImpl(indentConfig.childIndentOf(node)))\n+ if (previousChild != null) {\n+ addChild(PsiWhiteSpaceImpl(indentConfig.childIndentOf(node)))\n+ }\n prevLeaves\n .dropWhile { it.isWhiteSpace() }\n- .forEach(::addChild)\n- addChild(previousChild)\n+ .takeIf { it.isNotEmpty() }\n+ ?.forEach(::addChild)\n+ if (previousChild != null) {\n+ addChild(previousChild)\n+ }\n nextLeaves.forEach(::addChild)\n- addChild(PsiWhiteSpaceImpl(node.indent()))\n+ if (previousChild != null) {\n+ addChild(PsiWhiteSpaceImpl(node.indent()))\n+ }\n addChild(LeafPsiElement(RBRACE, \"}\"))\n }\n \n", "test_patch": "diff --git a/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/IfElseBracingRuleTest.kt b/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/IfElseBracingRuleTest.kt\nindex b3fe8f0069..99bbddc1c8 100644\n--- a/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/IfElseBracingRuleTest.kt\n+++ b/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/IfElseBracingRuleTest.kt\n@@ -372,4 +372,21 @@ class IfElseBracingRuleTest {\n .hasNoLintViolations()\n }\n }\n+\n+ @Test\n+ fun `Issue 2135 - Given ktlint_official code style and an if statement with and empty THEN block then do not throw a null pointer exception`() {\n+ val code =\n+ \"\"\"\n+ val foo = if (false) else { bar() }\n+ \"\"\".trimIndent()\n+ val formattedCode =\n+ \"\"\"\n+ val foo = if (false) {} else { bar() }\n+ \"\"\".trimIndent()\n+ @Suppress(\"ktlint:standard:argument-list-wrapping\", \"ktlint:standard:max-line-length\")\n+ multiLineIfElseRuleAssertThat(code)\n+ .withEditorConfigOverride(CODE_STYLE_PROPERTY to ktlint_official)\n+ .hasLintViolation(1, 22, \"All branches of the if statement should be wrapped between braces if at least one branch is wrapped between braces\")\n+ .isFormattedAs(formattedCode)\n+ }\n }\n", "problem_statement": "Nullpointer exception for if-else statement having an empty THEN block\nI made a typo in a multiline if else statement. While technically valid Kotlin code, it causes Ktlint to crash.\r\n\r\n## Expected Behavior\r\nI don't know exactly how Ktlint should behave here with regards to formatting, but it probably shouldn't crash.\r\n\r\n## Observed Behavior\r\n```\r\nInternal Error (rule 'standard:multiline-if-else') in Test.kt at position '0:0. Please create a ticket at https://github.com/pinterest/ktlint/issues and provide the source code that triggered an error.\r\ncom.pinterest.ktlint.rule.engine.api.KtLintRuleException: Rule 'standard:multiline-if-else' throws exception in file 'PrepareGoogle.kt' at position (0:0)\r\n Rule maintainer: KtLint\r\n Issue tracker : https://github.com/pinterest/ktlint/issues\r\n Repository : https://github.com/pinterest/ktlint\r\n\tat com.pinterest.ktlint.rule.engine.internal.RuleExecutionContext.executeRule(RuleExecutionContext.kt:65)\r\n\tat com.pinterest.ktlint.rule.engine.api.KtLintRuleEngine$format$3.invoke(KtLintRuleEngine.kt:154)\r\n\tat com.pinterest.ktlint.rule.engine.api.KtLintRuleEngine$format$3.invoke(KtLintRuleEngine.kt:153)\r\n\tat com.pinterest.ktlint.rule.engine.internal.VisitorProvider$visitor$3.invoke(VisitorProvider.kt:46)\r\n\tat com.pinterest.ktlint.rule.engine.internal.VisitorProvider$visitor$3.invoke(VisitorProvider.kt:44)\r\n\tat com.pinterest.ktlint.rule.engine.api.KtLintRuleEngine.format(KtLintRuleEngine.kt:153)\r\n\tat com.pinterest.ktlint.cli.internal.KtlintCommandLine.format(KtlintCommandLine.kt:485)\r\n\tat com.pinterest.ktlint.cli.internal.KtlintCommandLine.process(KtlintCommandLine.kt:471)\r\n\tat com.pinterest.ktlint.cli.internal.KtlintCommandLine.access$process(KtlintCommandLine.kt:61)\r\n\tat com.pinterest.ktlint.cli.internal.KtlintCommandLine$lintFiles$3.invoke$lambda$0(KtlintCommandLine.kt:411)\r\n\tat java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264)\r\n\tat java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1136)\r\n\tat java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:635)\r\n\tat java.base/java.lang.Thread.run(Thread.java:833)\r\nCaused by: java.lang.NullPointerException: Cannot invoke \"org.jetbrains.kotlin.com.intellij.lang.ASTNode.getElementType()\" because the return value of \"org.jetbrains.kotlin.com.intellij.lang.ASTNode.getFirstChildNode()\" is null\r\n\tat com.pinterest.ktlint.ruleset.standard.rules.MultiLineIfElseRule.beforeVisitChildNodes(MultiLineIfElseRule.kt:98)\r\n\tat com.pinterest.ktlint.rule.engine.internal.RuleExecutionContext$executeRuleOnNodeRecursively$1.invoke(RuleExecutionContext.kt:125)\r\n\tat com.pinterest.ktlint.rule.engine.internal.RuleExecutionContext$executeRuleOnNodeRecursively$1.invoke(RuleExecutionContext.kt:124)\r\n\tat com.pinterest.ktlint.rule.engine.internal.SuppressHandler.handle(SuppressHandler.kt:28)\r\n\tat com.pinterest.ktlint.rule.engine.internal.RuleExecutionContext.executeRuleOnNodeRecursively(RuleExecutionContext.kt:124)\r\n\tat com.pinterest.ktlint.rule.engine.internal.RuleExecutionContext.executeRuleOnNodeRecursively(RuleExecutionContext.kt:93)\r\n\tat com.pinterest.ktlint.rule.engine.internal.RuleExecutionContext.access$executeRuleOnNodeRecursively(RuleExecutionContext.kt:30)\r\n\tat com.pinterest.ktlint.rule.engine.internal.RuleExecutionContext$executeRuleOnNodeRecursively$2$1.invoke(RuleExecutionContext.kt:132)\r\n\tat com.pinterest.ktlint.rule.engine.internal.RuleExecutionContext$executeRuleOnNodeRecursively$2$1.invoke(RuleExecutionContext.kt:131)\r\n\tat com.pinterest.ktlint.rule.engine.internal.SuppressHandler.handle(SuppressHandler.kt:28)\r\n\tat com.pinterest.ktlint.rule.engine.internal.RuleExecutionContext.executeRuleOnNodeRecursively(RuleExecutionContext.kt:131)\r\n\tat com.pinterest.ktlint.rule.engine.internal.RuleExecutionContext.executeRuleOnNodeRecursively(RuleExecutionContext.kt:93)\r\n\tat com.pinterest.ktlint.rule.engine.internal.RuleExecutionContext.access$executeRuleOnNodeRecursively(RuleExecutionContext.kt:30)\r\n\tat com.pinterest.ktlint.rule.engine.internal.RuleExecutionContext$executeRuleOnNodeRecursively$2$1.invoke(RuleExecutionContext.kt:132)\r\n\tat com.pinterest.ktlint.rule.engine.internal.RuleExecutionContext$executeRuleOnNodeRecursively$2$1.invoke(RuleExecutionContext.kt:131)\r\n\tat com.pinterest.ktlint.rule.engine.internal.SuppressHandler.handle(SuppressHandler.kt:28)\r\n\tat com.pinterest.ktlint.rule.engine.internal.RuleExecutionContext.executeRuleOnNodeRecursively(RuleExecutionContext.kt:131)\r\n\tat com.pinterest.ktlint.rule.engine.internal.RuleExecutionContext.executeRuleOnNodeRecursively(RuleExecutionContext.kt:93)\r\n\tat com.pinterest.ktlint.rule.engine.internal.RuleExecutionContext.access$executeRuleOnNodeRecursively(RuleExecutionContext.kt:30)\r\n\tat com.pinterest.ktlint.rule.engine.internal.RuleExecutionContext$executeRuleOnNodeRecursively$2$1.invoke(RuleExecutionContext.kt:132)\r\n\tat com.pinterest.ktlint.rule.engine.internal.RuleExecutionContext$executeRuleOnNodeRecursively$2$1.invoke(RuleExecutionContext.kt:131)\r\n\tat com.pinterest.ktlint.rule.engine.internal.SuppressHandler.handle(SuppressHandler.kt:28)\r\n\tat com.pinterest.ktlint.rule.engine.internal.RuleExecutionContext.executeRuleOnNodeRecursively(RuleExecutionContext.kt:131)\r\n\tat com.pinterest.ktlint.rule.engine.internal.RuleExecutionContext.executeRuleOnNodeRecursively(RuleExecutionContext.kt:93)\r\n\tat com.pinterest.ktlint.rule.engine.internal.RuleExecutionContext.access$executeRuleOnNodeRecursively(RuleExecutionContext.kt:30)\r\n\tat com.pinterest.ktlint.rule.engine.internal.RuleExecutionContext$executeRuleOnNodeRecursively$2$1.invoke(RuleExecutionContext.kt:132)\r\n\tat com.pinterest.ktlint.rule.engine.internal.RuleExecutionContext$executeRuleOnNodeRecursively$2$1.invoke(RuleExecutionContext.kt:131)\r\n\tat com.pinterest.ktlint.rule.engine.internal.SuppressHandler.handle(SuppressHandler.kt:28)\r\n\tat com.pinterest.ktlint.rule.engine.internal.RuleExecutionContext.executeRuleOnNodeRecursively(RuleExecutionContext.kt:131)\r\n\tat com.pinterest.ktlint.rule.engine.internal.RuleExecutionContext.executeRuleOnNodeRecursively(RuleExecutionContext.kt:93)\r\n\tat com.pinterest.ktlint.rule.engine.internal.RuleExecutionContext.access$executeRuleOnNodeRecursively(RuleExecutionContext.kt:30)\r\n\tat com.pinterest.ktlint.rule.engine.internal.RuleExecutionContext$executeRuleOnNodeRecursively$2$1.invoke(RuleExecutionContext.kt:132)\r\n\tat com.pinterest.ktlint.rule.engine.internal.RuleExecutionContext$executeRuleOnNodeRecursively$2$1.invoke(RuleExecutionContext.kt:131)\r\n\tat com.pinterest.ktlint.rule.engine.internal.SuppressHandler.handle(SuppressHandler.kt:28)\r\n\tat com.pinterest.ktlint.rule.engine.internal.RuleExecutionContext.executeRuleOnNodeRecursively(RuleExecutionContext.kt:131)\r\n\tat com.pinterest.ktlint.rule.engine.internal.RuleExecutionContext.executeRuleOnNodeRecursively(RuleExecutionContext.kt:93)\r\n\tat com.pinterest.ktlint.rule.engine.internal.RuleExecutionContext.access$executeRuleOnNodeRecursively(RuleExecutionContext.kt:30)\r\n\tat com.pinterest.ktlint.rule.engine.internal.RuleExecutionContext$executeRuleOnNodeRecursively$2$1.invoke(RuleExecutionContext.kt:132)\r\n\tat com.pinterest.ktlint.rule.engine.internal.RuleExecutionContext$executeRuleOnNodeRecursively$2$1.invoke(RuleExecutionContext.kt:131)\r\n\tat com.pinterest.ktlint.rule.engine.internal.SuppressHandler.handle(SuppressHandler.kt:28)\r\n\tat com.pinterest.ktlint.rule.engine.internal.RuleExecutionContext.executeRuleOnNodeRecursively(RuleExecutionContext.kt:131)\r\n\tat com.pinterest.ktlint.rule.engine.internal.RuleExecutionContext.executeRuleOnNodeRecursively(RuleExecutionContext.kt:93)\r\n\tat com.pinterest.ktlint.rule.engine.internal.RuleExecutionContext.access$executeRuleOnNodeRecursively(RuleExecutionContext.kt:30)\r\n```\r\n\r\n\r\n## Steps to Reproduce\r\n```\r\n if (\"a\" == \"b\") {\r\n } else if (\"b\" == \"c\") else {\r\n }\r\n```\r\n\r\n## Your Environment\r\n\r\n* Version of ktlint used: 0.50.0\r\n* Relevant parts of the `.editorconfig` settings\r\n* Name and version (or code for custom task) of integration used (Gradle plugin, Maven plugin, command line, custom Gradle task): Custom Gradle task\r\n* Version of Gradle used (if applicable): 8.2.1\r\n* Operating System and version: macOS\r\n\n", "hints_text": ">```\r\n> if (\"a\" == \"b\") {\r\n> } else if (\"b\" == \"c\") else {\r\n> }\r\n>```\r\n\r\nKotlin keeps amazing me. I would never have expected that this was valid Kotlin code. Tnx for reporting the bug.", "created_at": "2023-07-22T15:54:17Z", "version": "0.50", "FAIL_TO_PASS": [ "gradle_test_execution" ], "PASS_TO_PASS": [], "ERROR_TO_PASS": [], "environment_setup_commit": "0a2500665d514f27ad06828544c43a6f28924426" }, { "repo": "pinterest/ktlint", "pull_number": 1852, "instance_id": "pinterest__ktlint-1852", "issue_numbers": [ "1797" ], "base_commit": "c0066b4a77f478a6606369c0b5d03c74ec2e08d6", "patch": "diff --git a/.editorconfig b/.editorconfig\nindex f761e59c0e..00a10e0581 100644\n--- a/.editorconfig\n+++ b/.editorconfig\n@@ -23,6 +23,9 @@ ktlint_standard = enabled\n # we are not pleased ourselves with the results on the ktlint code base.\n ktlint_experimental = enabled\n \n+# Don't allow any wildcard imports\n+ij_kotlin_packages_to_use_import_on_demand = unset\n+\n [*.md]\n trim_trailing_whitespace = false\n \ndiff --git a/CHANGELOG.md b/CHANGELOG.md\nindex 1b9e68b5a4..62fd532301 100644\n--- a/CHANGELOG.md\n+++ b/CHANGELOG.md\n@@ -263,6 +263,7 @@ Previously the default value for `.editorconfig` property `max_line_length` was\n * Disable the default patterns if the option `--patterns-from-stdin` is specified ([#1793](https://github.com/pinterest/ktlint/issues/1793))\n * Update Kotlin development version to `1.8.20-Beta` and Kotlin version to `1.8.10`.\n * Revert to matrix build to speed up build, especially for the Windows related build ([#1787](https://github.com/pinterest/ktlint/pull/1787))\n+* For the new code style `ktlint_official`, do not allow wildcard imports `java.util` and `kotlinx.android.synthetic` by default. Important: `.editorconfig` property `ij_kotlin_packages_to_use_import_on_demand` needs to be set to value `unset` in order to enforce IntelliJ IDEA default formatter to not generate wildcard imports `no-wildcard-imports` ([#1797](https://github.com/pinterest/ktlint/issues/1797))\n \n ## [0.48.2] - 2023-01-21\n \ndiff --git a/docs/rules/standard.md b/docs/rules/standard.md\nindex b298f0c685..28571ff1ce 100644\n--- a/docs/rules/standard.md\n+++ b/docs/rules/standard.md\n@@ -153,7 +153,7 @@ No wildcard imports except imports listed in `.editorconfig` property `ij_kotlin\n In case property `ij_kotlin_packages_to_use_import_on_demand` is not explicitly set, it allows wildcards imports like `java.util.*` by default to keep in sync with IntelliJ IDEA behavior. To disallow *all* wildcard imports, add property below to your `.editorconfig`:\n ```editorconfig\n [*.{kt,kts}]\n- ij_kotlin_packages_to_use_import_on_demand = nothing\n+ ij_kotlin_packages_to_use_import_on_demand = unset\n ```\n \n Rule id: `no-wildcard-imports`\ndiff --git a/ktlint-cli/src/main/kotlin/com/pinterest/ktlint/cli/internal/KtlintCommandLine.kt b/ktlint-cli/src/main/kotlin/com/pinterest/ktlint/cli/internal/KtlintCommandLine.kt\nindex baee2c7aef..5f946c6ec3 100644\n--- a/ktlint-cli/src/main/kotlin/com/pinterest/ktlint/cli/internal/KtlintCommandLine.kt\n+++ b/ktlint-cli/src/main/kotlin/com/pinterest/ktlint/cli/internal/KtlintCommandLine.kt\n@@ -43,7 +43,7 @@ import java.io.File\n import java.nio.file.FileSystems\n import java.nio.file.Path\n import java.nio.file.Paths\n-import java.util.*\n+import java.util.Locale\n import java.util.concurrent.ArrayBlockingQueue\n import java.util.concurrent.Callable\n import java.util.concurrent.Executors\n@@ -51,6 +51,8 @@ import java.util.concurrent.Future\n import java.util.concurrent.TimeUnit\n import java.util.concurrent.atomic.AtomicBoolean\n import java.util.concurrent.atomic.AtomicInteger\n+import kotlin.collections.ArrayList\n+import kotlin.collections.LinkedHashSet\n import kotlin.concurrent.thread\n import kotlin.io.path.absolutePathString\n import kotlin.io.path.pathString\ndiff --git a/ktlint-rule-engine/src/main/kotlin/com/pinterest/ktlint/rule/engine/internal/RuleExecutionContext.kt b/ktlint-rule-engine/src/main/kotlin/com/pinterest/ktlint/rule/engine/internal/RuleExecutionContext.kt\nindex a7dbd251ae..12d1cf10ab 100644\n--- a/ktlint-rule-engine/src/main/kotlin/com/pinterest/ktlint/rule/engine/internal/RuleExecutionContext.kt\n+++ b/ktlint-rule-engine/src/main/kotlin/com/pinterest/ktlint/rule/engine/internal/RuleExecutionContext.kt\n@@ -7,6 +7,7 @@ import com.pinterest.ktlint.rule.engine.api.KtLintRuleEngine\n import com.pinterest.ktlint.rule.engine.api.KtLintRuleEngine.Companion.UTF8_BOM\n import com.pinterest.ktlint.rule.engine.api.KtLintRuleException\n import com.pinterest.ktlint.rule.engine.core.api.Rule\n+import com.pinterest.ktlint.rule.engine.core.api.editorconfig.CODE_STYLE_PROPERTY\n import com.pinterest.ktlint.rule.engine.core.api.editorconfig.EditorConfig\n import com.pinterest.ktlint.rule.engine.internal.rulefilter.RuleExecutionRuleFilter\n import com.pinterest.ktlint.rule.engine.internal.rulefilter.RunAfterRuleFilter\n@@ -52,7 +53,9 @@ internal class RuleExecutionContext private constructor(\n // The rule get access to an EditConfig which is filtered by the properties which are actually registered as being used by\n // the rule. In this way it can be forced that the rule actually registers the properties that it uses and the field becomes\n // reliable to be used by for example the \".editorconfig\" file generator.\n- editorConfig.filterBy(rule.usesEditorConfigProperties),\n+ // Note that also the CODE_STYLE_PROPERTY is provided because that property is needed to determine the default value of an\n+ // EditorConfigProperty that is not explicitly defined.\n+ editorConfig.filterBy(rule.usesEditorConfigProperties.plus(CODE_STYLE_PROPERTY)),\n )\n this.executeRuleOnNodeRecursively(rootNode, rule, fqRuleId, autoCorrect, emit)\n rule.afterLastNode()\ndiff --git a/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/IndentationRule.kt b/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/IndentationRule.kt\nindex 3694bedae5..2b2d53b9b8 100644\n--- a/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/IndentationRule.kt\n+++ b/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/IndentationRule.kt\n@@ -113,7 +113,8 @@ import org.jetbrains.kotlin.com.intellij.psi.impl.source.tree.LeafPsiElement\n import org.jetbrains.kotlin.psi.KtStringTemplateExpression\n import org.jetbrains.kotlin.psi.psiUtil.leaves\n import org.jetbrains.kotlin.psi.psiUtil.parents\n-import java.util.*\n+import java.util.Deque\n+import java.util.LinkedList\n \n private val LOGGER = KotlinLogging.logger {}.initKtLintKLogger()\n \ndiff --git a/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/NoWildcardImportsRule.kt b/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/NoWildcardImportsRule.kt\nindex 66cead1556..d7907a3249 100644\n--- a/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/NoWildcardImportsRule.kt\n+++ b/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/NoWildcardImportsRule.kt\n@@ -93,7 +93,14 @@ public class NoWildcardImportsRule :\n * https://github.com/JetBrains/kotlin/blob/ffdab473e28d0d872136b910eb2e0f4beea2e19c/idea/formatter/src/org/jetbrains/kotlin/idea/core/formatter/KotlinCodeStyleSettings.java#L81-L82\n */\n defaultValue = parseAllowedWildcardImports(\"java.util.*,kotlinx.android.synthetic.**\"),\n- propertyWriter = { it.joinToString(separator = \",\") },\n+ propertyWriter = {\n+ if (it.isEmpty()) {\n+ \"unset\"\n+ } else {\n+ it.joinToString(separator = \",\")\n+ }\n+ },\n+ ktlintOfficialCodeStyleDefaultValue = emptyList(),\n )\n }\n }\n", "test_patch": "diff --git a/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/NoWildcardImportsRuleTest.kt b/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/NoWildcardImportsRuleTest.kt\nindex 5895de3515..f87600faf3 100644\n--- a/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/NoWildcardImportsRuleTest.kt\n+++ b/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/NoWildcardImportsRuleTest.kt\n@@ -1,5 +1,7 @@\n package com.pinterest.ktlint.ruleset.standard.rules\n \n+import com.pinterest.ktlint.rule.engine.core.api.editorconfig.CODE_STYLE_PROPERTY\n+import com.pinterest.ktlint.rule.engine.core.api.editorconfig.CodeStyleValue\n import com.pinterest.ktlint.ruleset.standard.rules.NoWildcardImportsRule.Companion.IJ_KOTLIN_PACKAGES_TO_USE_IMPORT_ON_DEMAND\n import com.pinterest.ktlint.test.KtLintAssertThat.Companion.assertThatRule\n import com.pinterest.ktlint.test.LintViolation\n@@ -98,4 +100,19 @@ class NoWildcardImportsRuleTest {\n .hasLintViolationWithoutAutoCorrect(2, 1, \"Wildcard import\")\n }\n }\n+\n+ @Test\n+ fun `Given the ktlint_official codestyle then the default wildcard imports allowed in other code styles are no longer allowed`() {\n+ val code =\n+ \"\"\"\n+ import java.util.*\n+ import kotlinx.android.synthetic.*\n+ \"\"\".trimIndent()\n+ noWildcardImportsRuleAssertThat(code)\n+ .withEditorConfigOverride(CODE_STYLE_PROPERTY to CodeStyleValue.ktlint_official)\n+ .hasLintViolationsWithoutAutoCorrect(\n+ LintViolation(1, 1, \"Wildcard import\"),\n+ LintViolation(2, 1, \"Wildcard import\"),\n+ )\n+ }\n }\n", "problem_statement": "Remove default for allowed wildcard imports in `ktlint_official` codestyle\n>Expected Behavior\r\n> When java.util.* is included as a wildcard import, it should trigger the warning for no-wildcard-imports.\r\n> ...\r\n> Given that, I think it makes sense that ktlint should stop including those two paths as default wildcard exceptions.\r\n\r\n_Originally posted by @greg-patterson in https://github.com/pinterest/ktlint/issues/1792#issuecomment-1407098815_\r\n \n", "hints_text": "The feature to respect setting ij_kotlin_packages_to_use_import_on_demand was implemented not too long ago in ktlint 0.45.x via https://github.com/pinterest/ktlint/pull/1272. The reason for adding the default values is that they seems to be hard-coded in IntelliJ IDEA as well (https://github.com/JetBrains/kotlin/blob/ffdab473e28d0d872136b910eb2e0f4beea2e19c/idea/formatter/src/org/jetbrains/kotlin/idea/core/formatter/KotlinCodeStyleSettings.java#L81-L82).\r\n\r\nIf the property is not set explicitly, IntelliJ IDEA allows imports java.util.* and kotlinx.android.synthetic.*. If ktlint would not do the same, this would result in a conclict between ktlint and IntelliJ IDEA. Lots of users of ktlint dislike that.\r\n\r\nIn the new codestyle `ktlint_official` the default value for allowed wildcard imports shoulbe be cleared.", "created_at": "2023-03-12T14:21:10Z", "version": "0.49", "FAIL_TO_PASS": [ "gradle_test_execution" ], "PASS_TO_PASS": [], "ERROR_TO_PASS": [], "environment_setup_commit": "410d8849874f4d3600f9d4572e0850adccce4f2d" }, { "repo": "pinterest/ktlint", "pull_number": 1849, "instance_id": "pinterest__ktlint-1849", "issue_numbers": [ "1725" ], "base_commit": "12b6eda3a7fc0d04dc4901ada371438bb99346b1", "patch": "diff --git a/CHANGELOG.md b/CHANGELOG.md\nindex dc027c13b9..d8b697c3f7 100644\n--- a/CHANGELOG.md\n+++ b/CHANGELOG.md\n@@ -246,6 +246,7 @@ Previously the default value for `.editorconfig` property `max_line_length` was\n * When generating the `.editorconfig` use value `off` for the `max_line_length` property instead of value `-1` to denote that lines are not restricted to a maximum length ([#1824](https://github.com/pinterest/ktlint/issues/1824))\n * Do not report an \"unnecessary semicolon\" after adding a trailing comma to an enum class containing a code element after the last enum entry `trailing-comma-on-declaration-site` ([#1786](https://github.com/pinterest/ktlint/issues/1786))\n * A newline before a function return type should not be removed in case that leads to exceeding the maximum line length `function-return-type-spacing` ([#1764](https://github.com/pinterest/ktlint/issues/1764))\n+* Wrap annotations on type arguments in same way as with other constructs `annotation`, `wrapping` ([#1725](https://github.com/pinterest/ktlint/issues/1725))\n \n ### Changed\n * Wrap the parameters of a function literal containing a multiline parameter list (only in `ktlint_official` code style) `parameter-list-wrapping` ([#1681](https://github.com/pinterest/ktlint/issues/1681)).\ndiff --git a/docs/faq.md b/docs/faq.md\nindex 656a312223..19e08e6473 100644\n--- a/docs/faq.md\n+++ b/docs/faq.md\n@@ -105,7 +105,9 @@ val foo = \"some really looooooooooooooooong string exceeding the max line length\n Like with other `@Suppress` annotations, it can be placed on targets supported by the annotation. As of this it is possible to disable rules in the entire file with:\n ```kotlin\n @file:Suppress(\"ktlint\") // Suppressing all rules for the entire file\n-// or\n+```\n+or\n+```\n @file:Suppress(\"ktlint:max-line-length\", \"ktlint:some-custom-rule-set-id:some-custom-rule-id\") // Suppressing specific rules for the entire file\n ```\n \ndiff --git a/ktlint-rule-engine-core/src/main/kotlin/com/pinterest/ktlint/rule/engine/core/api/ASTNodeExtension.kt b/ktlint-rule-engine-core/src/main/kotlin/com/pinterest/ktlint/rule/engine/core/api/ASTNodeExtension.kt\nindex 83cf46cf4b..ecbce9d9ff 100644\n--- a/ktlint-rule-engine-core/src/main/kotlin/com/pinterest/ktlint/rule/engine/core/api/ASTNodeExtension.kt\n+++ b/ktlint-rule-engine-core/src/main/kotlin/com/pinterest/ktlint/rule/engine/core/api/ASTNodeExtension.kt\n@@ -14,6 +14,8 @@ import org.jetbrains.kotlin.com.intellij.psi.impl.source.tree.LeafElement\n import org.jetbrains.kotlin.com.intellij.psi.impl.source.tree.PsiWhiteSpaceImpl\n import org.jetbrains.kotlin.com.intellij.psi.tree.IElementType\n import org.jetbrains.kotlin.psi.psiUtil.leaves\n+import org.jetbrains.kotlin.util.prefixIfNot\n+import org.jetbrains.kotlin.utils.addToStdlib.applyIf\n import kotlin.reflect.KClass\n \n public fun ASTNode.nextLeaf(\n@@ -296,6 +298,11 @@ public val ASTNode.column: Int\n return offsetToTheLeft + 1\n }\n \n+@Deprecated(\n+ message = \"Marked for removal in Ktlint 0.50. Replace with 'indent' but do note that it automatically includes a newline character \" +\n+ \"as prefix.\",\n+ replaceWith = ReplaceWith(\"indent\"),\n+)\n public fun ASTNode.lineIndent(): String {\n var leaf = this.prevLeaf()\n while (leaf != null) {\n@@ -307,6 +314,17 @@ public fun ASTNode.lineIndent(): String {\n return \"\"\n }\n \n+/**\n+ * Get the current indentation of the line containing the [ASTNode]. By default, this indentation starts with a newline (\\n) character.\n+ */\n+public fun ASTNode.indent(includeNewline: Boolean = true): String =\n+ leaves(forward = false)\n+ .firstOrNull { it.isWhiteSpaceWithNewline() }\n+ ?.text\n+ ?.substringAfterLast('\\n')\n+ .orEmpty() // Fallback if node is not preceded by any newline character\n+ .applyIf(includeNewline) { prefixIfNot(\"\\n\") }\n+\n /**\n * Print content of a node and the element type of the node, its parent and its direct children. Utility is meant to\n * be used during development only. Please do not remove.\ndiff --git a/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/AnnotationRule.kt b/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/AnnotationRule.kt\nindex 0530f0d2d5..7d5e6ef1bd 100644\n--- a/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/AnnotationRule.kt\n+++ b/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/AnnotationRule.kt\n@@ -1,19 +1,27 @@\n package com.pinterest.ktlint.ruleset.standard.rules\n \n+import com.pinterest.ktlint.rule.engine.core.api.ElementType\n import com.pinterest.ktlint.rule.engine.core.api.ElementType.ANNOTATED_EXPRESSION\n import com.pinterest.ktlint.rule.engine.core.api.ElementType.ANNOTATION\n import com.pinterest.ktlint.rule.engine.core.api.ElementType.ANNOTATION_ENTRY\n import com.pinterest.ktlint.rule.engine.core.api.ElementType.FILE_ANNOTATION_LIST\n+import com.pinterest.ktlint.rule.engine.core.api.ElementType.MODIFIER_LIST\n import com.pinterest.ktlint.rule.engine.core.api.ElementType.TYPE_ARGUMENT_LIST\n+import com.pinterest.ktlint.rule.engine.core.api.ElementType.TYPE_PROJECTION\n+import com.pinterest.ktlint.rule.engine.core.api.ElementType.TYPE_REFERENCE\n import com.pinterest.ktlint.rule.engine.core.api.ElementType.VALUE_ARGUMENT\n import com.pinterest.ktlint.rule.engine.core.api.ElementType.VALUE_ARGUMENT_LIST\n import com.pinterest.ktlint.rule.engine.core.api.ElementType.VALUE_PARAMETER\n import com.pinterest.ktlint.rule.engine.core.api.ElementType.WHITE_SPACE\n+import com.pinterest.ktlint.rule.engine.core.api.IndentConfig\n import com.pinterest.ktlint.rule.engine.core.api.RuleId\n import com.pinterest.ktlint.rule.engine.core.api.children\n+import com.pinterest.ktlint.rule.engine.core.api.editorconfig.EditorConfig\n+import com.pinterest.ktlint.rule.engine.core.api.editorconfig.INDENT_SIZE_PROPERTY\n+import com.pinterest.ktlint.rule.engine.core.api.editorconfig.INDENT_STYLE_PROPERTY\n import com.pinterest.ktlint.rule.engine.core.api.firstChildLeafOrSelf\n+import com.pinterest.ktlint.rule.engine.core.api.isCodeLeaf\n import com.pinterest.ktlint.rule.engine.core.api.isPartOf\n-import com.pinterest.ktlint.rule.engine.core.api.isPartOfComment\n import com.pinterest.ktlint.rule.engine.core.api.isWhiteSpace\n import com.pinterest.ktlint.rule.engine.core.api.isWhiteSpaceWithNewline\n import com.pinterest.ktlint.rule.engine.core.api.lastChildLeafOrSelf\n@@ -31,17 +39,57 @@ import org.jetbrains.kotlin.descriptors.annotations.AnnotationUseSiteTarget\n import org.jetbrains.kotlin.psi.KtAnnotationEntry\n import org.jetbrains.kotlin.psi.psiUtil.leaves\n import org.jetbrains.kotlin.psi.psiUtil.siblings\n+import org.jetbrains.kotlin.utils.addToStdlib.applyIf\n import org.jetbrains.kotlin.utils.addToStdlib.safeAs\n \n /**\n- * Ensures multiple annotations are not on the same line as the annotated declaration. Also ensures that annotations\n- * with parameters are placed on separate lines.\n+ * Ensures that annotation are wrapped to separate lines.\n *\n * https://kotlinlang.org/docs/reference/coding-conventions.html#annotation-formatting\n *\n- * @see [AnnotationSpacingRule] for white space rules. Moved since\n+ * 1) Place annotations on separate lines before the declaration to which they are attached, and with the same indentation:\n+ *\n+ * ```\n+ * @Target(AnnotationTarget.PROPERTY)\n+ * annotation class JsonExclude\n+ * ```\n+ *\n+ * 2) Annotations without arguments may be placed on the same line:\n+ *\n+ * ```\n+ * @JsonExclude @JvmField\n+ * var x: String\n+ * ```\n+ *\n+ * 3) A single annotation without arguments may be placed on the same line as the corresponding declaration:\n+ *\n+ * ```\n+ * @Test fun foo() { /*...*/ }\n+ * ```\n+ *\n+ * 4) File annotations are placed after the file comment (if any), before the package statement, and are separated from package with a blank\n+ * line (to emphasize the fact that they target the file and not the package).\n+ *\n+ * @see [AnnotationSpacingRule] for white space rules.\n */\n-public class AnnotationRule : StandardRule(\"annotation\") {\n+public class AnnotationRule :\n+ StandardRule(\n+ id = \"annotation\",\n+ usesEditorConfigProperties = setOf(\n+ INDENT_SIZE_PROPERTY,\n+ INDENT_STYLE_PROPERTY,\n+ ),\n+ ) {\n+ private var indentConfig = IndentConfig.DEFAULT_INDENT_CONFIG\n+\n+ override fun beforeFirstNode(editorConfig: EditorConfig) {\n+ indentConfig = IndentConfig(\n+ indentStyle = editorConfig[INDENT_STYLE_PROPERTY],\n+ tabWidth = editorConfig[INDENT_SIZE_PROPERTY],\n+ )\n+ Unit\n+ }\n+\n override fun beforeVisitChildNodes(\n node: ASTNode,\n autoCorrect: Boolean,\n@@ -52,10 +100,13 @@ public class AnnotationRule : StandardRule(\"annotation\") {\n visitFileAnnotationList(node, emit, autoCorrect)\n }\n ANNOTATION -> {\n+ // Annotation array\n+ // @[...]\n visitAnnotation(node, emit, autoCorrect)\n }\n- ANNOTATION_ENTRY ->\n+ ANNOTATION_ENTRY -> {\n visitAnnotationEntry(node, emit, autoCorrect)\n+ }\n }\n }\n \n@@ -75,20 +126,125 @@ public class AnnotationRule : StandardRule(\"annotation\") {\n checkForAnnotationWithParameterToBePlacedOnSeparateLine(node, emit, autoCorrect)\n }\n \n- if ((node.isFollowedByOtherAnnotationEntry() && node.isOnSameLineAsNextAnnotationEntry()) ||\n- (node.isPrecededByOtherAnnotationEntry() && node.isOnSameLineAsAnnotatedConstruct())\n- ) {\n- checkForAnnotationToBePlacedOnSeparateLine(node, emit, autoCorrect)\n+ if (node.isOnSameLineAsAnnotatedConstruct()) {\n+ if (node.isPrecededByAnnotationOnAnotherLine()) {\n+ // Code below is disallowed\n+ // @Foo1\n+ // @Foo2 fun foo() {}\n+ emit(\n+ node.startOffset,\n+ \"Annotation must be placed on a separate line when it is preceded by another annotation on a separate line\",\n+ true,\n+ )\n+ if (autoCorrect) {\n+ node\n+ .lastChildLeafOrSelf()\n+ .nextLeaf()\n+ ?.upsertWhitespaceBeforeMe(getNewlineWithIndent(node.treeParent))\n+ }\n+ }\n+\n+ if (node.treeParent.elementType != ANNOTATION &&\n+ node.isPrecededByOtherAnnotationEntryOnTheSameLine() &&\n+ node.isLastAnnotationEntry()\n+ ) {\n+ // Code below is disallowed\n+ // @Foo1 @Foo2 fun foo() {}\n+ // But following is allowed:\n+ // @[Foo1 Foo2] fun foo() {}\n+ emit(\n+ node.findAnnotatedConstruct().startOffset,\n+ \"Multiple annotations should not be placed on the same line as the annotated construct\",\n+ true,\n+ )\n+ if (autoCorrect) {\n+ node\n+ .lastChildLeafOrSelf()\n+ .nextCodeLeaf()\n+ ?.upsertWhitespaceBeforeMe(\n+ getNewlineWithIndent(node.treeParent)\n+ .applyIf(node.typeProjectionOrNull() != null) {\n+ plus(indentConfig.indent)\n+ },\n+ )\n+ }\n+ }\n+\n+ node\n+ .typeProjectionOrNull()\n+ ?.let { typeProjection ->\n+ // Code below is disallowed\n+ // var foo: List<@Foo1 @Foo2 String>\n+ // But following is allowed:\n+ // var foo: List<@[Foo1 Foo2] String>\n+ if (node.isFollowedByOtherAnnotationEntryOnTheSameLine() &&\n+ node.isFirstAnnotationEntry()\n+ ) {\n+ emit(\n+ typeProjection.startOffset,\n+ \"Annotations on a type reference should be placed on a separate line\",\n+ true,\n+ )\n+ if (autoCorrect) {\n+ typeProjection\n+ .upsertWhitespaceBeforeMe(\n+ getNewlineWithIndent(node.treeParent).plus(indentConfig.indent),\n+ )\n+ }\n+ }\n+ if (node.isPrecededByOtherAnnotationEntryOnTheSameLine() &&\n+ node.isLastAnnotationEntry()\n+ ) {\n+ val annotatedConstruct = node.findAnnotatedConstruct()\n+ emit(\n+ annotatedConstruct.startOffset,\n+ \"Annotations on a type reference should be placed on a separate line\",\n+ true,\n+ )\n+ if (autoCorrect) {\n+ annotatedConstruct\n+ .nextLeaf { it.isCodeLeaf() && it.elementType != ElementType.COMMA }!!\n+ .firstChildLeafOrSelf()\n+ .upsertWhitespaceBeforeMe(getNewlineWithIndent(node.treeParent))\n+ }\n+ }\n+ }\n }\n \n- if (node.treeParent.elementType != ANNOTATION &&\n- node.isPrecededByOtherAnnotationEntry() &&\n- node.isOnSameLineAsAnnotatedConstruct()\n- ) {\n- checkForMultipleAnnotationsOnSameLineAsAnnotatedConstruct(node, emit, autoCorrect)\n+ if (node.isPrecededByOtherAnnotationEntryOnTheSameLine() && node.isPrecededByAnnotationOnAnotherLine()) {\n+ // Code below is disallowed\n+ // @Foo1\n+ // @Foo2 @Foo3\n+ // fun foo() {}\n+ emit(\n+ node.startOffset,\n+ \"All annotations should either be on a single line or all annotations should be on a separate line\",\n+ true,\n+ )\n+ if (autoCorrect) {\n+ node\n+ .firstChildLeafOrSelf()\n+ .upsertWhitespaceBeforeMe(getNewlineWithIndent(node.treeParent))\n+ }\n }\n }\n \n+ private fun ASTNode.typeProjectionOrNull() =\n+ takeIf { elementType == ANNOTATION_ENTRY }\n+ ?.takeIf { it.treeParent.elementType == MODIFIER_LIST }\n+ ?.treeParent\n+ ?.takeIf { it.treeParent.elementType == TYPE_REFERENCE }\n+ ?.treeParent\n+ ?.takeIf { it.treeParent.elementType == TYPE_PROJECTION }\n+ ?.treeParent\n+\n+ private fun ASTNode.isPrecededByAnnotationOnAnotherLine(): Boolean {\n+ val firstAnnotation = treeParent.findChildByType(ANNOTATION_ENTRY)\n+ return siblings(forward = false)\n+ .takeWhile { it != firstAnnotation }\n+ .any { it.isWhiteSpaceWithNewline() }\n+ }\n+\n private fun checkForAnnotationWithParameterToBePlacedOnSeparateLine(\n node: ASTNode,\n emit: (offset: Int, errorMessage: String, canBeAutoCorrected: Boolean) -> Unit,\n@@ -135,60 +291,6 @@ public class AnnotationRule : StandardRule(\"annotation\") {\n }\n }\n \n- private fun checkForMultipleAnnotationsOnSameLineAsAnnotatedConstruct(\n- node: ASTNode,\n- emit: (offset: Int, errorMessage: String, canBeAutoCorrected: Boolean) -> Unit,\n- autoCorrect: Boolean,\n- ) {\n- if (node.isLastAnnotationEntry()) {\n- val noAnnotationWithParameters =\n- node\n- .siblings(forward = false)\n- .none { it.isAnnotationEntryWithValueArgumentList() }\n- if (noAnnotationWithParameters) {\n- emit(\n- node.treeParent.startOffset,\n- \"Multiple annotations should not be placed on the same line as the annotated construct\",\n- true,\n- )\n- if (autoCorrect) {\n- node\n- .lastChildLeafOrSelf()\n- .nextCodeLeaf()\n- ?.upsertWhitespaceBeforeMe(getNewlineWithIndent(node.treeParent))\n- }\n- }\n- }\n- }\n-\n- private fun checkForAnnotationToBePlacedOnSeparateLine(\n- node: ASTNode,\n- emit: (offset: Int, errorMessage: String, canBeAutoCorrected: Boolean) -> Unit,\n- autoCorrect: Boolean,\n- ) {\n- val isFollowedWithAnnotationHavingValueArgumentList =\n- node\n- .siblings(forward = true)\n- .any { it.isAnnotationEntryWithValueArgumentList() }\n- val isPrecededWithAnnotationOnOtherLine =\n- node\n- .siblings(forward = false)\n- .any { it.isWhiteSpaceWithNewline() }\n- if (isFollowedWithAnnotationHavingValueArgumentList || isPrecededWithAnnotationOnOtherLine) {\n- emit(\n- node.startOffset,\n- \"Annotation must be placed on separate line\",\n- true,\n- )\n- if (autoCorrect) {\n- node\n- .lastChildLeafOrSelf()\n- .nextLeaf()\n- ?.upsertWhitespaceBeforeMe(getNewlineWithIndent(node.treeParent))\n- }\n- }\n- }\n-\n private fun ASTNode.isNotReceiverTargetAnnotation() = getAnnotationUseSiteTarget() != AnnotationUseSiteTarget.RECEIVER\n \n private fun ASTNode.getAnnotationUseSiteTarget() =\n@@ -203,13 +305,31 @@ public class AnnotationRule : StandardRule(\"annotation\") {\n takeIf { it.elementType == ANNOTATION_ENTRY }\n ?.findChildByType(VALUE_ARGUMENT_LIST)\n \n+ private fun ASTNode.isFirstAnnotationEntry() =\n+ this ==\n+ treeParent\n+ .children()\n+ .firstOrNull { it.elementType == ANNOTATION_ENTRY }\n+\n private fun ASTNode.isLastAnnotationEntry() =\n- treeParent\n- .children()\n- .lastOrNull { it.elementType == ANNOTATION_ENTRY }\n- .let { it == this }\n+ this ==\n+ treeParent\n+ .children()\n+ .lastOrNull { it.elementType == ANNOTATION_ENTRY }\n+\n+ private fun ASTNode.isPrecededByOtherAnnotationEntryOnTheSameLine() =\n+ siblings(forward = false)\n+ .takeWhile { !it.isWhiteSpaceWithNewline() }\n+ .any { it.elementType == ANNOTATION_ENTRY }\n+\n+ private fun ASTNode.isFollowedByOtherAnnotationEntryOnTheSameLine() =\n+ siblings()\n+ .takeWhile { !it.isWhiteSpaceWithNewline() }\n+ .any { it.elementType == ANNOTATION_ENTRY }\n \n- private fun ASTNode.isPrecededByOtherAnnotationEntry() = siblings(forward = false).any { it.elementType == ANNOTATION_ENTRY }\n+ private fun ASTNode.isPrecededByOtherAnnotationEntry() =\n+ siblings(forward = false)\n+ .any { it.elementType == ANNOTATION_ENTRY }\n \n private fun ASTNode.isOnSameLineAsPreviousAnnotationEntry() =\n siblings(forward = false)\n@@ -223,11 +343,25 @@ public class AnnotationRule : StandardRule(\"annotation\") {\n .takeWhile { it.elementType != ANNOTATION_ENTRY }\n .none { it.isWhiteSpaceWithNewline() }\n \n- private fun ASTNode.isOnSameLineAsAnnotatedConstruct() =\n- lastChildLeafOrSelf()\n+ private fun ASTNode.isOnSameLineAsAnnotatedConstruct(): Boolean {\n+ val annotatedConstruct = findAnnotatedConstruct()\n+ return lastChildLeafOrSelf()\n .leaves(forward = true)\n- .takeWhile { it.isWhiteSpace() || it.isPartOfComment() }\n+ .takeWhile { it != annotatedConstruct }\n .none { it.isWhiteSpaceWithNewline() }\n+ }\n+\n+ private fun ASTNode.findAnnotatedConstruct(): ASTNode {\n+ val astNode = if (treeParent.elementType == MODIFIER_LIST) {\n+ treeParent\n+ } else {\n+ this\n+ }\n+\n+ return checkNotNull(\n+ astNode.lastChildLeafOrSelf().nextCodeLeaf(),\n+ )\n+ }\n \n private fun ASTNode.isOnSameLineAsNextAnnotationEntryOrAnnotatedConstruct() =\n if (isFollowedByOtherAnnotationEntry()) {\ndiff --git a/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/ArgumentListWrappingRule.kt b/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/ArgumentListWrappingRule.kt\nindex 610199928f..223796aab7 100644\n--- a/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/ArgumentListWrappingRule.kt\n+++ b/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/ArgumentListWrappingRule.kt\n@@ -11,10 +11,10 @@ import com.pinterest.ktlint.rule.engine.core.api.editorconfig.EditorConfig\n import com.pinterest.ktlint.rule.engine.core.api.editorconfig.INDENT_SIZE_PROPERTY\n import com.pinterest.ktlint.rule.engine.core.api.editorconfig.INDENT_STYLE_PROPERTY\n import com.pinterest.ktlint.rule.engine.core.api.editorconfig.MAX_LINE_LENGTH_PROPERTY\n+import com.pinterest.ktlint.rule.engine.core.api.indent\n import com.pinterest.ktlint.rule.engine.core.api.isPartOfComment\n import com.pinterest.ktlint.rule.engine.core.api.isWhiteSpace\n import com.pinterest.ktlint.rule.engine.core.api.isWhiteSpaceWithNewline\n-import com.pinterest.ktlint.rule.engine.core.api.lineIndent\n import com.pinterest.ktlint.rule.engine.core.api.prevLeaf\n import com.pinterest.ktlint.ruleset.standard.StandardRule\n import org.jetbrains.kotlin.com.intellij.lang.ASTNode\n@@ -105,7 +105,7 @@ public class ArgumentListWrappingRule :\n private fun ASTNode.exceedsMaxLineLength() = (column - 1 + textLength) > maxLineLength && !textContains('\\n')\n \n private fun ASTNode.getNewIndentLevel(): Int {\n- val currentIndentLevel = editorConfigIndent.indentLevelFrom(lineIndent())\n+ val currentIndentLevel = editorConfigIndent.indentLevelFrom(indent(false))\n return when {\n // IDEA quirk:\n // generic<\ndiff --git a/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/BlockCommentInitialStarAlignmentRule.kt b/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/BlockCommentInitialStarAlignmentRule.kt\nindex 56d053200c..34c4a1f463 100644\n--- a/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/BlockCommentInitialStarAlignmentRule.kt\n+++ b/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/BlockCommentInitialStarAlignmentRule.kt\n@@ -4,7 +4,7 @@ import com.pinterest.ktlint.rule.engine.core.api.ElementType.BLOCK_COMMENT\n import com.pinterest.ktlint.rule.engine.core.api.Rule\n import com.pinterest.ktlint.rule.engine.core.api.Rule.VisitorModifier.RunAfterRule.Mode.REGARDLESS_WHETHER_RUN_AFTER_RULE_IS_LOADED_OR_DISABLED\n import com.pinterest.ktlint.rule.engine.core.api.RuleId\n-import com.pinterest.ktlint.rule.engine.core.api.lineIndent\n+import com.pinterest.ktlint.rule.engine.core.api.indent\n import com.pinterest.ktlint.ruleset.standard.StandardRule\n import org.jetbrains.kotlin.com.intellij.lang.ASTNode\n import org.jetbrains.kotlin.com.intellij.psi.impl.source.tree.LeafElement\n@@ -32,7 +32,7 @@ public class BlockCommentInitialStarAlignmentRule :\n emit: (offset: Int, errorMessage: String, canBeAutoCorrected: Boolean) -> Unit,\n ) {\n if (node.elementType == BLOCK_COMMENT) {\n- val expectedIndentForLineWithInitialStar = node.lineIndent() + \" *\"\n+ val expectedIndentForLineWithInitialStar = node.indent(false) + \" *\"\n val lines = node.text.split(\"\\n\")\n var offset = node.startOffset\n val modifiedLines = mutableListOf()\ndiff --git a/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/ChainWrappingRule.kt b/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/ChainWrappingRule.kt\nindex 5e026a90f6..fcd03f03e9 100644\n--- a/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/ChainWrappingRule.kt\n+++ b/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/ChainWrappingRule.kt\n@@ -17,14 +17,15 @@ import com.pinterest.ktlint.rule.engine.core.api.ElementType.PREFIX_EXPRESSION\n import com.pinterest.ktlint.rule.engine.core.api.ElementType.SAFE_ACCESS\n import com.pinterest.ktlint.rule.engine.core.api.ElementType.WHITE_SPACE\n import com.pinterest.ktlint.rule.engine.core.api.IndentConfig\n+import com.pinterest.ktlint.rule.engine.core.api.IndentConfig.Companion.DEFAULT_INDENT_CONFIG\n import com.pinterest.ktlint.rule.engine.core.api.RuleId\n import com.pinterest.ktlint.rule.engine.core.api.editorconfig.EditorConfig\n import com.pinterest.ktlint.rule.engine.core.api.editorconfig.INDENT_SIZE_PROPERTY\n import com.pinterest.ktlint.rule.engine.core.api.editorconfig.INDENT_STYLE_PROPERTY\n+import com.pinterest.ktlint.rule.engine.core.api.indent\n import com.pinterest.ktlint.rule.engine.core.api.isPartOfComment\n import com.pinterest.ktlint.rule.engine.core.api.isWhiteSpaceWithNewline\n import com.pinterest.ktlint.rule.engine.core.api.isWhiteSpaceWithoutNewline\n-import com.pinterest.ktlint.rule.engine.core.api.lineIndent\n import com.pinterest.ktlint.rule.engine.core.api.nextCodeLeaf\n import com.pinterest.ktlint.rule.engine.core.api.nextLeaf\n import com.pinterest.ktlint.rule.engine.core.api.prevCodeLeaf\n@@ -48,18 +49,17 @@ public class ChainWrappingRule :\n INDENT_STYLE_PROPERTY,\n ),\n ) {\n- private var indent: String? = null\n private val sameLineTokens = TokenSet.create(MUL, DIV, PERC, ANDAND, OROR)\n private val prefixTokens = TokenSet.create(PLUS, MINUS)\n private val nextLineTokens = TokenSet.create(DOT, SAFE_ACCESS, ELVIS)\n private val noSpaceAroundTokens = TokenSet.create(DOT, SAFE_ACCESS)\n+ private var indentConfig = DEFAULT_INDENT_CONFIG\n \n override fun beforeFirstNode(editorConfig: EditorConfig) {\n- val indentConfig = IndentConfig(\n+ indentConfig = IndentConfig(\n indentStyle = editorConfig[INDENT_STYLE_PROPERTY],\n tabWidth = editorConfig[INDENT_SIZE_PROPERTY],\n )\n- indent = indentConfig.indent\n }\n \n override fun beforeVisitChildNodes(\n@@ -88,7 +88,7 @@ public class ChainWrappingRule :\n // to\n // \n if (node.elementType == ELVIS) {\n- node.upsertWhitespaceBeforeMe(\"\\n\" + node.lineIndent() + indent)\n+ node.upsertWhitespaceBeforeMe(node.indent().plus(indentConfig.indent))\n node.upsertWhitespaceAfterMe(\" \")\n } else {\n node.treeParent.removeChild(node)\ndiff --git a/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/CommentWrappingRule.kt b/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/CommentWrappingRule.kt\nindex 772257b883..31d0308815 100644\n--- a/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/CommentWrappingRule.kt\n+++ b/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/CommentWrappingRule.kt\n@@ -8,7 +8,7 @@ import com.pinterest.ktlint.rule.engine.core.api.RuleId\n import com.pinterest.ktlint.rule.engine.core.api.editorconfig.INDENT_SIZE_PROPERTY\n import com.pinterest.ktlint.rule.engine.core.api.editorconfig.INDENT_STYLE_PROPERTY\n import com.pinterest.ktlint.rule.engine.core.api.hasNewLineInClosedRange\n-import com.pinterest.ktlint.rule.engine.core.api.lineIndent\n+import com.pinterest.ktlint.rule.engine.core.api.indent\n import com.pinterest.ktlint.rule.engine.core.api.nextLeaf\n import com.pinterest.ktlint.rule.engine.core.api.prevLeaf\n import com.pinterest.ktlint.rule.engine.core.api.upsertWhitespaceBeforeMe\n@@ -118,7 +118,7 @@ public class CommentWrappingRule :\n ) {\n emit(startOffset, \"A block comment may not be followed by any other element on that same line\", true)\n if (autoCorrect) {\n- this.upsertWhitespaceBeforeMe(\"\\n${blockCommentNode.lineIndent()}\")\n+ this.upsertWhitespaceBeforeMe(blockCommentNode.indent())\n }\n }\n \ndiff --git a/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/ContextReceiverWrappingRule.kt b/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/ContextReceiverWrappingRule.kt\nindex 683849a67b..a68a2836cf 100644\n--- a/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/ContextReceiverWrappingRule.kt\n+++ b/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/ContextReceiverWrappingRule.kt\n@@ -7,6 +7,7 @@ import com.pinterest.ktlint.rule.engine.core.api.ElementType.RPAR\n import com.pinterest.ktlint.rule.engine.core.api.ElementType.TYPE_ARGUMENT_LIST\n import com.pinterest.ktlint.rule.engine.core.api.ElementType.TYPE_PROJECTION\n import com.pinterest.ktlint.rule.engine.core.api.IndentConfig\n+import com.pinterest.ktlint.rule.engine.core.api.IndentConfig.Companion.DEFAULT_INDENT_CONFIG\n import com.pinterest.ktlint.rule.engine.core.api.Rule\n import com.pinterest.ktlint.rule.engine.core.api.RuleId\n import com.pinterest.ktlint.rule.engine.core.api.children\n@@ -15,12 +16,12 @@ import com.pinterest.ktlint.rule.engine.core.api.editorconfig.INDENT_SIZE_PROPER\n import com.pinterest.ktlint.rule.engine.core.api.editorconfig.INDENT_STYLE_PROPERTY\n import com.pinterest.ktlint.rule.engine.core.api.editorconfig.MAX_LINE_LENGTH_PROPERTY\n import com.pinterest.ktlint.rule.engine.core.api.firstChildLeafOrSelf\n+import com.pinterest.ktlint.rule.engine.core.api.indent\n import com.pinterest.ktlint.rule.engine.core.api.isPartOf\n import com.pinterest.ktlint.rule.engine.core.api.isPartOfComment\n import com.pinterest.ktlint.rule.engine.core.api.isWhiteSpaceWithNewline\n import com.pinterest.ktlint.rule.engine.core.api.isWhiteSpaceWithoutNewline\n import com.pinterest.ktlint.rule.engine.core.api.lastChildLeafOrSelf\n-import com.pinterest.ktlint.rule.engine.core.api.lineIndent\n import com.pinterest.ktlint.rule.engine.core.api.nextLeaf\n import com.pinterest.ktlint.rule.engine.core.api.prevLeaf\n import com.pinterest.ktlint.rule.engine.core.api.upsertWhitespaceAfterMe\n@@ -42,15 +43,14 @@ public class ContextReceiverWrappingRule :\n ),\n ),\n Rule.Experimental {\n- private lateinit var indent: String\n+ private var indentConfig = DEFAULT_INDENT_CONFIG\n private var maxLineLength = MAX_LINE_LENGTH_PROPERTY.defaultValue\n \n override fun beforeFirstNode(editorConfig: EditorConfig) {\n- val indentConfig = IndentConfig(\n+ indentConfig = IndentConfig(\n indentStyle = editorConfig[INDENT_STYLE_PROPERTY],\n tabWidth = editorConfig[INDENT_SIZE_PROPERTY],\n )\n- indent = indentConfig.indent\n maxLineLength = editorConfig[MAX_LINE_LENGTH_PROPERTY]\n }\n \n@@ -82,14 +82,13 @@ public class ContextReceiverWrappingRule :\n if (autoCorrect) {\n nodeAfterContextReceiver\n .firstChildLeafOrSelf()\n- .upsertWhitespaceBeforeMe(\"\\n\" + node.treeParent.lineIndent())\n+ .upsertWhitespaceBeforeMe(node.treeParent.indent())\n }\n }\n \n- // Check line length assuming that the context receiver is indented correctly. Wrapping rule must however run\n- // before indenting.\n+ // Check line length assuming that the context receiver is indented correctly. Wrapping rule must however run before indenting.\n if (!node.textContains('\\n') &&\n- node.lineIndent().length + node.textLength > maxLineLength\n+ node.indent(false).length + node.textLength > maxLineLength\n ) {\n node\n .children()\n@@ -103,7 +102,7 @@ public class ContextReceiverWrappingRule :\n if (autoCorrect) {\n it\n .prevLeaf(includeEmpty = true)\n- ?.upsertWhitespaceAfterMe(\"\\n\" + node.lineIndent() + indent)\n+ ?.upsertWhitespaceAfterMe(node.indent().plus(indentConfig.indent))\n }\n }\n node\n@@ -115,7 +114,7 @@ public class ContextReceiverWrappingRule :\n true,\n )\n if (autoCorrect) {\n- rpar.upsertWhitespaceBeforeMe(\"\\n\" + node.lineIndent())\n+ rpar.upsertWhitespaceBeforeMe(node.indent())\n }\n }\n }\n@@ -130,7 +129,7 @@ public class ContextReceiverWrappingRule :\n // Check line length assuming that the context receiver is indented correctly. Wrapping rule must however run\n // before indenting.\n if (!contextReceiver.contains('\\n') &&\n- node.lineIndent().length + contextReceiver.length > maxLineLength\n+ node.indent(false).length + contextReceiver.length > maxLineLength\n ) {\n node\n .children()\n@@ -143,7 +142,7 @@ public class ContextReceiverWrappingRule :\n )\n if (autoCorrect) {\n it\n- .upsertWhitespaceBeforeMe(\"\\n\" + node.lineIndent() + indent)\n+ .upsertWhitespaceBeforeMe(node.indent().plus(indentConfig.indent))\n }\n }\n node\n@@ -158,7 +157,7 @@ public class ContextReceiverWrappingRule :\n // Ideally, the closing angle bracket should be de-indented to make it consistent with\n // de-intentation of closing \")\", \"}\" and \"]\". This however would be inconsistent with how the\n // type argument lists are formatted by IntelliJ IDEA default formatter.\n- gt.upsertWhitespaceBeforeMe(\"\\n\" + node.lineIndent() + indent)\n+ gt.upsertWhitespaceBeforeMe(node.indent().plus(indentConfig.indent))\n }\n }\n }\ndiff --git a/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/FunctionSignatureRule.kt b/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/FunctionSignatureRule.kt\nindex 63d87eedaf..aae0389bbc 100644\n--- a/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/FunctionSignatureRule.kt\n+++ b/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/FunctionSignatureRule.kt\n@@ -15,6 +15,7 @@ import com.pinterest.ktlint.rule.engine.core.api.ElementType.VALUE_PARAMETER\n import com.pinterest.ktlint.rule.engine.core.api.ElementType.VALUE_PARAMETER_LIST\n import com.pinterest.ktlint.rule.engine.core.api.ElementType.WHITE_SPACE\n import com.pinterest.ktlint.rule.engine.core.api.IndentConfig\n+import com.pinterest.ktlint.rule.engine.core.api.IndentConfig.Companion.DEFAULT_INDENT_CONFIG\n import com.pinterest.ktlint.rule.engine.core.api.Rule\n import com.pinterest.ktlint.rule.engine.core.api.RuleId\n import com.pinterest.ktlint.rule.engine.core.api.children\n@@ -24,9 +25,9 @@ import com.pinterest.ktlint.rule.engine.core.api.editorconfig.INDENT_SIZE_PROPER\n import com.pinterest.ktlint.rule.engine.core.api.editorconfig.INDENT_STYLE_PROPERTY\n import com.pinterest.ktlint.rule.engine.core.api.editorconfig.MAX_LINE_LENGTH_PROPERTY\n import com.pinterest.ktlint.rule.engine.core.api.editorconfig.MAX_LINE_LENGTH_PROPERTY_OFF\n+import com.pinterest.ktlint.rule.engine.core.api.indent\n import com.pinterest.ktlint.rule.engine.core.api.isWhiteSpace\n import com.pinterest.ktlint.rule.engine.core.api.isWhiteSpaceWithNewline\n-import com.pinterest.ktlint.rule.engine.core.api.lineIndent\n import com.pinterest.ktlint.rule.engine.core.api.nextCodeLeaf\n import com.pinterest.ktlint.rule.engine.core.api.nextCodeSibling\n import com.pinterest.ktlint.rule.engine.core.api.nextLeaf\n@@ -63,7 +64,7 @@ public class FunctionSignatureRule :\n ),\n ),\n Rule.Experimental {\n- private var indent: String? = null\n+ private var indentConfig = DEFAULT_INDENT_CONFIG\n private var maxLineLength = MAX_LINE_LENGTH_PROPERTY.defaultValue\n private var functionSignatureWrappingMinimumParameters =\n FORCE_MULTILINE_WHEN_PARAMETER_COUNT_GREATER_OR_EQUAL_THAN_PROPERTY.defaultValue\n@@ -74,11 +75,10 @@ public class FunctionSignatureRule :\n FORCE_MULTILINE_WHEN_PARAMETER_COUNT_GREATER_OR_EQUAL_THAN_PROPERTY,\n ]\n functionBodyExpressionWrapping = editorConfig[FUNCTION_BODY_EXPRESSION_WRAPPING_PROPERTY]\n- val indentConfig = IndentConfig(\n+ indentConfig = IndentConfig(\n indentStyle = editorConfig[INDENT_STYLE_PROPERTY],\n tabWidth = editorConfig[INDENT_SIZE_PROPERTY],\n )\n- indent = indentConfig.indent\n maxLineLength = editorConfig[MAX_LINE_LENGTH_PROPERTY]\n }\n \n@@ -206,7 +206,7 @@ public class FunctionSignatureRule :\n endASTNodePredicate = { false },\n )\n \n- return node.lineIndent().length +\n+ return node.indent(false).length +\n tailNodesOfFunctionSignature.sumOf { it.text.length }\n }\n \n@@ -234,7 +234,7 @@ public class FunctionSignatureRule :\n fixWhiteSpacesInValueParameterList(node, emit, autoCorrect, multiline = false, dryRun = true)\n }\n \n- private fun ASTNode.getFunctionSignatureLength() = lineIndent().length + getFunctionSignatureNodesLength()\n+ private fun ASTNode.getFunctionSignatureLength() = indent(false).length + getFunctionSignatureNodesLength()\n \n private fun ASTNode.getFunctionSignatureNodesLength() =\n functionSignatureNodes()\n@@ -326,7 +326,7 @@ public class FunctionSignatureRule :\n ?.takeIf { it.elementType == WHITE_SPACE }\n .let { whiteSpaceBeforeIdentifier ->\n if (multiline) {\n- val expectedParameterIndent = \"\\n\" + node.lineIndent() + indent\n+ val expectedParameterIndent = node.indent().plus(indentConfig.indent)\n if (whiteSpaceBeforeIdentifier == null ||\n whiteSpaceBeforeIdentifier.text != expectedParameterIndent\n ) {\n@@ -390,7 +390,7 @@ public class FunctionSignatureRule :\n ?.takeIf { it.elementType == WHITE_SPACE }\n .let { whiteSpaceBeforeIdentifier ->\n if (multiline) {\n- val expectedParameterIndent = \"\\n\" + node.lineIndent() + indent\n+ val expectedParameterIndent = node.indent().plus(indentConfig.indent)\n if (whiteSpaceBeforeIdentifier == null ||\n whiteSpaceBeforeIdentifier.text != expectedParameterIndent\n ) {\n@@ -438,7 +438,7 @@ public class FunctionSignatureRule :\n ): Int {\n var whiteSpaceCorrection = 0\n \n- val newlineAndIndent = \"\\n\" + node.lineIndent()\n+ val newlineAndIndent = node.indent()\n val valueParameterList = requireNotNull(node.findChildByType(VALUE_PARAMETER_LIST))\n \n val closingParenthesis = valueParameterList.findChildByType(RPAR)\n@@ -572,7 +572,7 @@ public class FunctionSignatureRule :\n if (autoCorrect) {\n functionBodyExpressionNodes\n .first()\n- .upsertWhitespaceBeforeMe(\"\\n\" + node.lineIndent() + indent)\n+ .upsertWhitespaceBeforeMe(node.indent().plus(indentConfig.indent))\n }\n }\n }\ndiff --git a/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/IfElseBracingRule.kt b/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/IfElseBracingRule.kt\nindex 8e21614f71..8e2fea722b 100644\n--- a/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/IfElseBracingRule.kt\n+++ b/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/IfElseBracingRule.kt\n@@ -14,10 +14,10 @@ import com.pinterest.ktlint.rule.engine.core.api.RuleId\n import com.pinterest.ktlint.rule.engine.core.api.editorconfig.EditorConfig\n import com.pinterest.ktlint.rule.engine.core.api.editorconfig.INDENT_SIZE_PROPERTY\n import com.pinterest.ktlint.rule.engine.core.api.editorconfig.INDENT_STYLE_PROPERTY\n+import com.pinterest.ktlint.rule.engine.core.api.indent\n import com.pinterest.ktlint.rule.engine.core.api.isPartOfComment\n import com.pinterest.ktlint.rule.engine.core.api.isWhiteSpace\n import com.pinterest.ktlint.rule.engine.core.api.isWhiteSpaceWithoutNewline\n-import com.pinterest.ktlint.rule.engine.core.api.lineIndent\n import com.pinterest.ktlint.rule.engine.core.api.nextSibling\n import com.pinterest.ktlint.rule.engine.core.api.upsertWhitespaceBeforeMe\n import com.pinterest.ktlint.ruleset.standard.StandardRule\n@@ -147,13 +147,13 @@ public class IfElseBracingRule :\n val previousChild = node.firstChildNode\n node.replaceChild(node.firstChildNode, this)\n addChild(LeafPsiElement(LBRACE, \"{\"))\n- addChild(PsiWhiteSpaceImpl(\"\\n\" + node.lineIndent() + indentConfig.indent))\n+ addChild(PsiWhiteSpaceImpl(node.indent().plus(indentConfig.indent)))\n prevLeaves\n .dropWhile { it.isWhiteSpace() }\n .forEach(::addChild)\n addChild(previousChild)\n nextLeaves.forEach(::addChild)\n- addChild(PsiWhiteSpaceImpl(\"\\n\" + node.lineIndent()))\n+ addChild(PsiWhiteSpaceImpl(node.indent()))\n addChild(LeafPsiElement(RBRACE, \"}\"))\n }\n \ndiff --git a/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/KdocWrappingRule.kt b/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/KdocWrappingRule.kt\nindex d1b9e65880..740d491ef9 100644\n--- a/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/KdocWrappingRule.kt\n+++ b/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/KdocWrappingRule.kt\n@@ -8,7 +8,7 @@ import com.pinterest.ktlint.rule.engine.core.api.Rule\n import com.pinterest.ktlint.rule.engine.core.api.RuleId\n import com.pinterest.ktlint.rule.engine.core.api.editorconfig.INDENT_SIZE_PROPERTY\n import com.pinterest.ktlint.rule.engine.core.api.editorconfig.INDENT_STYLE_PROPERTY\n-import com.pinterest.ktlint.rule.engine.core.api.lineIndent\n+import com.pinterest.ktlint.rule.engine.core.api.indent\n import com.pinterest.ktlint.rule.engine.core.api.nextLeaf\n import com.pinterest.ktlint.rule.engine.core.api.noNewLineInClosedRange\n import com.pinterest.ktlint.rule.engine.core.api.prevLeaf\n@@ -93,7 +93,7 @@ public class KdocWrappingRule :\n ) {\n emit(startOffset, \"A KDoc comment may not be followed by any other element on that same line\", true)\n if (autoCorrect) {\n- this.upsertWhitespaceBeforeMe(\"\\n${kdocCommentNode.lineIndent()}\")\n+ this.upsertWhitespaceBeforeMe(kdocCommentNode.indent())\n }\n }\n \ndiff --git a/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/ModifierListSpacingRule.kt b/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/ModifierListSpacingRule.kt\nindex f5057396e4..2241f96ff7 100644\n--- a/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/ModifierListSpacingRule.kt\n+++ b/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/ModifierListSpacingRule.kt\n@@ -7,8 +7,8 @@ import com.pinterest.ktlint.rule.engine.core.api.ElementType.WHITE_SPACE\n import com.pinterest.ktlint.rule.engine.core.api.Rule\n import com.pinterest.ktlint.rule.engine.core.api.RuleId\n import com.pinterest.ktlint.rule.engine.core.api.children\n+import com.pinterest.ktlint.rule.engine.core.api.indent\n import com.pinterest.ktlint.rule.engine.core.api.isPartOfComment\n-import com.pinterest.ktlint.rule.engine.core.api.lineIndent\n import com.pinterest.ktlint.rule.engine.core.api.nextLeaf\n import com.pinterest.ktlint.rule.engine.core.api.nextSibling\n import com.pinterest.ktlint.rule.engine.core.api.prevLeaf\n@@ -57,7 +57,7 @@ public class ModifierListSpacingRule :\n (node.elementType == MODIFIER_LIST && node.lastChildNode.isAnnotationElement())\n ) {\n val expectedWhiteSpace = if (whitespace.textContains('\\n')) {\n- \"\\n\" + node.lineIndent()\n+ node.indent()\n } else {\n \" \"\n }\ndiff --git a/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/MultiLineIfElseRule.kt b/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/MultiLineIfElseRule.kt\nindex c9e18ace54..7a4a81cd85 100644\n--- a/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/MultiLineIfElseRule.kt\n+++ b/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/MultiLineIfElseRule.kt\n@@ -13,10 +13,10 @@ import com.pinterest.ktlint.rule.engine.core.api.RuleId\n import com.pinterest.ktlint.rule.engine.core.api.editorconfig.EditorConfig\n import com.pinterest.ktlint.rule.engine.core.api.editorconfig.INDENT_SIZE_PROPERTY\n import com.pinterest.ktlint.rule.engine.core.api.editorconfig.INDENT_STYLE_PROPERTY\n+import com.pinterest.ktlint.rule.engine.core.api.indent\n import com.pinterest.ktlint.rule.engine.core.api.isPartOfComment\n import com.pinterest.ktlint.rule.engine.core.api.isWhiteSpace\n import com.pinterest.ktlint.rule.engine.core.api.isWhiteSpaceWithoutNewline\n-import com.pinterest.ktlint.rule.engine.core.api.lineIndent\n import com.pinterest.ktlint.rule.engine.core.api.nextSibling\n import com.pinterest.ktlint.rule.engine.core.api.upsertWhitespaceBeforeMe\n import com.pinterest.ktlint.ruleset.standard.StandardRule\n@@ -101,13 +101,13 @@ public class MultiLineIfElseRule :\n val previousChild = node.firstChildNode\n node.replaceChild(node.firstChildNode, this)\n addChild(LeafPsiElement(LBRACE, \"{\"))\n- addChild(PsiWhiteSpaceImpl(\"\\n\" + node.lineIndent() + indentConfig.indent))\n+ addChild(PsiWhiteSpaceImpl(node.indent().plus(indentConfig.indent)))\n prevLeaves\n .dropWhile { it.isWhiteSpace() }\n .forEach(::addChild)\n addChild(previousChild)\n nextLeaves.forEach(::addChild)\n- addChild(PsiWhiteSpaceImpl(\"\\n\" + node.lineIndent()))\n+ addChild(PsiWhiteSpaceImpl(node.indent()))\n addChild(LeafPsiElement(RBRACE, \"}\"))\n }\n \ndiff --git a/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/NoEmptyFirstLineInClassBodyRule.kt b/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/NoEmptyFirstLineInClassBodyRule.kt\nindex b462d5e143..1ccab54c32 100644\n--- a/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/NoEmptyFirstLineInClassBodyRule.kt\n+++ b/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/NoEmptyFirstLineInClassBodyRule.kt\n@@ -7,8 +7,8 @@ import com.pinterest.ktlint.rule.engine.core.api.RuleId\n import com.pinterest.ktlint.rule.engine.core.api.editorconfig.EditorConfig\n import com.pinterest.ktlint.rule.engine.core.api.editorconfig.INDENT_SIZE_PROPERTY\n import com.pinterest.ktlint.rule.engine.core.api.editorconfig.INDENT_STYLE_PROPERTY\n+import com.pinterest.ktlint.rule.engine.core.api.indent\n import com.pinterest.ktlint.rule.engine.core.api.isWhiteSpaceWithNewline\n-import com.pinterest.ktlint.rule.engine.core.api.lineIndent\n import com.pinterest.ktlint.rule.engine.core.api.nextLeaf\n import com.pinterest.ktlint.ruleset.standard.StandardRule\n import org.jetbrains.kotlin.com.intellij.lang.ASTNode\n@@ -56,7 +56,7 @@ public class NoEmptyFirstLineInClassBodyRule :\n )\n if (autoCorrect) {\n (whitespace as LeafPsiElement).rawReplaceWithText(\n- \"\\n${node.lineIndent()}${indentConfig.indent}\",\n+ node.indent().plus(indentConfig.indent),\n )\n }\n }\ndiff --git a/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/ParameterListWrappingRule.kt b/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/ParameterListWrappingRule.kt\nindex 3aa3a59492..b0a5ee77b8 100644\n--- a/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/ParameterListWrappingRule.kt\n+++ b/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/ParameterListWrappingRule.kt\n@@ -18,8 +18,8 @@ import com.pinterest.ktlint.rule.engine.core.api.editorconfig.EditorConfig\n import com.pinterest.ktlint.rule.engine.core.api.editorconfig.INDENT_SIZE_PROPERTY\n import com.pinterest.ktlint.rule.engine.core.api.editorconfig.INDENT_STYLE_PROPERTY\n import com.pinterest.ktlint.rule.engine.core.api.editorconfig.MAX_LINE_LENGTH_PROPERTY\n+import com.pinterest.ktlint.rule.engine.core.api.indent\n import com.pinterest.ktlint.rule.engine.core.api.isWhiteSpaceWithNewline\n-import com.pinterest.ktlint.rule.engine.core.api.lineIndent\n import com.pinterest.ktlint.rule.engine.core.api.prevLeaf\n import com.pinterest.ktlint.rule.engine.core.api.prevSibling\n import com.pinterest.ktlint.rule.engine.core.api.upsertWhitespaceAfterMe\n@@ -155,7 +155,7 @@ public class ParameterListWrappingRule :\n }\n \n private fun getNewIndentLevel(node: ASTNode): Int {\n- val currentIndentLevel = indentConfig.indentLevelFrom(node.lineIndent())\n+ val currentIndentLevel = indentConfig.indentLevelFrom(node.indent(false))\n return when {\n // IDEA quirk:\n // fun <\ndiff --git a/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/ParameterWrappingRule.kt b/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/ParameterWrappingRule.kt\nindex 89bfe0442f..acc78f0d6a 100644\n--- a/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/ParameterWrappingRule.kt\n+++ b/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/ParameterWrappingRule.kt\n@@ -9,16 +9,17 @@ import com.pinterest.ktlint.rule.engine.core.api.ElementType.EQ\n import com.pinterest.ktlint.rule.engine.core.api.ElementType.TYPE_REFERENCE\n import com.pinterest.ktlint.rule.engine.core.api.ElementType.VALUE_PARAMETER\n import com.pinterest.ktlint.rule.engine.core.api.IndentConfig\n+import com.pinterest.ktlint.rule.engine.core.api.IndentConfig.Companion.DEFAULT_INDENT_CONFIG\n import com.pinterest.ktlint.rule.engine.core.api.RuleId\n import com.pinterest.ktlint.rule.engine.core.api.editorconfig.EditorConfig\n import com.pinterest.ktlint.rule.engine.core.api.editorconfig.INDENT_SIZE_PROPERTY\n import com.pinterest.ktlint.rule.engine.core.api.editorconfig.INDENT_STYLE_PROPERTY\n import com.pinterest.ktlint.rule.engine.core.api.editorconfig.MAX_LINE_LENGTH_PROPERTY\n import com.pinterest.ktlint.rule.engine.core.api.firstChildLeafOrSelf\n+import com.pinterest.ktlint.rule.engine.core.api.indent\n import com.pinterest.ktlint.rule.engine.core.api.isWhiteSpaceWithNewline\n import com.pinterest.ktlint.rule.engine.core.api.lastChildLeafOrSelf\n import com.pinterest.ktlint.rule.engine.core.api.leavesIncludingSelf\n-import com.pinterest.ktlint.rule.engine.core.api.lineIndent\n import com.pinterest.ktlint.rule.engine.core.api.nextCodeLeaf\n import com.pinterest.ktlint.rule.engine.core.api.prevLeaf\n import com.pinterest.ktlint.rule.engine.core.api.upsertWhitespaceAfterMe\n@@ -48,7 +49,7 @@ public class ParameterWrappingRule :\n ),\n ) {\n private var line = 1\n- private lateinit var indentConfig: IndentConfig\n+ private var indentConfig = DEFAULT_INDENT_CONFIG\n private var maxLineLength: Int = MAX_LINE_LENGTH_PROPERTY.defaultValue\n \n override fun beforeFirstNode(editorConfig: EditorConfig) {\n@@ -77,7 +78,7 @@ public class ParameterWrappingRule :\n ) {\n require(node.elementType == VALUE_PARAMETER)\n \n- val baseIndent = node.lineIndent()\n+ val baseIndentLength = node.indent(false).length\n \n // Find the first node after the indenting whitespace on the same line as the identifier\n val nodeFirstChildLeafOrSelf = node.firstChildLeafOrSelf()\n@@ -91,9 +92,9 @@ public class ParameterWrappingRule :\n node\n .findChildByType(COLON)\n ?.let { colon ->\n- if (baseIndent.length + fromNode.sumOfTextLengthUntil(colon) > maxLineLength) {\n+ if (baseIndentLength + fromNode.sumOfTextLengthUntil(colon) > maxLineLength) {\n fromNode.sumOfTextLengthUntil(colon)\n- requireNewlineAfterLeaf(colon, autoCorrect, emit, baseIndent)\n+ requireNewlineAfterLeaf(colon, autoCorrect, emit)\n return\n }\n }\n@@ -101,8 +102,8 @@ public class ParameterWrappingRule :\n node\n .findChildByType(TYPE_REFERENCE)\n ?.let { typeReference ->\n- if (baseIndent.length + fromNode.sumOfTextLengthUntil(typeReference.orTrailingComma()) > maxLineLength) {\n- requireNewlineBeforeLeaf(typeReference, autoCorrect, emit, baseIndent)\n+ if (baseIndentLength + fromNode.sumOfTextLengthUntil(typeReference.orTrailingComma()) > maxLineLength) {\n+ requireNewlineBeforeLeaf(typeReference, autoCorrect, emit)\n return\n }\n }\n@@ -110,8 +111,8 @@ public class ParameterWrappingRule :\n node\n .findChildByType(EQ)\n ?.let { equal ->\n- if (baseIndent.length + fromNode.sumOfTextLengthUntil(equal.orTrailingComma()) > maxLineLength) {\n- requireNewlineAfterLeaf(equal, autoCorrect, emit, baseIndent)\n+ if (baseIndentLength + fromNode.sumOfTextLengthUntil(equal.orTrailingComma()) > maxLineLength) {\n+ requireNewlineAfterLeaf(equal, autoCorrect, emit)\n return\n }\n }\n@@ -119,8 +120,8 @@ public class ParameterWrappingRule :\n node\n .findChildByType(CALL_EXPRESSION)\n ?.let { callExpression ->\n- if (baseIndent.length + fromNode.sumOfTextLengthUntil(callExpression.orTrailingComma()) > maxLineLength) {\n- requireNewlineBeforeLeaf(callExpression, autoCorrect, emit, baseIndent)\n+ if (baseIndentLength + fromNode.sumOfTextLengthUntil(callExpression.orTrailingComma()) > maxLineLength) {\n+ requireNewlineBeforeLeaf(callExpression, autoCorrect, emit)\n return\n }\n }\n@@ -143,7 +144,6 @@ public class ParameterWrappingRule :\n node: ASTNode,\n autoCorrect: Boolean,\n emit: (offset: Int, errorMessage: String, canBeAutoCorrected: Boolean) -> Unit,\n- indent: String,\n ) {\n emit(\n node.startOffset - 1,\n@@ -152,7 +152,7 @@ public class ParameterWrappingRule :\n )\n LOGGER.trace { \"$line: \" + ((if (!autoCorrect) \"would have \" else \"\") + \"inserted newline before ${node.text}\") }\n if (autoCorrect) {\n- node.upsertWhitespaceBeforeMe(\"\\n\" + indent)\n+ node.upsertWhitespaceBeforeMe(node.indent())\n }\n }\n \n@@ -160,7 +160,6 @@ public class ParameterWrappingRule :\n nodeAfterWhichNewlineIsRequired: ASTNode,\n autoCorrect: Boolean,\n emit: (offset: Int, errorMessage: String, canBeAutoCorrected: Boolean) -> Unit,\n- indent: String? = null,\n nodeToFix: ASTNode = nodeAfterWhichNewlineIsRequired,\n ) {\n emit(\n@@ -172,8 +171,7 @@ public class ParameterWrappingRule :\n \"$line: \" + (if (!autoCorrect) \"would have \" else \"\") + \"inserted newline after ${nodeAfterWhichNewlineIsRequired.text}\"\n }\n if (autoCorrect) {\n- val tempIndent = indent ?: (nodeToFix.lineIndent() + indentConfig.indent)\n- nodeToFix.upsertWhitespaceAfterMe(\"\\n\" + tempIndent)\n+ nodeToFix.upsertWhitespaceAfterMe(nodeToFix.indent().plus(indentConfig.indent))\n }\n }\n }\ndiff --git a/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/PropertyWrappingRule.kt b/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/PropertyWrappingRule.kt\nindex 96c2e5670a..034c465ead 100644\n--- a/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/PropertyWrappingRule.kt\n+++ b/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/PropertyWrappingRule.kt\n@@ -8,16 +8,17 @@ import com.pinterest.ktlint.rule.engine.core.api.ElementType.EQ\n import com.pinterest.ktlint.rule.engine.core.api.ElementType.PROPERTY\n import com.pinterest.ktlint.rule.engine.core.api.ElementType.TYPE_REFERENCE\n import com.pinterest.ktlint.rule.engine.core.api.IndentConfig\n+import com.pinterest.ktlint.rule.engine.core.api.IndentConfig.Companion.DEFAULT_INDENT_CONFIG\n import com.pinterest.ktlint.rule.engine.core.api.RuleId\n import com.pinterest.ktlint.rule.engine.core.api.editorconfig.EditorConfig\n import com.pinterest.ktlint.rule.engine.core.api.editorconfig.INDENT_SIZE_PROPERTY\n import com.pinterest.ktlint.rule.engine.core.api.editorconfig.INDENT_STYLE_PROPERTY\n import com.pinterest.ktlint.rule.engine.core.api.editorconfig.MAX_LINE_LENGTH_PROPERTY\n import com.pinterest.ktlint.rule.engine.core.api.firstChildLeafOrSelf\n+import com.pinterest.ktlint.rule.engine.core.api.indent\n import com.pinterest.ktlint.rule.engine.core.api.isWhiteSpaceWithNewline\n import com.pinterest.ktlint.rule.engine.core.api.lastChildLeafOrSelf\n import com.pinterest.ktlint.rule.engine.core.api.leavesIncludingSelf\n-import com.pinterest.ktlint.rule.engine.core.api.lineIndent\n import com.pinterest.ktlint.rule.engine.core.api.prevLeaf\n import com.pinterest.ktlint.rule.engine.core.api.upsertWhitespaceAfterMe\n import com.pinterest.ktlint.rule.engine.core.api.upsertWhitespaceBeforeMe\n@@ -46,7 +47,7 @@ public class PropertyWrappingRule :\n ),\n ) {\n private var line = 1\n- private lateinit var indentConfig: IndentConfig\n+ private var indentConfig = DEFAULT_INDENT_CONFIG\n private var maxLineLength: Int = MAX_LINE_LENGTH_PROPERTY.defaultValue\n \n override fun beforeFirstNode(editorConfig: EditorConfig) {\n@@ -75,7 +76,7 @@ public class PropertyWrappingRule :\n ) {\n require(node.elementType == PROPERTY)\n \n- val baseIndent = node.lineIndent()\n+ val baseIndentLength = node.indent(false).length\n \n // Find the first node after the indenting whitespace on the same line as the identifier\n val nodeFirstChildLeafOrSelf = node.firstChildLeafOrSelf()\n@@ -89,9 +90,9 @@ public class PropertyWrappingRule :\n node\n .findChildByType(COLON)\n ?.let { colon ->\n- if (baseIndent.length + fromNode.sumOfTextLengthUntil(colon) > maxLineLength) {\n+ if (baseIndentLength + fromNode.sumOfTextLengthUntil(colon) > maxLineLength) {\n fromNode.sumOfTextLengthUntil(colon)\n- requireNewlineAfterLeaf(colon, autoCorrect, emit, baseIndent)\n+ requireNewlineAfterLeaf(colon, autoCorrect, emit)\n return\n }\n }\n@@ -99,8 +100,8 @@ public class PropertyWrappingRule :\n node\n .findChildByType(TYPE_REFERENCE)\n ?.let { typeReference ->\n- if (baseIndent.length + fromNode.sumOfTextLengthUntil(typeReference) > maxLineLength) {\n- requireNewlineBeforeLeaf(typeReference, autoCorrect, emit, baseIndent)\n+ if (baseIndentLength + fromNode.sumOfTextLengthUntil(typeReference) > maxLineLength) {\n+ requireNewlineBeforeLeaf(typeReference, autoCorrect, emit)\n return\n }\n }\n@@ -108,8 +109,8 @@ public class PropertyWrappingRule :\n node\n .findChildByType(EQ)\n ?.let { equal ->\n- if (baseIndent.length + fromNode.sumOfTextLengthUntil(equal) > maxLineLength) {\n- requireNewlineAfterLeaf(equal, autoCorrect, emit, baseIndent)\n+ if (baseIndentLength + fromNode.sumOfTextLengthUntil(equal) > maxLineLength) {\n+ requireNewlineAfterLeaf(equal, autoCorrect, emit)\n return\n }\n }\n@@ -117,8 +118,8 @@ public class PropertyWrappingRule :\n node\n .findChildByType(CALL_EXPRESSION)\n ?.let { callExpression ->\n- if (baseIndent.length + fromNode.sumOfTextLengthUntil(callExpression) > maxLineLength) {\n- requireNewlineBeforeLeaf(callExpression, autoCorrect, emit, baseIndent)\n+ if (baseIndentLength + fromNode.sumOfTextLengthUntil(callExpression) > maxLineLength) {\n+ requireNewlineBeforeLeaf(callExpression, autoCorrect, emit)\n return\n }\n }\n@@ -135,7 +136,6 @@ public class PropertyWrappingRule :\n node: ASTNode,\n autoCorrect: Boolean,\n emit: (offset: Int, errorMessage: String, canBeAutoCorrected: Boolean) -> Unit,\n- indent: String,\n ) {\n emit(\n node.startOffset - 1,\n@@ -144,7 +144,7 @@ public class PropertyWrappingRule :\n )\n LOGGER.trace { \"$line: \" + ((if (!autoCorrect) \"would have \" else \"\") + \"inserted newline before ${node.text}\") }\n if (autoCorrect) {\n- node.upsertWhitespaceBeforeMe(\"\\n\" + indent)\n+ node.upsertWhitespaceBeforeMe(node.indent())\n }\n }\n \n@@ -152,7 +152,6 @@ public class PropertyWrappingRule :\n nodeAfterWhichNewlineIsRequired: ASTNode,\n autoCorrect: Boolean,\n emit: (offset: Int, errorMessage: String, canBeAutoCorrected: Boolean) -> Unit,\n- indent: String? = null,\n nodeToFix: ASTNode = nodeAfterWhichNewlineIsRequired,\n ) {\n emit(\n@@ -164,8 +163,7 @@ public class PropertyWrappingRule :\n \"$line: \" + (if (!autoCorrect) \"would have \" else \"\") + \"inserted newline after ${nodeAfterWhichNewlineIsRequired.text}\"\n }\n if (autoCorrect) {\n- val tempIndent = indent ?: (nodeToFix.lineIndent() + indentConfig.indent)\n- nodeToFix.upsertWhitespaceAfterMe(\"\\n\" + tempIndent)\n+ nodeToFix.upsertWhitespaceAfterMe(nodeToFix.indent().plus(indentConfig.indent))\n }\n }\n }\ndiff --git a/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/TrailingCommaOnDeclarationSiteRule.kt b/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/TrailingCommaOnDeclarationSiteRule.kt\nindex 1d89ec86ed..4fc2c570d9 100644\n--- a/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/TrailingCommaOnDeclarationSiteRule.kt\n+++ b/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/TrailingCommaOnDeclarationSiteRule.kt\n@@ -15,8 +15,8 @@ import com.pinterest.ktlint.rule.engine.core.api.RuleId\n import com.pinterest.ktlint.rule.engine.core.api.children\n import com.pinterest.ktlint.rule.engine.core.api.editorconfig.EditorConfig\n import com.pinterest.ktlint.rule.engine.core.api.editorconfig.EditorConfigProperty\n+import com.pinterest.ktlint.rule.engine.core.api.indent\n import com.pinterest.ktlint.rule.engine.core.api.isCodeLeaf\n-import com.pinterest.ktlint.rule.engine.core.api.lineIndent\n import com.pinterest.ktlint.rule.engine.core.api.noNewLineInClosedRange\n import com.pinterest.ktlint.rule.engine.core.api.prevCodeLeaf\n import com.pinterest.ktlint.rule.engine.core.api.prevLeaf\n@@ -41,7 +41,6 @@ import org.jetbrains.kotlin.psi.KtWhenExpression\n import org.jetbrains.kotlin.psi.psiUtil.anyDescendantOfType\n import org.jetbrains.kotlin.psi.psiUtil.collectDescendantsOfType\n import org.jetbrains.kotlin.psi.psiUtil.nextLeaf\n-import org.jetbrains.kotlin.psi.psiUtil.parents\n import org.jetbrains.kotlin.psi.psiUtil.prevLeaf\n import org.jetbrains.kotlin.utils.addToStdlib.cast\n \n@@ -260,8 +259,7 @@ public class TrailingCommaOnDeclarationSiteRule :\n true,\n )\n if (autoCorrect) {\n- val parentIndent = \"\\n\" + inspectNode.getWhenEntryIndent()\n- lastNodeBeforeArrow.upsertWhitespaceAfterMe(parentIndent)\n+ lastNodeBeforeArrow.upsertWhitespaceAfterMe(inspectNode.treeParent.indent())\n }\n }\n }\n@@ -294,13 +292,15 @@ public class TrailingCommaOnDeclarationSiteRule :\n }\n if (autoCorrect) {\n if (addNewLineBeforeArrowInWhenEntry) {\n- val parentIndent = \"\\n\" + prevNode.getWhenEntryIndent()\n+ val newLine = KtPsiFactory(prevNode.psi).createWhiteSpace(\n+ prevNode\n+ .treeParent\n+ .indent(),\n+ )\n val leafBeforeArrow = (psi as KtWhenEntry).arrow?.prevLeaf()\n if (leafBeforeArrow != null && leafBeforeArrow is PsiWhiteSpace) {\n- val newLine = KtPsiFactory(prevNode.psi).createWhiteSpace(parentIndent)\n leafBeforeArrow.replace(newLine)\n } else {\n- val newLine = KtPsiFactory(prevNode.psi).createWhiteSpace(parentIndent)\n prevNode.psi.parent.addAfter(newLine, prevNode.psi)\n }\n }\n@@ -310,7 +310,7 @@ public class TrailingCommaOnDeclarationSiteRule :\n with(KtPsiFactory(prevNode.psi)) {\n val parentIndent =\n (prevNode.psi.parent.prevLeaf() as? PsiWhiteSpace)?.text\n- ?: \"\\n${prevNode.lineIndent()}\"\n+ ?: prevNode.indent()\n val newline = createWhiteSpace(parentIndent)\n val enumEntry = inspectNode.treeParent.psi\n enumEntry.apply {\n@@ -339,12 +339,6 @@ public class TrailingCommaOnDeclarationSiteRule :\n }\n }\n \n- private fun ASTNode.getWhenEntryIndent() =\n- // The when entry can be a simple value but might also be a complex expression.\n- parents()\n- .last { it.elementType == WHEN_ENTRY }\n- .lineIndent()\n-\n private fun isMultiline(element: PsiElement): Boolean =\n when {\n element.parent is KtFunctionLiteral -> {\ndiff --git a/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/WrappingRule.kt b/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/WrappingRule.kt\nindex 323a58daf8..cd173e065b 100644\n--- a/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/WrappingRule.kt\n+++ b/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/WrappingRule.kt\n@@ -30,6 +30,8 @@ import com.pinterest.ktlint.rule.engine.core.api.ElementType.STRING_TEMPLATE\n import com.pinterest.ktlint.rule.engine.core.api.ElementType.SUPER_TYPE_CALL_ENTRY\n import com.pinterest.ktlint.rule.engine.core.api.ElementType.SUPER_TYPE_ENTRY\n import com.pinterest.ktlint.rule.engine.core.api.ElementType.SUPER_TYPE_LIST\n+import com.pinterest.ktlint.rule.engine.core.api.ElementType.TYPE_ARGUMENT_LIST\n+import com.pinterest.ktlint.rule.engine.core.api.ElementType.TYPE_PROJECTION\n import com.pinterest.ktlint.rule.engine.core.api.ElementType.VALUE_ARGUMENT\n import com.pinterest.ktlint.rule.engine.core.api.ElementType.VALUE_ARGUMENT_LIST\n import com.pinterest.ktlint.rule.engine.core.api.ElementType.VALUE_PARAMETER\n@@ -37,6 +39,7 @@ import com.pinterest.ktlint.rule.engine.core.api.ElementType.VALUE_PARAMETER_LIS\n import com.pinterest.ktlint.rule.engine.core.api.ElementType.WHEN_ENTRY\n import com.pinterest.ktlint.rule.engine.core.api.ElementType.WHITE_SPACE\n import com.pinterest.ktlint.rule.engine.core.api.IndentConfig\n+import com.pinterest.ktlint.rule.engine.core.api.IndentConfig.Companion.DEFAULT_INDENT_CONFIG\n import com.pinterest.ktlint.rule.engine.core.api.RuleId\n import com.pinterest.ktlint.rule.engine.core.api.children\n import com.pinterest.ktlint.rule.engine.core.api.editorconfig.EditorConfig\n@@ -45,12 +48,12 @@ import com.pinterest.ktlint.rule.engine.core.api.editorconfig.INDENT_STYLE_PROPE\n import com.pinterest.ktlint.rule.engine.core.api.editorconfig.MAX_LINE_LENGTH_PROPERTY\n import com.pinterest.ktlint.rule.engine.core.api.editorconfig.MAX_LINE_LENGTH_PROPERTY_OFF\n import com.pinterest.ktlint.rule.engine.core.api.firstChildLeafOrSelf\n+import com.pinterest.ktlint.rule.engine.core.api.indent\n import com.pinterest.ktlint.rule.engine.core.api.isPartOfComment\n import com.pinterest.ktlint.rule.engine.core.api.isWhiteSpace\n import com.pinterest.ktlint.rule.engine.core.api.isWhiteSpaceWithNewline\n import com.pinterest.ktlint.rule.engine.core.api.isWhiteSpaceWithoutNewline\n import com.pinterest.ktlint.rule.engine.core.api.lastChildLeafOrSelf\n-import com.pinterest.ktlint.rule.engine.core.api.lineIndent\n import com.pinterest.ktlint.rule.engine.core.api.nextCodeLeaf\n import com.pinterest.ktlint.rule.engine.core.api.nextCodeSibling\n import com.pinterest.ktlint.rule.engine.core.api.nextLeaf\n@@ -92,7 +95,7 @@ public class WrappingRule :\n ),\n ) {\n private var line = 1\n- private lateinit var indentConfig: IndentConfig\n+ private var indentConfig = DEFAULT_INDENT_CONFIG\n private var maxLineLength: Int = MAX_LINE_LENGTH_PROPERTY.defaultValue\n \n override fun beforeFirstNode(editorConfig: EditorConfig) {\n@@ -114,6 +117,7 @@ public class WrappingRule :\n LPAR, LBRACKET -> rearrangeBlock(node, autoCorrect, emit) // TODO: LT\n SUPER_TYPE_LIST -> rearrangeSuperTypeList(node, autoCorrect, emit)\n VALUE_PARAMETER_LIST, VALUE_ARGUMENT_LIST -> rearrangeValueList(node, autoCorrect, emit)\n+ TYPE_ARGUMENT_LIST -> rearrangeTypeArgumentList(node, autoCorrect, emit)\n ARROW -> rearrangeArrow(node, autoCorrect, emit)\n WHITE_SPACE -> line += node.text.count { it == '\\n' }\n CLOSING_QUOTE -> rearrangeClosingQuote(node, autoCorrect, emit)\n@@ -246,7 +250,7 @@ public class WrappingRule :\n requireNewlineAfterLeaf(node, autoCorrect, emit)\n }\n if (!r.prevLeaf().isWhiteSpaceWithNewline()) {\n- requireNewlineBeforeLeaf(r, autoCorrect, emit, node.treeParent.lineIndent())\n+ requireNewlineBeforeLeaf(r, autoCorrect, emit, node.treeParent.indent())\n }\n }\n \n@@ -283,7 +287,7 @@ public class WrappingRule :\n !colon.prevLeaf().isWhiteSpaceWithNewline() &&\n colon.prevCodeLeaf().let { it?.elementType != RPAR || !it.prevLeaf().isWhiteSpaceWithNewline() }\n ) {\n- requireNewlineAfterLeaf(colon, autoCorrect, emit, node.lineIndent() + indentConfig.indent)\n+ requireNewlineAfterLeaf(colon, autoCorrect, emit)\n }\n }\n // put entries on separate lines\n@@ -297,7 +301,7 @@ public class WrappingRule :\n nodeAfterWhichNewlineIsRequired = c,\n autoCorrect = autoCorrect,\n emit = emit,\n- indent = node.lineIndent(),\n+ indent = node.indent(),\n )\n }\n }\n@@ -363,6 +367,50 @@ public class WrappingRule :\n elementType == VALUE_PARAMETER &&\n siblings().none { it.elementType == VALUE_PARAMETER }\n \n+ private fun rearrangeTypeArgumentList(\n+ node: ASTNode,\n+ autoCorrect: Boolean,\n+ emit: (offset: Int, errorMessage: String, canBeAutoCorrected: Boolean) -> Unit,\n+ ) {\n+ if (node.textContains('\\n')) {\n+ // Each type projection must be preceded with a whitespace containing a newline\n+ node\n+ .children()\n+ .filter { it.elementType == TYPE_PROJECTION }\n+ .forEach { typeProjection ->\n+ typeProjection\n+ .prevSibling { !it.isPartOfComment() }\n+ .let { prevSibling ->\n+ if (prevSibling?.elementType == LT || prevSibling.isWhiteSpaceWithoutNewline()) {\n+ emit(typeProjection.startOffset, \"A newline was expected before '${typeProjection.text}'\", true)\n+ if (autoCorrect) {\n+ typeProjection.upsertWhitespaceBeforeMe(\n+ node.treeParent.indent().plus(indentConfig.indent),\n+ )\n+ }\n+ }\n+ }\n+ }\n+\n+ // After the last type projection a whitespace containing a newline must exist\n+ node\n+ .findChildByType(GT)\n+ ?.let { closingAngle ->\n+ val prevSibling = closingAngle.prevSibling { !it.isPartOfComment() }\n+ if (prevSibling?.elementType != WHITE_SPACE || prevSibling.isWhiteSpaceWithoutNewline()) {\n+ emit(closingAngle.startOffset, \"A newline was expected before '${closingAngle.text}'\", true)\n+ if (autoCorrect) {\n+ closingAngle.upsertWhitespaceBeforeMe(\n+ node.treeParent.indent().plus(indentConfig.indent),\n+ )\n+ }\n+ }\n+ }\n+\n+ Unit\n+ }\n+ }\n+\n private fun rearrangeClosingQuote(\n node: ASTNode,\n autoCorrect: Boolean,\n@@ -461,7 +509,7 @@ public class WrappingRule :\n }\n val r = node.nextSibling { it.elementType == RBRACE } ?: return\n if (!r.prevLeaf().isWhiteSpaceWithNewline()) {\n- requireNewlineBeforeLeaf(r, autoCorrect, emit, node.lineIndent())\n+ requireNewlineBeforeLeaf(r, autoCorrect, emit, node.indent())\n }\n }\n \n@@ -478,7 +526,7 @@ public class WrappingRule :\n )\n LOGGER.trace { \"$line: \" + ((if (!autoCorrect) \"would have \" else \"\") + \"inserted newline before ${node.text}\") }\n if (autoCorrect) {\n- node.upsertWhitespaceBeforeMe(\"\\n\" + indent)\n+ node.upsertWhitespaceBeforeMe(indent)\n }\n }\n \n@@ -498,8 +546,8 @@ public class WrappingRule :\n \"$line: \" + (if (!autoCorrect) \"would have \" else \"\") + \"inserted newline after ${nodeAfterWhichNewlineIsRequired.text}\"\n }\n if (autoCorrect) {\n- val tempIndent = indent ?: (nodeToFix.lineIndent() + indentConfig.indent)\n- nodeToFix.upsertWhitespaceAfterMe(\"\\n\" + tempIndent)\n+ val tempIndent = indent ?: (nodeToFix.indent().plus(indentConfig.indent))\n+ nodeToFix.upsertWhitespaceAfterMe(tempIndent)\n }\n }\n \n@@ -590,7 +638,7 @@ public class WrappingRule :\n endOfBlock,\n autoCorrect,\n emit,\n- node.treeParent.lineIndent(),\n+ node.treeParent.indent(),\n )\n }\n }\n", "test_patch": "diff --git a/ktlint-rule-engine-core/src/test/kotlin/com/pinterest/ktlint/rule/engine/core/api/ASTNodeExtensionTest.kt b/ktlint-rule-engine-core/src/test/kotlin/com/pinterest/ktlint/rule/engine/core/api/ASTNodeExtensionTest.kt\nindex 68d1dac2ec..608597e9c7 100644\n--- a/ktlint-rule-engine-core/src/test/kotlin/com/pinterest/ktlint/rule/engine/core/api/ASTNodeExtensionTest.kt\n+++ b/ktlint-rule-engine-core/src/test/kotlin/com/pinterest/ktlint/rule/engine/core/api/ASTNodeExtensionTest.kt\n@@ -6,14 +6,17 @@ import com.pinterest.ktlint.rule.engine.core.api.ElementType.CLASS\n import com.pinterest.ktlint.rule.engine.core.api.ElementType.CLASS_BODY\n import com.pinterest.ktlint.rule.engine.core.api.ElementType.ENUM_ENTRY\n import com.pinterest.ktlint.rule.engine.core.api.ElementType.FUN\n+import com.pinterest.ktlint.rule.engine.core.api.ElementType.IDENTIFIER\n import com.pinterest.ktlint.rule.engine.core.api.ElementType.LPAR\n import com.pinterest.ktlint.rule.engine.core.api.ElementType.RPAR\n import com.pinterest.ktlint.rule.engine.core.api.ElementType.VALUE_PARAMETER\n import com.pinterest.ktlint.rule.engine.core.api.ElementType.VALUE_PARAMETER_LIST\n import com.pinterest.ktlint.rule.engine.core.api.ElementType.WHITE_SPACE\n-import org.assertj.core.api.Assertions\n+import org.assertj.core.api.Assertions.assertThat\n+import org.assertj.core.api.Assertions.entry\n import org.jetbrains.kotlin.com.intellij.lang.ASTNode\n import org.jetbrains.kotlin.com.intellij.lang.FileASTNode\n+import org.jetbrains.kotlin.psi.psiUtil.leaves\n import org.junit.jupiter.api.Nested\n import org.junit.jupiter.api.Test\n import kotlin.reflect.KFunction1\n@@ -34,7 +37,7 @@ class ASTNodeExtensionTest {\n .map { it.text }\n .toList()\n \n- Assertions.assertThat(actual).containsExactly(\n+ assertThat(actual).containsExactly(\n // LBRACE is omitted from class body as it is an open range\n \"\\n \",\n \"FOO\",\n@@ -66,7 +69,7 @@ class ASTNodeExtensionTest {\n \n val actual = hasNewLineInClosedRange(enumEntries.first(), enumEntries.last())\n \n- Assertions.assertThat(actual).isFalse\n+ assertThat(actual).isFalse\n }\n \n @Test\n@@ -80,7 +83,7 @@ class ASTNodeExtensionTest {\n \n val actual = hasNewLineInClosedRange(enumClassBody.first(), enumClassBody.last())\n \n- Assertions.assertThat(actual).isTrue\n+ assertThat(actual).isTrue\n }\n \n @Test\n@@ -96,7 +99,7 @@ class ASTNodeExtensionTest {\n \n val actual = hasNewLineInClosedRange(enumClassBody.first(), enumClassBody.last())\n \n- Assertions.assertThat(actual).isTrue\n+ assertThat(actual).isTrue\n }\n \n @Test\n@@ -110,7 +113,7 @@ class ASTNodeExtensionTest {\n \n val actual = hasNewLineInClosedRange(enumClassBody.first(), enumClassBody.last())\n \n- Assertions.assertThat(actual).isTrue\n+ assertThat(actual).isTrue\n }\n \n @Test\n@@ -125,7 +128,7 @@ class ASTNodeExtensionTest {\n \n val actual = hasNewLineInClosedRange(enumClassBody.first(), enumClassBody.last())\n \n- Assertions.assertThat(actual).isTrue\n+ assertThat(actual).isTrue\n }\n }\n \n@@ -146,7 +149,7 @@ class ASTNodeExtensionTest {\n \n val actual = noNewLineInClosedRange(enumEntries.first(), enumEntries.last())\n \n- Assertions.assertThat(actual).isTrue\n+ assertThat(actual).isTrue\n }\n \n @Test\n@@ -160,7 +163,7 @@ class ASTNodeExtensionTest {\n \n val actual = noNewLineInClosedRange(enumClassBody.first(), enumClassBody.last())\n \n- Assertions.assertThat(actual).isFalse\n+ assertThat(actual).isFalse\n }\n \n @Test\n@@ -177,7 +180,7 @@ class ASTNodeExtensionTest {\n \n val actual = noNewLineInClosedRange(enumClassBody.first(), enumClassBody.last())\n \n- Assertions.assertThat(actual).isFalse\n+ assertThat(actual).isFalse\n }\n \n @Test\n@@ -191,7 +194,7 @@ class ASTNodeExtensionTest {\n \n val actual = noNewLineInClosedRange(enumClassBody.first(), enumClassBody.last())\n \n- Assertions.assertThat(actual).isFalse\n+ assertThat(actual).isFalse\n }\n \n @Test\n@@ -206,7 +209,7 @@ class ASTNodeExtensionTest {\n \n val actual = noNewLineInClosedRange(enumClassBody.first(), enumClassBody.last())\n \n- Assertions.assertThat(actual).isFalse\n+ assertThat(actual).isFalse\n }\n }\n \n@@ -233,7 +236,7 @@ class ASTNodeExtensionTest {\n ?.upsertWhitespaceBeforeMe(\"\\n\")\n }.text\n \n- Assertions.assertThat(actual).isEqualTo(formattedCode)\n+ assertThat(actual).isEqualTo(formattedCode)\n }\n \n @Test\n@@ -256,7 +259,7 @@ class ASTNodeExtensionTest {\n ?.upsertWhitespaceBeforeMe(\"\\n\\n\")\n }.text\n \n- Assertions.assertThat(actual).isEqualTo(formattedCode)\n+ assertThat(actual).isEqualTo(formattedCode)\n }\n \n @Test\n@@ -279,7 +282,7 @@ class ASTNodeExtensionTest {\n ?.upsertWhitespaceBeforeMe(\"\\n\\n\")\n }.text\n \n- Assertions.assertThat(actual).isEqualTo(formattedCode)\n+ assertThat(actual).isEqualTo(formattedCode)\n }\n \n @Test\n@@ -303,7 +306,7 @@ class ASTNodeExtensionTest {\n ?.upsertWhitespaceBeforeMe(\"\\n \")\n }.text\n \n- Assertions.assertThat(actual).isEqualTo(formattedCode)\n+ assertThat(actual).isEqualTo(formattedCode)\n }\n \n @Test\n@@ -328,7 +331,7 @@ class ASTNodeExtensionTest {\n .upsertWhitespaceBeforeMe(\"\\n\\n\")\n }.text\n \n- Assertions.assertThat(actual).isEqualTo(formattedCode)\n+ assertThat(actual).isEqualTo(formattedCode)\n }\n }\n \n@@ -354,7 +357,7 @@ class ASTNodeExtensionTest {\n ?.upsertWhitespaceAfterMe(\"\\n\\n\")\n }.text\n \n- Assertions.assertThat(actual).isEqualTo(formattedCode)\n+ assertThat(actual).isEqualTo(formattedCode)\n }\n \n @Test\n@@ -377,7 +380,7 @@ class ASTNodeExtensionTest {\n ?.upsertWhitespaceAfterMe(\"\\n\\n\")\n }.text\n \n- Assertions.assertThat(actual).isEqualTo(formattedCode)\n+ assertThat(actual).isEqualTo(formattedCode)\n }\n \n @Test\n@@ -401,7 +404,7 @@ class ASTNodeExtensionTest {\n ?.upsertWhitespaceAfterMe(\"\\n\")\n }.text\n \n- Assertions.assertThat(actual).isEqualTo(formattedCode)\n+ assertThat(actual).isEqualTo(formattedCode)\n }\n \n @Test\n@@ -426,10 +429,39 @@ class ASTNodeExtensionTest {\n .upsertWhitespaceAfterMe(\"\\n\\n\")\n }.text\n \n- Assertions.assertThat(actual).isEqualTo(formattedCode)\n+ assertThat(actual).isEqualTo(formattedCode)\n }\n }\n \n+ @Test\n+ fun `Given some identifiers at different indentation levels`() {\n+ val code =\n+ \"\"\"\n+ class Foo1 {\n+ val foo2 = \"foo2\"\n+\n+ fun foo3() {\n+ val foo4 = \"foo4\"\n+ }\n+ }\n+ \"\"\".trimIndent()\n+\n+ val actual =\n+ transformCodeToAST(code)\n+ .firstChildLeafOrSelf()\n+ .leaves()\n+ .filter { it.elementType == IDENTIFIER }\n+ .map { it.text to it.indent() }\n+ .toMap()\n+\n+ assertThat(actual).contains(\n+ entry(\"Foo1\", \"\\n\"),\n+ entry(\"foo2\", \"\\n \"),\n+ entry(\"foo3\", \"\\n \"),\n+ entry(\"foo4\", \"\\n \"),\n+ )\n+ }\n+\n private inline fun String.transformAst(block: FileASTNode.() -> Unit): FileASTNode =\n transformCodeToAST(this)\n .apply(block)\ndiff --git a/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/AnnotationRuleTest.kt b/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/AnnotationRuleTest.kt\nindex c7a7b08196..6dc52f2d9d 100644\n--- a/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/AnnotationRuleTest.kt\n+++ b/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/AnnotationRuleTest.kt\n@@ -6,7 +6,7 @@ import org.junit.jupiter.api.Nested\n import org.junit.jupiter.api.Test\n \n class AnnotationRuleTest {\n- private val annotationRuleAssertThat = assertThatRule { com.pinterest.ktlint.ruleset.standard.rules.AnnotationRule() }\n+ private val annotationRuleAssertThat = assertThatRule { AnnotationRule() }\n \n @Test\n fun `Given a single annotation on same line before the annotated construct`() {\n@@ -126,12 +126,32 @@ class AnnotationRuleTest {\n \"\"\".trimIndent()\n annotationRuleAssertThat(code)\n .hasLintViolations(\n- LintViolation(1, 1, \"Multiple annotations should not be placed on the same line as the annotated construct\"),\n- LintViolation(2, 5, \"Multiple annotations should not be placed on the same line as the annotated construct\"),\n- LintViolation(3, 5, \"Multiple annotations should not be placed on the same line as the annotated construct\"),\n+ LintViolation(1, 11, \"Multiple annotations should not be placed on the same line as the annotated construct\"),\n+ LintViolation(2, 15, \"Multiple annotations should not be placed on the same line as the annotated construct\"),\n+ LintViolation(3, 15, \"Multiple annotations should not be placed on the same line as the annotated construct\"),\n ).isFormattedAs(formattedCode)\n }\n \n+ @Test\n+ fun `Given an array of annotations on the same line as the annotated construct then do not report a violation`() {\n+ val code =\n+ \"\"\"\n+ @[Foo Bar] class FooBar2 {\n+ @[Foo Bar] var foo: String\n+ @[Foo Bar] fun bar() {}\n+ }\n+ \"\"\".trimIndent()\n+ val formattedCode =\n+ \"\"\"\n+ @[Foo Bar] class FooBar2 {\n+ @[Foo Bar] var foo: String\n+ @[Foo Bar] fun bar() {}\n+ }\n+ \"\"\".trimIndent()\n+ annotationRuleAssertThat(code)\n+ .hasNoLintViolations()\n+ }\n+\n @Test\n fun `Given multiple annotations on same line as annotated construct (without indentation)`() {\n val code =\n@@ -144,7 +164,7 @@ class AnnotationRuleTest {\n var foo: String\n \"\"\".trimIndent()\n annotationRuleAssertThat(code)\n- .hasLintViolation(1, 1, \"Multiple annotations should not be placed on the same line as the annotated construct\")\n+ .hasLintViolation(1, 21, \"Multiple annotations should not be placed on the same line as the annotated construct\")\n .isFormattedAs(formattedCode)\n }\n \n@@ -160,7 +180,7 @@ class AnnotationRuleTest {\n var foo: String\n \"\"\".trimIndent()\n annotationRuleAssertThat(code)\n- .hasLintViolation(1, 1, \"Multiple annotations should not be placed on the same line as the annotated construct\")\n+ .hasLintViolation(1, 21, \"Multiple annotations should not be placed on the same line as the annotated construct\")\n .isFormattedAs(formattedCode)\n }\n \n@@ -238,8 +258,9 @@ class AnnotationRuleTest {\n val bar: Any\n }\n \"\"\".trimIndent()\n+ @Suppress(\"ktlint:argument-list-wrapping\", \"ktlint:max-line-length\")\n annotationRuleAssertThat(code)\n- .hasLintViolation(3, 5, \"Annotation must be placed on separate line\")\n+ .hasLintViolation(3, 5, \"Annotation must be placed on a separate line when it is preceded by another annotation on a separate line\")\n .isFormattedAs(formattedCode)\n }\n \n@@ -509,6 +530,17 @@ class AnnotationRuleTest {\n annotationRuleAssertThat(code).hasNoLintViolations()\n }\n \n+ @Test\n+ fun `Given multiple annotations on the same line without parameter but above the annotated construct`() {\n+ val code =\n+ \"\"\"\n+ @Foo1 @Foo2\n+ fun foo() {}\n+ \"\"\".trimIndent()\n+ annotationRuleAssertThat(code)\n+ .hasNoLintViolations()\n+ }\n+\n @Test\n fun `Given a line containing multiple annotations without parameters and another line with another annotation`() {\n val code =\n@@ -526,7 +558,7 @@ class AnnotationRuleTest {\n \"\"\".trimIndent()\n annotationRuleAssertThat(code)\n .asKotlinScript()\n- .hasLintViolation(2, 1, \"Annotation must be placed on separate line\")\n+ .hasLintViolation(2, 7, \"All annotations should either be on a single line or all annotations should be on a separate line\")\n .isFormattedAs(formattedCode)\n }\n \n@@ -595,4 +627,83 @@ class AnnotationRuleTest {\n .isFormattedAs(formattedCode)\n }\n }\n+\n+ @Test\n+ fun `Given a single annotation on same line as a type parameter then do not report a violation`() {\n+ val code =\n+ \"\"\"\n+ @Target(AnnotationTarget.TYPE)\n+ annotation class Foo\n+ val foo1: List<@Foo String> = emptyList()\n+ val foo2 = emptyList<@Foo String>()\n+ val foo3: Map<@Foo String, @Foo String> = emptyMap()\n+ val foo4 = emptyMap<@Foo String, @Foo String>()\n+ \"\"\".trimIndent()\n+ annotationRuleAssertThat(code)\n+ .hasNoLintViolations()\n+ }\n+\n+ @Nested\n+ inner class `Issue 1725 - Given multiple annotations on same line as a type parameter` {\n+ @Test\n+ fun `Given a list with multiple annotations on its type`() {\n+ val code =\n+ \"\"\"\n+ val fooBar: List<@Foo @Bar String> = emptyList()\n+ \"\"\".trimIndent()\n+ val formattedCode =\n+ \"\"\"\n+ val fooBar: List<\n+ @Foo @Bar\n+ String\n+ > = emptyList()\n+ \"\"\".trimIndent()\n+ annotationRuleAssertThat(code)\n+ .addAdditionalRuleProvider { TrailingCommaOnDeclarationSiteRule() }\n+ .addAdditionalRuleProvider { WrappingRule() }\n+ .hasLintViolations(\n+ LintViolation(1, 18, \"Annotations on a type reference should be placed on a separate line\"),\n+ LintViolation(1, 28, \"Multiple annotations should not be placed on the same line as the annotated construct\"),\n+ LintViolation(1, 28, \"Annotations on a type reference should be placed on a separate line\"),\n+ ).isFormattedAs(formattedCode)\n+ }\n+\n+ @Test\n+ fun `Given a custom type with multiple annotations on it type parameter(s)`() {\n+ val code =\n+ \"\"\"\n+ val fooBar: FooBar = emptyList()\n+ \"\"\".trimIndent()\n+ val formattedCode =\n+ \"\"\"\n+ val fooBar: FooBar<\n+ String,\n+ @Foo @Bar\n+ String,\n+ String\n+ > = emptyList()\n+ \"\"\".trimIndent()\n+ annotationRuleAssertThat(code)\n+ .addAdditionalRuleProvider { IndentationRule() }\n+ .addAdditionalRuleProvider { WrappingRule() }\n+ .hasLintViolations(\n+ LintViolation(1, 28, \"Annotations on a type reference should be placed on a separate line\"),\n+ LintViolation(1, 38, \"Multiple annotations should not be placed on the same line as the annotated construct\"),\n+ LintViolation(1, 38, \"Annotations on a type reference should be placed on a separate line\"),\n+ ).isFormattedAs(formattedCode)\n+ }\n+ }\n+\n+ @Nested\n+ inner class `Given an array of annotations on same line as a type parameter` {\n+ @Test\n+ fun `Given a list with an array of annotations on its type`() {\n+ val code =\n+ \"\"\"\n+ val fooBar: List<@[Foo Bar] String> = emptyList()\n+ \"\"\".trimIndent()\n+ annotationRuleAssertThat(code)\n+ .hasNoLintViolations()\n+ }\n+ }\n }\ndiff --git a/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/BlockCommentInitialStarTest.kt b/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/BlockCommentInitialStarAlignmentRuleTest.kt\nsimilarity index 98%\nrename from ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/BlockCommentInitialStarTest.kt\nrename to ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/BlockCommentInitialStarAlignmentRuleTest.kt\nindex 941e91045b..63c9b54e79 100644\n--- a/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/BlockCommentInitialStarTest.kt\n+++ b/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/BlockCommentInitialStarAlignmentRuleTest.kt\n@@ -4,7 +4,7 @@ import com.pinterest.ktlint.test.KtLintAssertThat.Companion.assertThatRule\n import com.pinterest.ktlint.test.LintViolation\n import org.junit.jupiter.api.Test\n \n-class BlockCommentInitialStarTest {\n+class BlockCommentInitialStarAlignmentRuleTest {\n private val blockCommentInitialStarAlignmentRuleAssertThat = assertThatRule { BlockCommentInitialStarAlignmentRule() }\n \n @Test\ndiff --git a/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/WrappingRuleTest.kt b/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/WrappingRuleTest.kt\nindex 68eda43510..70939d0019 100644\n--- a/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/WrappingRuleTest.kt\n+++ b/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/WrappingRuleTest.kt\n@@ -1779,6 +1779,62 @@ internal class WrappingRuleTest {\n .hasNoLintViolations()\n }\n }\n+\n+ @Nested\n+ inner class `Given a multiline type argument list` {\n+ @Test\n+ fun `Given a single line type argument list then do not report a violation`() {\n+ val code =\n+ \"\"\"\n+ val fooBar: FooBar = emptyList()\n+ \"\"\".trimIndent()\n+ wrappingRuleAssertThat(code)\n+ .hasNoLintViolations()\n+ }\n+\n+ @Test\n+ fun `Given that newline is missing before some type projections`() {\n+ val code =\n+ \"\"\"\n+ val fooBar: FooBar = emptyList()\n+ \"\"\".trimIndent()\n+ val formattedCode =\n+ \"\"\"\n+ val fooBar: FooBar<\n+ Foo1,\n+ Foo2,\n+ Bar1,\n+ Bar2,\n+ > = emptyList()\n+ \"\"\".trimIndent()\n+ wrappingRuleAssertThat(code)\n+ .hasLintViolations(\n+ LintViolation(1, 20, \"A newline was expected before 'Foo1'\"),\n+ LintViolation(1, 26, \"A newline was expected before 'Foo2'\"),\n+ LintViolation(2, 11, \"A newline was expected before 'Bar2'\"),\n+ ).isFormattedAs(formattedCode)\n+ }\n+\n+ @Test\n+ fun `Given that newline is missing before the closing angle bracket`() {\n+ val code =\n+ \"\"\"\n+ val fooBar: List<\n+ Bar> = emptyList()\n+ \"\"\".trimIndent()\n+ val formattedCode =\n+ \"\"\"\n+ val fooBar: List<\n+ Bar\n+ > = emptyList()\n+ \"\"\".trimIndent()\n+ wrappingRuleAssertThat(code)\n+ .hasLintViolation(2, 8, \"A newline was expected before '>'\")\n+ .isFormattedAs(formattedCode)\n+ }\n+ }\n }\n \n // Replace the \"$.\" placeholder with an actual \"$\" so that string \"$.{expression}\" is transformed to a String template\n", "problem_statement": "A type with multiple annotations inside a TypeArgumentList is not formatted correctly\nCode below:\r\n```\r\ndata class FooRequestDto(\r\n val data: List<@Valid @NotNull FooDto>,\r\n)\r\n```\r\n\r\nis formatted as:\r\n```\r\ndata class FooRequestDto(\r\n val data: List<@Valid @NotNull\r\n FooDto,>,\r\n)\r\n```\r\n\r\nKtLint: 0.47.1\r\n\r\n_Originally posted by @Vadgyik in https://github.com/pinterest/ktlint/issues/673#issuecomment-1351480443_\r\n \n", "hints_text": "When I really exaggerate the example code, it turns out that it is not so easy to find an acceptable outcome that is deterministic when formatting generic type parameters that are annotated.\r\n\r\nSuppose I have following classes and annotations:\r\n```\r\n@Target(AnnotationTarget.TYPE)\r\nannotation class Foo\r\n@Target(AnnotationTarget.TYPE)\r\nannotation class Bar1\r\n@Target(AnnotationTarget.TYPE)\r\nannotation class Bar2\r\n@Target(AnnotationTarget.TYPE)\r\nannotation class FooBarLongDescription\r\n@Target(AnnotationTarget.TYPE)\r\nannotation class ComplexAnnotationWithParameters(val string: String)\r\nclass SimpleDto\r\nclass LongerButReasonableDto\r\nclass ExtremeLooooooooooooooooooooooooooooongDto\r\nclass SomeCustomTypeWithGenerics\r\n```\r\n\r\nExample A below shows the code in which annotations are not wrapped:\r\n```\r\ndata class ExampleA(\r\n val atom: List<@Foo SimpleDto>,\r\n val simpleList: List<@Foo @FooBarLongDescription @Bar1 @Bar2 SimpleDto>,\r\n val moreComplexxxxxxxxxxxxMap: Map<@Foo @FooBarLongDescription @Bar1 @Bar2 SimpleDto, @Foo @FooBarLongDescription LongerButReasonableDto>,\r\n val veryLoooooooooooooooooooooooooongCustomType: SomeCustomTypeWithGenerics<@Foo @FooBarLongDescription @Bar1 @Bar2 SimpleDto, @Foo @FooBarLongDescription LongerButReasonableDto, @Suppress(\"AnnotationRule\") @Foo @FooBarLongDescription ExtremeLooooooooooooooooooooooooooooongDto>,\r\n)\r\n```\r\n\r\nThis can be made more readable by wrapping each generic type having multiple annotations:\r\n```\r\ndata class ExampleB(\r\n val atom: List<@Foo SimpleDto>,\r\n val simpleList:\r\n List<\r\n @Foo @FooBarLongDescription @Bar1 @Bar2 SimpleDto,\r\n >,\r\n val moreComplexxxxxxxxxxxxMap: Map<\r\n @Foo @FooBarLongDescription @Bar1 @Bar2 SimpleDto,\r\n @Foo @FooBarLongDescription LongerButReasonableDto,\r\n >,\r\n val veryLoooooooooooooooooooooooooongCustomType:\r\n SomeCustomTypeWithGenerics<\r\n @Foo @FooBarLongDescription @Bar1 @Bar2 SimpleDto,\r\n @Foo @FooBarLongDescription LongerButReasonableDto,\r\n @ComplexAnnotationWithParameters(\"foo bar foo bar foo bar foo bar foo bar foo bar foo bar\") @Foo @FooBarLongDescription ExtremeLooooooooooooooooooooooooooooongDto,\r\n >,\r\n)\r\n```\r\nA valid question with the example above is whether the same should also have be done with `atom: List<@Foo SimpleDto>`. The biggest downside of this approach is that formatting is not consistent with the way that annotations are formatted on normal parameters or classes.\r\n\r\nIf each annotation is wrapped to a separate line, the result would look like:\r\n```\r\ndata class ExampleC(\r\n val atom: List<@Foo SimpleDto>,\r\n val simpleList: List<\r\n @Foo\r\n @FooBarLongDescription\r\n @Bar1\r\n @Bar2\r\n SimpleDto\r\n >,\r\n val moreComplexxxxxxxxxxxxMap: Map<\r\n @Foo\r\n @FooBarLongDescription\r\n @Bar1\r\n @Bar2\r\n SimpleDto,\r\n @Foo\r\n @FooBarLongDescription\r\n LongerButReasonableDto\r\n >,\r\n val veryLoooooooooooooooooooooooooongCustomType: SomeCustomTypeWithGenerics<\r\n @Foo\r\n @FooBarLongDescription\r\n @Bar1\r\n @Bar2\r\n SimpleDto,\r\n @Foo\r\n @FooBarLongDescription\r\n LongerButReasonableDto,\r\n @ComplexAnnotationWithParameters(\"foo bar foo bar foo bar foo bar foo bar foo bar foo bar\")\r\n @Foo\r\n @FooBarLongDescription\r\n ExtremeLooooooooooooooooooooooooooooongDto,\r\n >,\r\n)\r\n```\r\nAdvantage is that this is consistent with other formatting. Disadvantage of course is that it is lengthy. Despite that, I am inclined to choose this formatting.\r\n\r\nBut when combined with the rule suppression mechanism, the developer could choose in specific case to use a manual formatting like below:\r\n```\r\n@Suppress(\"ktlint:annotation\")\r\ndata class ExampleD(\r\n val atom: List<@Foo SimpleDto>,\r\n val simpleList: List<@Foo @FooBarLongDescription SimpleDto>,\r\n val moreComplexxxxxxxxxxxxMap:\r\n Map<\r\n @Foo @FooBarLongDescription\r\n SimpleDto,\r\n @Foo @FooBarLongDescription\r\n LongerButReasonableDto\r\n >,\r\n val veryLoooooooooooooooooooooooooongCustomType:\r\n SomeCustomTypeWithGenerics<\r\n @Foo @FooBarLongDescription SimpleDto,\r\n @Foo @FooBarLongDescription\r\n LongerButReasonableDto,\r\n @ComplexAnnotationWithParameters(\"foo bar foo bar foo bar foo bar foo bar foo bar foo bar\")\r\n @Foo\r\n @FooBarLongDescription\r\n ExtremeLooooooooooooooooooooooooooooongDto,\r\n >,\r\n)\r\n```\r\n", "created_at": "2023-03-12T08:51:45Z", "version": "0.49", "FAIL_TO_PASS": [ "gradle_test_execution" ], "PASS_TO_PASS": [], "ERROR_TO_PASS": [], "environment_setup_commit": "410d8849874f4d3600f9d4572e0850adccce4f2d" }, { "repo": "pinterest/ktlint", "pull_number": 1859, "instance_id": "pinterest__ktlint-1859", "issue_numbers": [ "1858" ], "base_commit": "c5ec2c6aeadaf7a23612cdce5d0804c77f205ae4", "patch": "diff --git a/CHANGELOG.md b/CHANGELOG.md\nindex 65486fb6ac..fe4019cfce 100644\n--- a/CHANGELOG.md\n+++ b/CHANGELOG.md\n@@ -253,6 +253,7 @@ Previously the default value for `.editorconfig` property `max_line_length` was\n * Fix false positive when multiple KDOCs exists between a declaration and another annotated declaration `spacing-between-declarations-with-annotations` ([#1802](https://github.com/pinterest/ktlint/issues/1802))\n * Fix false positive when a single line statement containing a block having exactly the maximum line length is preceded by a blank line `wrapping` ([#1808](https://github.com/pinterest/ktlint/issues/1808))\n * Fix false positive when a single line contains multiple dot qualified expressions and/or safe expressions `indent` ([#1830](https://github.com/pinterest/ktlint/issues/1830))\n+* Enforce spacing around rangeUntil operator `..<` similar to the range operator `..` in `range-spacing` ([#1858](https://github.com/pinterest/ktlint/issues/1858))\n * When `.editorconfig` property `ij_kotlin_imports_layout` contains a `|` but no import exists that match any pattern before the first `|` then do not report a violation nor insert a blank line `import-ordering` ([#1845](https://github.com/pinterest/ktlint/issues/1845))\n \n ### Changed\ndiff --git a/ktlint-rule-engine-core/src/main/kotlin/com/pinterest/ktlint/rule/engine/core/api/ElementType.kt b/ktlint-rule-engine-core/src/main/kotlin/com/pinterest/ktlint/rule/engine/core/api/ElementType.kt\nindex 1158353d67..ee3d0ce7a6 100644\n--- a/ktlint-rule-engine-core/src/main/kotlin/com/pinterest/ktlint/rule/engine/core/api/ElementType.kt\n+++ b/ktlint-rule-engine-core/src/main/kotlin/com/pinterest/ktlint/rule/engine/core/api/ElementType.kt\n@@ -213,6 +213,7 @@ public object ElementType {\n public val SEMICOLON: IElementType = KtTokens.SEMICOLON\n public val DOUBLE_SEMICOLON: IElementType = KtTokens.DOUBLE_SEMICOLON\n public val RANGE: IElementType = KtTokens.RANGE\n+ public val RANGE_UNTIL: IElementType = KtTokens.RANGE_UNTIL\n public val EQ: IElementType = KtTokens.EQ\n public val MULTEQ: IElementType = KtTokens.MULTEQ\n public val DIVEQ: IElementType = KtTokens.DIVEQ\ndiff --git a/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/SpacingAroundRangeOperatorRule.kt b/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/SpacingAroundRangeOperatorRule.kt\nindex 0518037205..303e6088b9 100644\n--- a/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/SpacingAroundRangeOperatorRule.kt\n+++ b/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/SpacingAroundRangeOperatorRule.kt\n@@ -1,12 +1,14 @@\n package com.pinterest.ktlint.ruleset.standard.rules\n \n import com.pinterest.ktlint.rule.engine.core.api.ElementType.RANGE\n+import com.pinterest.ktlint.rule.engine.core.api.ElementType.RANGE_UNTIL\n import com.pinterest.ktlint.rule.engine.core.api.RuleId\n import com.pinterest.ktlint.rule.engine.core.api.nextLeaf\n import com.pinterest.ktlint.rule.engine.core.api.prevLeaf\n import com.pinterest.ktlint.ruleset.standard.StandardRule\n import org.jetbrains.kotlin.com.intellij.lang.ASTNode\n import org.jetbrains.kotlin.com.intellij.psi.PsiWhiteSpace\n+import org.jetbrains.kotlin.lexer.KtSingleValueToken\n \n public class SpacingAroundRangeOperatorRule : StandardRule(\"range-spacing\") {\n override fun beforeVisitChildNodes(\n@@ -14,25 +16,25 @@ public class SpacingAroundRangeOperatorRule : StandardRule(\"range-spacing\") {\n autoCorrect: Boolean,\n emit: (offset: Int, errorMessage: String, canBeAutoCorrected: Boolean) -> Unit,\n ) {\n- if (node.elementType == RANGE) {\n+ if (node.elementType == RANGE || node.elementType == RANGE_UNTIL) {\n val prevLeaf = node.prevLeaf()\n val nextLeaf = node.nextLeaf()\n when {\n prevLeaf is PsiWhiteSpace && nextLeaf is PsiWhiteSpace -> {\n- emit(node.startOffset, \"Unexpected spacing around \\\"..\\\"\", true)\n+ emit(node.startOffset, \"Unexpected spacing around \\\"${node.elementTypeDescription()}\\\"\", true)\n if (autoCorrect) {\n prevLeaf.node.treeParent.removeChild(prevLeaf.node)\n nextLeaf.node.treeParent.removeChild(nextLeaf.node)\n }\n }\n prevLeaf is PsiWhiteSpace -> {\n- emit(prevLeaf.node.startOffset, \"Unexpected spacing before \\\"..\\\"\", true)\n+ emit(prevLeaf.node.startOffset, \"Unexpected spacing before \\\"${node.elementTypeDescription()}\\\"\", true)\n if (autoCorrect) {\n prevLeaf.node.treeParent.removeChild(prevLeaf.node)\n }\n }\n nextLeaf is PsiWhiteSpace -> {\n- emit(nextLeaf.node.startOffset, \"Unexpected spacing after \\\"..\\\"\", true)\n+ emit(nextLeaf.node.startOffset, \"Unexpected spacing after \\\"${node.elementTypeDescription()}\\\"\", true)\n if (autoCorrect) {\n nextLeaf.node.treeParent.removeChild(nextLeaf.node)\n }\n@@ -40,6 +42,8 @@ public class SpacingAroundRangeOperatorRule : StandardRule(\"range-spacing\") {\n }\n }\n }\n+\n+ private fun ASTNode.elementTypeDescription() = (elementType as? KtSingleValueToken)?.value ?: elementType\n }\n \n public val SPACING_AROUND_RANGE_OPERATOR_RULE_ID: RuleId = SpacingAroundRangeOperatorRule().ruleId\n", "test_patch": "diff --git a/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/SpacingAroundRangeOperatorRuleTest.kt b/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/SpacingAroundRangeOperatorRuleTest.kt\nindex 8c13a21ffb..1b7255848f 100644\n--- a/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/SpacingAroundRangeOperatorRuleTest.kt\n+++ b/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/SpacingAroundRangeOperatorRuleTest.kt\n@@ -64,4 +64,38 @@ class SpacingAroundRangeOperatorRuleTest {\n LintViolation(5, 16, \"Unexpected spacing before \\\"..\\\"\"),\n ).isFormattedAs(formattedCode)\n }\n+\n+ @Test\n+ fun `Given a rangeUntil operator`() {\n+ val code =\n+ \"\"\"\n+ @OptIn(ExperimentalStdlibApi::class)\n+ fun foo(int: Int): String =\n+ when (int) {\n+ in 10..<20 -> \"A\"\n+ in 20..< 30 -> \"B\"\n+ in 30 ..< 40 -> \"C\"\n+ in 40 ..<50 -> \"D\"\n+ else -> \"unknown\"\n+ }\n+ \"\"\".trimIndent()\n+ val formattedCode =\n+ \"\"\"\n+ @OptIn(ExperimentalStdlibApi::class)\n+ fun foo(int: Int): String =\n+ when (int) {\n+ in 10..<20 -> \"A\"\n+ in 20..<30 -> \"B\"\n+ in 30..<40 -> \"C\"\n+ in 40..<50 -> \"D\"\n+ else -> \"unknown\"\n+ }\n+ \"\"\".trimIndent()\n+ spacingAroundRangeOperatorRuleAssertThat(code)\n+ .hasLintViolations(\n+ LintViolation(5, 17, \"Unexpected spacing after \\\"..<\\\"\"),\n+ LintViolation(6, 15, \"Unexpected spacing around \\\"..<\\\"\"),\n+ LintViolation(7, 14, \"Unexpected spacing before \\\"..<\\\"\"),\n+ ).isFormattedAs(formattedCode)\n+ }\n }\n", "problem_statement": "Spacing around `..<` should be identical to spacing around `..`\nGiven code below with inconsistent spacing around `..<`:\r\n```\r\n@OptIn(ExperimentalStdlibApi::class)\r\nfun foo(int: Int): String =\r\n when (int) {\r\n in 10..<20 -> \"A\"\r\n in 20..< 30 -> \"B\"\r\n in 30 ..< 40 -> \"C\"\r\n in 40 ..<50 -> \"D\"\r\n else -> \"unknown\"\r\n }\r\n```\r\n\r\nshould be formatted as:\r\n```\r\n@OptIn(ExperimentalStdlibApi::class)\r\nfun foo(int: Int): String =\r\n when (int) {\r\n in 10..<20 -> \"A\"\r\n in 20..<30 -> \"B\"\r\n in 30..<40 -> \"C\"\r\n in 40..<50 -> \"D\"\r\n else -> \"unknown\"\r\n }\r\n```\n", "hints_text": "", "created_at": "2023-03-14T07:18:10Z", "version": "0.49", "FAIL_TO_PASS": [ "gradle_test_execution" ], "PASS_TO_PASS": [], "ERROR_TO_PASS": [], "environment_setup_commit": "410d8849874f4d3600f9d4572e0850adccce4f2d" }, { "repo": "pinterest/ktlint", "pull_number": 2107, "instance_id": "pinterest__ktlint-2107", "issue_numbers": [ "2103" ], "base_commit": "b0b93f05f4da60141baae3dd0f6ff403d0b3bceb", "patch": "diff --git a/CHANGELOG.md b/CHANGELOG.md\nindex 4e69a2969e..6ef0db0c41 100644\n--- a/CHANGELOG.md\n+++ b/CHANGELOG.md\n@@ -10,6 +10,7 @@ This project adheres to [Semantic Versioning](https://semver.org/).\n \n ### Fixed\n \n+* Fix wrapping of nested function literals `wrapping` ([#2106](https://github.com/pinterest/ktlint/issues/2106))\n * Do not indent class body for classes having a long super type list in code style `ktlint_official` as it is inconsistent compared to other class bodies `indent` [#2115](https://github.com/pinterest/ktlint/issues/2115) \n \n ### Changed\ndiff --git a/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/WrappingRule.kt b/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/WrappingRule.kt\nindex 732ba49bd0..706001a6ea 100644\n--- a/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/WrappingRule.kt\n+++ b/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/WrappingRule.kt\n@@ -158,6 +158,7 @@ public class WrappingRule :\n ?: return\n if (lbrace.followedByNewline() ||\n lbrace.followedByEolComment() ||\n+ lbrace.followedByFunctionLiteralParameterList() ||\n lbrace.isPartOf(LONG_STRING_TEMPLATE_ENTRY)\n ) {\n // String template inside raw string literal may exceed the maximum line length\n@@ -198,6 +199,12 @@ public class WrappingRule :\n .takeWhile { it.isWhiteSpaceWithoutNewline() || it.elementType == EOL_COMMENT }\n .firstOrNull { it.elementType == EOL_COMMENT }\n \n+ private fun ASTNode.followedByFunctionLiteralParameterList() =\n+ VALUE_PARAMETER_LIST ==\n+ takeIf { treeParent.elementType == FUNCTION_LITERAL }\n+ ?.nextCodeSibling()\n+ ?.elementType\n+\n private fun rearrangeBlock(\n node: ASTNode,\n autoCorrect: Boolean,\n@@ -425,8 +432,6 @@ public class WrappingRule :\n }\n }\n }\n-\n- Unit\n }\n }\n \n@@ -676,6 +681,7 @@ public class WrappingRule :\n ?: return\n node\n .getEndOfBlock()\n+ ?.takeIf { it.elementType == RBRACE }\n ?.takeUnless { it.isPrecededByNewline() }\n ?.let { rbrace ->\n if (hasNewLineInClosedRange(lbrace, rbrace)) {\n@@ -695,28 +701,36 @@ public class WrappingRule :\n private fun ASTNode.isPrecededByNewline() = prevLeaf().isWhiteSpaceWithNewline()\n \n private fun ASTNode.getStartOfBlock() =\n- firstChildLeafOrSelf()\n- .let { node ->\n- if (node.elementType == LBRACE) {\n- // WHEN-entry block have LBRACE and RBRACE as first and last elements\n- node\n- } else {\n- // Other blocks have LBRACE and RBRACE as siblings of the block\n- node.prevLeaf { !it.isPartOfComment() && !it.isWhiteSpace() }\n+ if (treeParent.elementType == FUNCTION_LITERAL) {\n+ treeParent.findChildByType(LBRACE)\n+ } else {\n+ firstChildLeafOrSelf()\n+ .let { node ->\n+ if (node.elementType == LBRACE) {\n+ // WHEN-entry block have LBRACE and RBRACE as first and last elements\n+ node\n+ } else {\n+ // Other blocks have LBRACE and RBRACE as siblings of the block\n+ node.prevSibling { !it.isPartOfComment() && !it.isWhiteSpace() }\n+ }\n }\n- }\n+ }\n \n private fun ASTNode.getEndOfBlock() =\n- lastChildLeafOrSelf()\n- .let { node ->\n- if (node.elementType == RBRACE && treeParent.elementType != FUNCTION_LITERAL) {\n- // WHEN-entry block have LBRACE and RBRACE as first and last elements\n- node\n- } else {\n- // Other blocks have LBRACE and RBRACE as siblings of the block\n- node.nextLeaf { !it.isPartOfComment() && !it.isWhiteSpace() }\n+ if (treeParent.elementType == FUNCTION_LITERAL) {\n+ treeParent.findChildByType(RBRACE)\n+ } else {\n+ lastChildLeafOrSelf()\n+ .let { node ->\n+ if (node.elementType == RBRACE) {\n+ // WHEN-entry block have LBRACE and RBRACE as first and last elements\n+ node\n+ } else {\n+ // Other blocks have LBRACE and RBRACE as siblings of the block\n+ node.nextSibling { !it.isPartOfComment() && !it.isWhiteSpace() }\n+ }\n }\n- }\n+ }\n \n private companion object {\n private val LTOKEN_SET = TokenSet.create(LPAR, LBRACE, LBRACKET, LT)\n", "test_patch": "diff --git a/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/WrappingRuleTest.kt b/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/WrappingRuleTest.kt\nindex 0d047bed59..a9bec73a4a 100644\n--- a/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/WrappingRuleTest.kt\n+++ b/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/WrappingRuleTest.kt\n@@ -2629,6 +2629,18 @@ internal class WrappingRuleTest {\n \"\"\".trimIndent()\n wrappingRuleAssertThat(code).hasNoLintViolations()\n }\n+\n+ @Test\n+ fun `Given a nested function literal`() {\n+ val code =\n+ \"\"\"\n+ val foo =\n+ bar {\n+ { Foobar() }\n+ }\n+ \"\"\".trimIndent()\n+ wrappingRuleAssertThat(code).hasNoLintViolations()\n+ }\n }\n \n // Replace the \"$.\" placeholder with an actual \"$\" so that string \"$.{expression}\" is transformed to a String template\n", "problem_statement": "Unexpected indentation level after newline with 0.50.0\nWith version 0.50.0, the below code now produces an error because of the lack of newline after the {:\r\n```\r\n{ size -> icon?.getBitmap(size)?.await() }\r\n```\r\nWhat seems odd to me is that the \"correct\" formatting looks like the below:\r\n```\r\n{\r\n size ->\r\n icon?.getBitmap(size)?.await()\r\n}\r\n```\r\nThis plays out the same for larger code blocks as well where the first line after the bracket is indented further over than all subsequent ones if there's a separator involved. It seems to me that if anything, we'd want to invert that indentation to something more like:\r\n```\r\n{\r\n size ->\r\n icon?.getBitmap(size)?.await()\r\n}\r\n```\n", "hints_text": "This problem has the same root cause as #2106 and will be fixed via that issue.\r\n\r\nThe double indentation of parameters inside the lambda looks indeed weird at first sight. It is based on (but not identical to) the default formatting of IntelliJ IDEA.\r\n\r\nGiven the functional literal below (note that it contains multiple parameters on separate lines):\r\n```\r\nval foo = { a,\r\n b,\r\n c ->\r\n doSomething()\r\n}\r\n```\r\nIt is formatted by IntelliJ IDEA formatter as:\r\n```\r\nval foo = { a,\r\n b,\r\n c ->\r\n doSomething()\r\n}\r\n```\r\nAnalog to formatting of functions having parameters on separate lines, ktlint formats this as:\r\n```\r\nval foo = {\r\n a,\r\n b,\r\n c ->\r\n doSomething()\r\n}\r\n```\r\n\r\nThe format above should only be applied when having a function literal with parameters on separate lines. As result of the bug in #2101, your parameter list was wrapped and as of that changed into a multiline parameter list. As a result of that, the indentation of a multiline parameter list was applied. With fix of #2106 you original code sample will be kept unchanged.", "created_at": "2023-07-03T12:49:59Z", "version": "0.50", "FAIL_TO_PASS": [ "gradle_test_execution" ], "PASS_TO_PASS": [], "ERROR_TO_PASS": [], "environment_setup_commit": "0a2500665d514f27ad06828544c43a6f28924426" }, { "repo": "pinterest/ktlint", "pull_number": 1779, "instance_id": "pinterest__ktlint-1779", "issue_numbers": [ "1776" ], "base_commit": "c158350a25c59cc2b58af32f5fe6e7beaa33a4c7", "patch": "diff --git a/CHANGELOG.md b/CHANGELOG.md\nindex 0695bd9c4b..ea4b034ebb 100644\n--- a/CHANGELOG.md\n+++ b/CHANGELOG.md\n@@ -11,6 +11,7 @@ This project adheres to [Semantic Versioning](https://semver.org/).\n ### Fixed\n * Do not enable the experimental rules by default when `.editorconfig` properties `disabled_rules` or `ktlint_disabled_rules` are set. ([#1771](https://github.com/pinterest/ktlint/issues/1771))\n * A function signature not having any parameters which exceeds the `max-line-length` should be ignored by rule `function-signature` ([#1773](https://github.com/pinterest/ktlint/issues/1773))\n+* \n \n ### Changed\n \ndiff --git a/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/WrappingRule.kt b/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/WrappingRule.kt\nindex 167cc1323a..061a5c071e 100644\n--- a/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/WrappingRule.kt\n+++ b/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/WrappingRule.kt\n@@ -31,6 +31,7 @@ import com.pinterest.ktlint.core.ast.ElementType.LT\n import com.pinterest.ktlint.core.ast.ElementType.OBJECT_LITERAL\n import com.pinterest.ktlint.core.ast.ElementType.RBRACE\n import com.pinterest.ktlint.core.ast.ElementType.RBRACKET\n+import com.pinterest.ktlint.core.ast.ElementType.REGULAR_STRING_PART\n import com.pinterest.ktlint.core.ast.ElementType.RPAR\n import com.pinterest.ktlint.core.ast.ElementType.STRING_TEMPLATE\n import com.pinterest.ktlint.core.ast.ElementType.SUPER_TYPE_CALL_ENTRY\n@@ -142,8 +143,8 @@ public class WrappingRule :\n node.firstChildLeafOrSelf().elementType != EOL_COMMENT\n }\n maxLineLength > 0 -> {\n- val startOfLine = node.prevLeaf { it.isWhiteSpaceWithNewline() }\n- val endOfLine = node.nextLeaf { it.isWhiteSpaceWithNewline() }\n+ val startOfLine = node.prevLeaf { it.isWhiteSpaceWithNewline() || (it.elementType == REGULAR_STRING_PART && it.text == \"\\n\") }\n+ val endOfLine = node.nextLeaf { it.isWhiteSpaceWithNewline() || (it.elementType == REGULAR_STRING_PART && it.text == \"\\n\") }\n val line =\n startOfLine\n ?.leaves()\n", "test_patch": "diff --git a/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/WrappingRuleTest.kt b/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/WrappingRuleTest.kt\nindex 6fbbf99f32..2e485ec2d7 100644\n--- a/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/WrappingRuleTest.kt\n+++ b/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/WrappingRuleTest.kt\n@@ -1715,6 +1715,70 @@ internal class WrappingRuleTest {\n \"\"\".trimIndent()\n wrappingRuleAssertThat(code).hasNoLintViolations()\n }\n+\n+ @Nested\n+ inner class `Issue 1776 - Given a string template containing a block` {\n+ @Test\n+ fun `Given that the string template is on a separate line in the raw string literal`() {\n+ val code =\n+ \"\"\"\n+ // $MAX_LINE_LENGTH_MARKER $EOL_CHAR\n+ fun getQueryString(query: QueryRequest): String {\n+ val q = $MULTILINE_STRING_QUOTE\n+ SELECT *\n+ FROM table\n+ WHERE 1 = 1\n+ $.{query.gameId?.let { \"AND id = ?\" } ?: \"\"}\n+ $MULTILINE_STRING_QUOTE\n+ return q\n+ }\n+ \"\"\".replacePlaceholderWithStringTemplate()\n+ .trimIndent()\n+ wrappingRuleAssertThat(code)\n+ .setMaxLineLength()\n+ .hasNoLintViolations()\n+ }\n+\n+ @Test\n+ fun `Given that the string template is preceded by some text on the same line in the raw string literal`() {\n+ val code =\n+ \"\"\"\n+ // $MAX_LINE_LENGTH_MARKER $EOL_CHAR\n+ fun getQueryString(query: QueryRequest): String {\n+ val q = $MULTILINE_STRING_QUOTE\n+ SELECT *\n+ FROM table\n+ WHERE $.{query.gameId?.let { \"id = ?\" } ?: \"1 = 1\"}\n+ $MULTILINE_STRING_QUOTE\n+ return q\n+ }\n+ \"\"\".replacePlaceholderWithStringTemplate()\n+ .trimIndent()\n+ wrappingRuleAssertThat(code)\n+ .setMaxLineLength()\n+ .hasNoLintViolations()\n+ }\n+\n+ @Test\n+ fun `Given that the string template is followed by some text on the same line in the raw string literal`() {\n+ val code =\n+ \"\"\"\n+ // $MAX_LINE_LENGTH_MARKER $EOL_CHAR\n+ fun getQueryString(query: QueryRequest): String {\n+ val q = $MULTILINE_STRING_QUOTE\n+ SELECT *\n+ FROM table\n+ WHERE $.{query.gameId?.let { \"id = ?\" } ?: \"1 = 1\"} OR level = ?\n+ $MULTILINE_STRING_QUOTE\n+ return q\n+ }\n+ \"\"\".replacePlaceholderWithStringTemplate()\n+ .trimIndent()\n+ wrappingRuleAssertThat(code)\n+ .setMaxLineLength()\n+ .hasNoLintViolations()\n+ }\n+ }\n }\n \n // Replace the \"$.\" placeholder with an actual \"$\" so that string \"$.{expression}\" is transformed to a String template\n", "problem_statement": "`wrapping`: raw string false positive `Missing newline after \"{\"`\nI have some code using `let` blocks inside raw strings, something like:\r\n```\r\npackage test\r\n\r\nclass QueryGenerator {\r\n fun getQueryString(query: QueryRequest): String {\r\n val q = \"\"\"\r\n SELECT *\r\n FROM table\r\n WHERE 1 = 1\r\n ${query.gameId?.let { \"AND id = ?\" } ?: \"\"} \r\n \"\"\"\r\n return q\r\n }\r\n}\r\n\r\ndata class QueryRequest(\r\n val gameId: String?,\r\n)\r\n```\r\n\r\n## Expected Behavior\r\nThis should cause no violations of the `wrapping` rule, regardless of the string size.\r\n\r\n## Observed Behavior\r\nIn the code above, if I replace `table` by `table_name_long_enough_so_max_line_length_is_met_and_wrapping_rule_is_violated_and_generates_an_error`, for example (anything that makes the raw string size go above `max_line_length` seems to work), then I start seeing:\r\n```\r\nQueryGenerator.kt:9:34: Missing newline after \"{\" (wrapping)\r\n```\r\n\r\n## Steps to Reproduce\r\n1. Start with the code above\r\n2. Make the raw string big enough\r\n3. Run ktlint 0.48+ in the file\r\n\r\n## Your Environment\r\n\r\n* Version of ktlint used: 0.48.1\r\n* Relevant parts of the `.editorconfig` settings: `max_line_length = 160`\r\n* Name and version (or code for custom task) of integration used (Gradle plugin, Maven plugin, command line, custom Gradle task): ktlint CLI\r\n* Operating System and version: Arch Linux (rolling as of 2023-01-15)\r\n\n", "hints_text": "This issue is very tricky to reproduce, actually, this might not be related to `max_line_length` at all. I just tried moving the entire content of the raw string to a single line and the error is gone, even with a very long raw string.\r\nThe exact values I provided causes the issue 100% of the times I tried, though, so I hope that's enough to reproduce the issue on your side.\nCan be reproduced. The error is introduced in `0.48.x`.\nThanks for the quick reply :)\r\nThis is my only blocker to update to 0.48, so let me know if I can help with anything.\nYou can try to solve this issue via a PR ;-)\r\n\r\nOtherwise. just disable the rule (https://pinterest.github.io/ktlint/faq/#how-do-i-suppress-errors-for-a-lineblockfile) and start using the new version.", "created_at": "2023-01-15T18:52:56Z", "version": "0.49", "FAIL_TO_PASS": [ "gradle_test_execution" ], "PASS_TO_PASS": [], "ERROR_TO_PASS": [], "environment_setup_commit": "410d8849874f4d3600f9d4572e0850adccce4f2d" }, { "repo": "pinterest/ktlint", "pull_number": 2116, "instance_id": "pinterest__ktlint-2116", "issue_numbers": [ "2115" ], "base_commit": "5fd06a28a42fa02ba6e3cf8bc3c2a232a41c516d", "patch": "diff --git a/CHANGELOG.md b/CHANGELOG.md\nindex 447660124e..4e69a2969e 100644\n--- a/CHANGELOG.md\n+++ b/CHANGELOG.md\n@@ -10,6 +10,8 @@ This project adheres to [Semantic Versioning](https://semver.org/).\n \n ### Fixed\n \n+* Do not indent class body for classes having a long super type list in code style `ktlint_official` as it is inconsistent compared to other class bodies `indent` [#2115](https://github.com/pinterest/ktlint/issues/2115) \n+\n ### Changed\n \n * Update dependency gradle to v8.2 ([#2105](https://github.com/pinterest/ktlint/pull/2105))\ndiff --git a/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/IndentationRule.kt b/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/IndentationRule.kt\nindex 39ae35af94..71e7a66898 100644\n--- a/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/IndentationRule.kt\n+++ b/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/IndentationRule.kt\n@@ -19,6 +19,7 @@ import com.pinterest.ktlint.rule.engine.core.api.ElementType.CLOSING_QUOTE\n import com.pinterest.ktlint.rule.engine.core.api.ElementType.COLON\n import com.pinterest.ktlint.rule.engine.core.api.ElementType.CONDITION\n import com.pinterest.ktlint.rule.engine.core.api.ElementType.CONSTRUCTOR_DELEGATION_CALL\n+import com.pinterest.ktlint.rule.engine.core.api.ElementType.CONSTRUCTOR_KEYWORD\n import com.pinterest.ktlint.rule.engine.core.api.ElementType.CONTEXT_RECEIVER_LIST\n import com.pinterest.ktlint.rule.engine.core.api.ElementType.DELEGATED_SUPER_TYPE_ENTRY\n import com.pinterest.ktlint.rule.engine.core.api.ElementType.DESTRUCTURING_DECLARATION\n@@ -605,12 +606,17 @@ public class IndentationRule :\n }\n \n val primaryConstructor = node.findChildByType(PRIMARY_CONSTRUCTOR)\n- if (codeStyle == ktlint_official && primaryConstructor != null) {\n+ val containsConstructorKeyword = primaryConstructor?.findChildByType(CONSTRUCTOR_KEYWORD) != null\n+ if (codeStyle == ktlint_official && primaryConstructor != null && containsConstructorKeyword) {\n // Indent both constructor and super type list\n nextToAstNode =\n startIndentContext(\n fromAstNode = primaryConstructor.getPrecedingLeadingCommentsAndWhitespaces(),\n- toAstNode = nextToAstNode,\n+ toAstNode =\n+ node\n+ .findChildByType(SUPER_TYPE_LIST)\n+ ?.lastChildLeafOrSelf()\n+ ?: nextToAstNode,\n ).prevCodeLeaf()\n } else {\n node\n", "test_patch": "diff --git a/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/IndentationRuleTest.kt b/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/IndentationRuleTest.kt\nindex fe5372a8d5..64966e8204 100644\n--- a/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/IndentationRuleTest.kt\n+++ b/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/IndentationRuleTest.kt\n@@ -4958,22 +4958,13 @@ internal class IndentationRuleTest {\n indentationRuleAssertThat(code).hasNoLintViolations()\n }\n \n- @Test\n- fun `Issue 1916 - Given a class declaration with an annotation before the constructor`() {\n- val code =\n- \"\"\"\n- class Foo\n- @Bar1 @Bar2\n- constructor(\n- foo1: Foo1,\n- foo2: Foo2,\n- ) {\n- fun foo() = \"foo\"\n- }\n- \"\"\".trimIndent()\n- val formattedCode =\n- \"\"\"\n- class Foo\n+ @Nested\n+ inner class `Issue 1916, issue 2115 - Given the ktlint_official code style and a class declaration with an annotated constructor` {\n+ @Test\n+ fun `Issue 1916, issue 2115 - Given a class declaration with an annotation before the constructor keyword`() {\n+ val code =\n+ \"\"\"\n+ class Foo\n @Bar1 @Bar2\n constructor(\n foo1: Foo1,\n@@ -4981,39 +4972,36 @@ internal class IndentationRuleTest {\n ) {\n fun foo() = \"foo\"\n }\n- \"\"\".trimIndent()\n- indentationRuleAssertThat(code)\n- .withEditorConfigOverride(CODE_STYLE_PROPERTY to ktlint_official)\n- .hasLintViolations(\n- LintViolation(2, 1, \"Unexpected indentation (0) (should be 4)\"),\n- LintViolation(3, 1, \"Unexpected indentation (0) (should be 4)\"),\n- LintViolation(4, 1, \"Unexpected indentation (4) (should be 8)\"),\n- LintViolation(5, 1, \"Unexpected indentation (4) (should be 8)\"),\n- LintViolation(6, 1, \"Unexpected indentation (0) (should be 4)\"),\n- LintViolation(7, 1, \"Unexpected indentation (4) (should be 8)\"),\n- LintViolation(8, 1, \"Unexpected indentation (0) (should be 4)\"),\n- ).isFormattedAs(formattedCode)\n- }\n+ \"\"\".trimIndent()\n+ val formattedCode =\n+ \"\"\"\n+ class Foo\n+ @Bar1 @Bar2\n+ constructor(\n+ foo1: Foo1,\n+ foo2: Foo2,\n+ ) {\n+ fun foo() = \"foo\"\n+ }\n+ \"\"\".trimIndent()\n+ indentationRuleAssertThat(code)\n+ .withEditorConfigOverride(CODE_STYLE_PROPERTY to ktlint_official)\n+ .hasLintViolations(\n+ LintViolation(2, 1, \"Unexpected indentation (0) (should be 4)\"),\n+ LintViolation(3, 1, \"Unexpected indentation (0) (should be 4)\"),\n+ LintViolation(4, 1, \"Unexpected indentation (4) (should be 8)\"),\n+ LintViolation(5, 1, \"Unexpected indentation (4) (should be 8)\"),\n+ LintViolation(6, 1, \"Unexpected indentation (0) (should be 4)\"),\n+ LintViolation(7, 1, \"Unexpected indentation (4) (should be 8)\"),\n+ LintViolation(8, 1, \"Unexpected indentation (0) (should be 4)\"),\n+ ).isFormattedAs(formattedCode)\n+ }\n \n- @Test\n- fun `Issue 1916 - Given a class declaration with an annotation before the constructor nad having a super type list`() {\n- val code =\n- \"\"\"\n- class Foo\n- @Bar1 @Bar2\n- constructor(\n- foo1: Foo1,\n- foo2: Foo2,\n- ) : Foobar(\n- \"foobar1\",\n- \"foobar2\",\n- ) {\n- fun foo() = \"foo\"\n- }\n- \"\"\".trimIndent()\n- val formattedCode =\n- \"\"\"\n- class Foo\n+ @Test\n+ fun `Issue 1916, issue 2115 - Given a class declaration with an annotation before the constructor and having a single super type`() {\n+ val code =\n+ \"\"\"\n+ class Foo\n @Bar1 @Bar2\n constructor(\n foo1: Foo1,\n@@ -5024,21 +5012,96 @@ internal class IndentationRuleTest {\n ) {\n fun foo() = \"foo\"\n }\n- \"\"\".trimIndent()\n- indentationRuleAssertThat(code)\n- .withEditorConfigOverride(CODE_STYLE_PROPERTY to ktlint_official)\n- .hasLintViolations(\n- LintViolation(2, 1, \"Unexpected indentation (0) (should be 4)\"),\n- LintViolation(3, 1, \"Unexpected indentation (0) (should be 4)\"),\n- LintViolation(4, 1, \"Unexpected indentation (4) (should be 8)\"),\n- LintViolation(5, 1, \"Unexpected indentation (4) (should be 8)\"),\n- LintViolation(6, 1, \"Unexpected indentation (0) (should be 4)\"),\n- LintViolation(7, 1, \"Unexpected indentation (4) (should be 8)\"),\n- LintViolation(8, 1, \"Unexpected indentation (4) (should be 8)\"),\n- LintViolation(9, 1, \"Unexpected indentation (0) (should be 4)\"),\n- LintViolation(10, 1, \"Unexpected indentation (4) (should be 8)\"),\n- LintViolation(11, 1, \"Unexpected indentation (0) (should be 4)\"),\n- ).isFormattedAs(formattedCode)\n+ \"\"\".trimIndent()\n+ val formattedCode =\n+ \"\"\"\n+ class Foo\n+ @Bar1 @Bar2\n+ constructor(\n+ foo1: Foo1,\n+ foo2: Foo2,\n+ ) : Foobar(\n+ \"foobar1\",\n+ \"foobar2\",\n+ ) {\n+ fun foo() = \"foo\"\n+ }\n+ \"\"\".trimIndent()\n+ indentationRuleAssertThat(code)\n+ .withEditorConfigOverride(CODE_STYLE_PROPERTY to ktlint_official)\n+ .hasLintViolations(\n+ LintViolation(2, 1, \"Unexpected indentation (0) (should be 4)\"),\n+ LintViolation(3, 1, \"Unexpected indentation (0) (should be 4)\"),\n+ LintViolation(4, 1, \"Unexpected indentation (4) (should be 8)\"),\n+ LintViolation(5, 1, \"Unexpected indentation (4) (should be 8)\"),\n+ LintViolation(6, 1, \"Unexpected indentation (0) (should be 4)\"),\n+ LintViolation(7, 1, \"Unexpected indentation (4) (should be 8)\"),\n+ LintViolation(8, 1, \"Unexpected indentation (4) (should be 8)\"),\n+ LintViolation(9, 1, \"Unexpected indentation (0) (should be 4)\"),\n+ ).isFormattedAs(formattedCode)\n+ }\n+\n+ @Test\n+ fun `Issue 1916, issue 2115 - Given a class declaration with an annotation before the constructor and having multiple super types`() {\n+ val code =\n+ \"\"\"\n+ class Foo\n+ @Bar1 @Bar2\n+ constructor(\n+ foo1: Foo1,\n+ foo2: Foo2,\n+ ) : Foobar1(\n+ \"foobar1\",\n+ \"foobar2\",\n+ ), FooBar2 {\n+ fun foo() = \"foo\"\n+ }\n+ \"\"\".trimIndent()\n+ val formattedCode =\n+ \"\"\"\n+ class Foo\n+ @Bar1 @Bar2\n+ constructor(\n+ foo1: Foo1,\n+ foo2: Foo2,\n+ ) : Foobar1(\n+ \"foobar1\",\n+ \"foobar2\",\n+ ), FooBar2 {\n+ fun foo() = \"foo\"\n+ }\n+ \"\"\".trimIndent()\n+ indentationRuleAssertThat(code)\n+ .withEditorConfigOverride(CODE_STYLE_PROPERTY to ktlint_official)\n+ .hasLintViolations(\n+ LintViolation(2, 1, \"Unexpected indentation (0) (should be 4)\"),\n+ LintViolation(3, 1, \"Unexpected indentation (0) (should be 4)\"),\n+ LintViolation(4, 1, \"Unexpected indentation (4) (should be 8)\"),\n+ LintViolation(5, 1, \"Unexpected indentation (4) (should be 8)\"),\n+ LintViolation(6, 1, \"Unexpected indentation (0) (should be 4)\"),\n+ LintViolation(7, 1, \"Unexpected indentation (4) (should be 8)\"),\n+ LintViolation(8, 1, \"Unexpected indentation (4) (should be 8)\"),\n+ LintViolation(9, 1, \"Unexpected indentation (0) (should be 4)\"),\n+ ).isFormattedAs(formattedCode)\n+ }\n+\n+ @Test\n+ fun `Issue 2115 - Given a class without an explicit constructor and with a long super type list then do not indent the class body`() {\n+ val code =\n+ \"\"\"\n+ class Foo(\n+ val bar1: Bar,\n+ val bar2: Bar,\n+ ) : FooBar(bar1, bar2),\n+ BarFoo1,\n+ BarFoo2 {\n+ // body\n+ }\n+ \"\"\".trimIndent()\n+ indentationRuleAssertThat(code)\n+ .withEditorConfigOverride(CODE_STYLE_PROPERTY to ktlint_official)\n+ .hasNoLintViolations()\n+ }\n }\n \n @Test\n", "problem_statement": "Indentation class body when class has multiline super type list (ktlint_official only)\n#1916 fixed the wrapping of an explicit constructor for code style `ktlint_official`. Code like below:\r\n```\r\nclass Foo\r\n@Bar1 @Bar2\r\nconstructor(\r\n foo1: Foo1,\r\n foo2: Foo2,\r\n) : Foobar(\r\n \"foobar1\",\r\n \"foobar2\",\r\n) {\r\n fun foo() = \"foo\"\r\n}\r\n```\r\nis formatted as:\r\n```\r\nclass Foo\r\n @Bar1 @Bar2\r\n constructor(\r\n foo1: Foo1,\r\n foo2: Foo2,\r\n ) : Foobar(\r\n \"foobar1\",\r\n \"foobar2\",\r\n ) {\r\n fun foo() = \"foo\"\r\n }\r\n```\r\n\r\nThe identation of the class body however is unwanted as it also affects classes not using the explicit `constructor` keyword.\r\n\r\nExample:\r\n```\r\nclass Foo(\r\n val bar1: Bar,\r\n val bar2: Bar,\r\n) : FooBar(bar1, bar2),\r\n BarFoo1,\r\n BarFoo2 {\r\n // body\r\n}\r\n```\r\nis formatted with `0.50.0` as:\r\n```\r\nclass Foo(\r\n val bar1: Bar,\r\n val bar2: Bar,\r\n) : FooBar(bar1, bar2),\r\n BarFoo1,\r\n BarFoo2 {\r\n // body\r\n }\r\n```\r\nwhile it would be expected that the original format was kept.\r\n\r\nAlso classes having an explicit `constructor` and a long super type list are not indented correctly:\r\n```\r\nclass Foo\r\n constructor(\r\n val bar1: Bar,\r\n val bar2: Bar,\r\n ) : FooBar(bar1, bar2),\r\n BarFoo1,\r\n BarFoo2 {\r\n // body\r\n}\r\n```\r\nis formatted as:\r\n```\r\nclass Foo\r\n constructor(\r\n val bar1: Bar,\r\n val bar2: Bar,\r\n ) : FooBar(bar1, bar2),\r\n BarFoo1,\r\n BarFoo2 {\r\n // body\r\n }\r\n```\r\n\n", "hints_text": "", "created_at": "2023-07-07T10:53:40Z", "version": "0.50", "FAIL_TO_PASS": [ "gradle_test_execution" ], "PASS_TO_PASS": [], "ERROR_TO_PASS": [], "environment_setup_commit": "0a2500665d514f27ad06828544c43a6f28924426" }, { "repo": "pinterest/ktlint", "pull_number": 1796, "instance_id": "pinterest__ktlint-1796", "issue_numbers": [ "1786" ], "base_commit": "87153ae1ec9ee211aab6ee4c8e8d345039ebcdf5", "patch": "diff --git a/CHANGELOG.md b/CHANGELOG.md\nindex a72391445e..32cf0eb7f7 100644\n--- a/CHANGELOG.md\n+++ b/CHANGELOG.md\n@@ -2,6 +2,18 @@\n All notable changes to this project will be documented in this file.\n This project adheres to [Semantic Versioning](https://semver.org/).\n \n+## Unreleased\n+\n+### Added\n+\n+### Removed\n+\n+### Fixed\n+\n+* Do not report an \"unnecessary semicolon\" after adding a trailing comma to an enum class containing a code element after the last enum entry `trailing-comma-on-declaration-site` ([#1786](https://github.com/pinterest/ktlint/issues/1786))\n+\n+### Changed\n+\n ## [0.48.2] - 2023-01-21\n \n ### Additional clarification on API Changes in `0.48.0` and `0.48.1`\ndiff --git a/RELEASING.md b/RELEASING.md\nindex 019e463b50..79c19e938e 100644\n--- a/RELEASING.md\n+++ b/RELEASING.md\n@@ -13,4 +13,15 @@ Note: These steps should be done directly in the pinterest/ktlint repository, no\n 7. Add a tag with the new release version, and push it directly to remote (e.g. `git tag 0.50.0 && git push origin 0.50.0`). This will kick off the [Release workflow](https://github.com/pinterest/ktlint/actions/workflows/release.yml).\n 9. Close and release the repo on Sonatype. (Only Pinterest employees can do this.)\n 10. Find the `-update-refs` branch in the repo (created by the `.announce` script) and merge it.\n-11. Update `gradle.properties` with the new `SNAPSHOT` version, and add a new empty `Unreleased` section to the top of `CHANGELOG.md` and commit. (This can be done directly in the main repo or in your fork.)\n+11. Update `gradle.properties` with the new `SNAPSHOT` version, and add the section below to the top of `CHANGELOG.md` and commit. (This can be done directly in the main repo or in your fork.)\n+```markdown\n+## Unreleased\n+\n+### Added\n+\n+### Removed\n+\n+### Fixed\n+\n+### Changed\n+```\ndiff --git a/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/TrailingCommaOnDeclarationSiteRule.kt b/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/TrailingCommaOnDeclarationSiteRule.kt\nindex 3035e5f2f0..5dc91ba628 100644\n--- a/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/TrailingCommaOnDeclarationSiteRule.kt\n+++ b/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/TrailingCommaOnDeclarationSiteRule.kt\n@@ -311,6 +311,7 @@ public class TrailingCommaOnDeclarationSiteRule :\n }\n }\n \n+ val comma = KtPsiFactory(prevNode.psi).createComma()\n if (inspectNode.treeParent.elementType == ElementType.ENUM_ENTRY) {\n with(KtPsiFactory(prevNode.psi)) {\n val parentIndent =\n@@ -319,15 +320,15 @@ public class TrailingCommaOnDeclarationSiteRule :\n val newline = createWhiteSpace(parentIndent)\n val enumEntry = inspectNode.treeParent.psi\n enumEntry.apply {\n+ inspectNode.psi.replace(comma)\n add(newline)\n- removeChild(inspectNode)\n- parent.addAfter(createSemicolon(), this)\n+ add(createSemicolon())\n }\n }\n+ Unit\n+ } else {\n+ prevNode.psi.parent.addAfter(comma, prevNode.psi)\n }\n-\n- val comma = KtPsiFactory(prevNode.psi).createComma()\n- prevNode.psi.parent.addAfter(comma, prevNode.psi)\n }\n }\n TrailingCommaState.REDUNDANT -> {\n", "test_patch": "diff --git a/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/TrailingCommaOnDeclarationSiteRuleTest.kt b/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/TrailingCommaOnDeclarationSiteRuleTest.kt\nindex 50b80aff64..e1734e8eaa 100644\n--- a/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/TrailingCommaOnDeclarationSiteRuleTest.kt\n+++ b/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/TrailingCommaOnDeclarationSiteRuleTest.kt\n@@ -990,4 +990,47 @@ class TrailingCommaOnDeclarationSiteRuleTest {\n .withEditorConfigOverride(TRAILING_COMMA_ON_DECLARATION_SITE_PROPERTY to true)\n .hasNoLintViolations()\n }\n+\n+ @Test\n+ fun `Issue 1786 - Given an enumeration containing a companion object, and that a trailing comma is inserted then do not report a unnecessary semicolon`() {\n+ val code =\n+ \"\"\"\n+ enum class TestEnum() {\n+ A,\n+ B;\n+\n+ companion object {\n+ const val A_NUMBER = 1L\n+ }\n+ }\n+ \"\"\".trimIndent()\n+ val formattedCode =\n+ \"\"\"\n+ enum class TestEnum() {\n+ A,\n+ B,\n+ ;\n+\n+ companion object {\n+ const val A_NUMBER = 1L\n+ }\n+ }\n+ \"\"\".trimIndent()\n+ val noSemicolonsRuleAssertThat =\n+ KtLintAssertThat.assertThatRule(\n+ provider = { NoSemicolonsRule() },\n+ additionalRuleProviders = setOf(\n+ // WrappingRule must be loaded in order to run TrailingCommaOnCallSiteRule\n+ RuleProvider { WrappingRule() },\n+ // Apply the IndentationRule always as additional rule, so that the formattedCode in the unit test looks\n+ // correct.\n+ RuleProvider { IndentationRule() },\n+ RuleProvider { TrailingCommaOnDeclarationSiteRule() },\n+ ),\n+ )\n+ noSemicolonsRuleAssertThat(code)\n+ .withEditorConfigOverride(TRAILING_COMMA_ON_DECLARATION_SITE_PROPERTY to true)\n+ .hasNoLintViolationsForRuleId(\"no-semi\")\n+ .isFormattedAs(formattedCode)\n+ }\n }\ndiff --git a/ktlint-test/src/main/kotlin/com/pinterest/ktlint/test/KtLintAssertThat.kt b/ktlint-test/src/main/kotlin/com/pinterest/ktlint/test/KtLintAssertThat.kt\nindex b611132d6d..080a23b077 100644\n--- a/ktlint-test/src/main/kotlin/com/pinterest/ktlint/test/KtLintAssertThat.kt\n+++ b/ktlint-test/src/main/kotlin/com/pinterest/ktlint/test/KtLintAssertThat.kt\n@@ -157,6 +157,12 @@ public class KtLintAssertThat(\n */\n public fun hasNoLintViolations(): Unit = ktLintAssertThatAssertable().hasNoLintViolations()\n \n+ /**\n+ * Asserts that the code does not contain any [LintViolation]s for a given rule id.\n+ */\n+ public fun hasNoLintViolationsForRuleId(ruleId: String): KtLintAssertThatAssertable =\n+ ktLintAssertThatAssertable().hasNoLintViolationsForRuleId(ruleId)\n+\n /**\n * Asserts that the code does not contain any [LintViolation]s except in the additional formatting rules.\n *\n@@ -354,6 +360,19 @@ public class KtLintAssertThatAssertable(\n )\n }\n \n+ /**\n+ * Asserts that the code does not contain any [LintViolation]s for the given rule id.\n+ */\n+ public fun hasNoLintViolationsForRuleId(ruleId: String): KtLintAssertThatAssertable {\n+ val (_, lintErrorsWhenFormatting) = format()\n+\n+ assertThat(lintErrorsWhenFormatting.filter { it.ruleId == ruleId })\n+ .describedAs(\"At least 1 lint violation was found for rule id '$ruleId' while none were expected\")\n+ .isEmpty()\n+\n+ return this\n+ }\n+\n /**\n * Asserts that the code does not contain any [LintViolation]s except in the additional formatting rules.\n *\n", "problem_statement": " Formatting enum class with member definition and missing trailing commas causes rule violations on first run\n## Expected Behavior\r\n\r\n\r\n\r\n\r\n\r\nWhen formatting and validating the following enum class, the ktlint command should exit successfully (status `0`):\r\n\r\n```kotlin\r\nenum class TestEnum() {\r\n A,\r\n B;\r\n\r\n companion object {\r\n const val A_NUMBER = 1L\r\n }\r\n}\r\n```\r\n\r\n## Observed Behavior\r\n\r\n\r\n\r\n\r\n\r\nWhen running ktlint on the above enum class, it is formatted correctly, but the run fails with rule violations (exit status `1`):\r\n```bash\r\n$ ktlint --format \r\n17:25:00.694 [main] INFO com.pinterest.ktlint.internal.KtlintCommandLine - Enable default patterns [**/*.kt, **/*.kts]\r\n/home/karl/tasks/ktlint-issue-example/TestEnum.kt:1:1: Missing trailing comma before \"}\" (trailing-comma-on-declaration-site)\r\n/home/karl/tasks/ktlint-issue-example/TestEnum.kt:5:4: Unnecessary semicolon (no-semi)\r\n\r\nSummary error count (descending) by rule:\r\n no-semi: 1\r\n trailing-comma-on-declaration-site: 1\r\nExit status: 1 \r\n```\r\n\r\nI note that the line number for the `no-semi` violation is the line number after formatting.\r\n\r\nA second run on the (now properly formatted) code runs correctly (exit status `0`):\r\n```bash\r\n$ ktlint --format\r\n17:25:05.397 [main] INFO com.pinterest.ktlint.internal.KtlintCommandLine - Enable default patterns [**/*.kt, **/*.kts]\r\nExit status: 0\r\n```\r\n\r\n## Steps to Reproduce\r\nRun command on above enum class:\r\n```ktlint --format```\r\n\r\n## Your Environment\r\n\r\n* Version of ktlint used: 0.48.1\r\n* Operating System and version: Arch Linux\r\n\n", "hints_text": "I have the same issue\r\n\nSee release notes of 0.48.0:\r\n> * The default value for trailing comma's on call site is changed to `true` unless the `android codestyle` is enabled. Note that KtLint from a consistency viewpoint *enforces* the trailing comma on call site while default IntelliJ IDEA formatting only *allows* the trailing comma but leaves it up to the developer's discretion. ([#1670](https://github.com/pinterest/ktlint/pull/1670))\r\n\n@paul-dingemans I don't quite follow. My issue is that after doing formatting, ktlint reports invalid `no-semi` and `trailing-comma-on-declaration-site` rule violations. A subsequent run of ktlint (correctly) passes the same code.\r\n\nAh now I see. Although it is not visual in the textual representation of the code, the trailing comma is not inserted at the correct place in the AST representation of the code. I will try to fix it.", "created_at": "2023-01-28T12:35:06Z", "version": "0.49", "FAIL_TO_PASS": [ "gradle_test_execution" ], "PASS_TO_PASS": [], "ERROR_TO_PASS": [], "environment_setup_commit": "410d8849874f4d3600f9d4572e0850adccce4f2d" }, { "repo": "pinterest/ktlint", "pull_number": 2049, "instance_id": "pinterest__ktlint-2049", "issue_numbers": [ "2043" ], "base_commit": "55bab3d5f1d416a4f9fcd6bcaebbfb4977217559", "patch": "diff --git a/CHANGELOG.md b/CHANGELOG.md\nindex 8722a8cdd1..b0e0cf7f53 100644\n--- a/CHANGELOG.md\n+++ b/CHANGELOG.md\n@@ -11,6 +11,7 @@ This project adheres to [Semantic Versioning](https://semver.org/).\n ### Fixed\n \n * Do not flag a (potential) mutable extension property in case the getter is annotated or prefixed with a modifier `property-naming` ([#2024](https://github.com/pinterest/ktlint/issues/2024))\n+* Do not merge an annotated expression body with the function signature even if it fits on a single line ([#2043](https://github.com/pinterest/ktlint/issues/2043))\n \n ### Changed\n \ndiff --git a/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/FunctionSignatureRule.kt b/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/FunctionSignatureRule.kt\nindex 28a6ebc722..f2dee473c6 100644\n--- a/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/FunctionSignatureRule.kt\n+++ b/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/FunctionSignatureRule.kt\n@@ -1,5 +1,6 @@\n package com.pinterest.ktlint.ruleset.standard.rules\n \n+import com.pinterest.ktlint.rule.engine.core.api.ElementType.ANNOTATED_EXPRESSION\n import com.pinterest.ktlint.rule.engine.core.api.ElementType.ANNOTATION\n import com.pinterest.ktlint.rule.engine.core.api.ElementType.ANNOTATION_ENTRY\n import com.pinterest.ktlint.rule.engine.core.api.ElementType.BLOCK\n@@ -540,6 +541,13 @@ public class FunctionSignatureRule :\n .firstOrNull()\n ?.also { firstLineOfBodyExpression ->\n if (whiteSpaceBeforeFunctionBodyExpression.isWhiteSpaceWithNewline()) {\n+ lastNodeOfFunctionSignatureWithBodyExpression\n+ .nextCodeSibling()\n+ .takeIf { it?.elementType == ANNOTATED_EXPRESSION }\n+ ?.let {\n+ // Never merge an annotated expression body with function signature as this conflicts with the Annotation rule\n+ return\n+ }\n val mergeWithFunctionSignature =\n if (firstLineOfBodyExpression.length < maxLengthRemainingForFirstLineOfBodyExpression) {\n functionBodyExpressionWrapping == default ||\n", "test_patch": "diff --git a/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/FunctionSignatureRuleTest.kt b/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/FunctionSignatureRuleTest.kt\nindex 661faffdac..b3eebad07e 100644\n--- a/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/FunctionSignatureRuleTest.kt\n+++ b/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/FunctionSignatureRuleTest.kt\n@@ -6,6 +6,8 @@ import com.pinterest.ktlint.rule.engine.core.api.editorconfig.CodeStyleValue.ktl\n import com.pinterest.ktlint.rule.engine.core.api.editorconfig.ec4j.toPropertyWithValue\n import com.pinterest.ktlint.ruleset.standard.rules.FunctionSignatureRule.Companion.FORCE_MULTILINE_WHEN_PARAMETER_COUNT_GREATER_OR_EQUAL_THAN_PROPERTY\n import com.pinterest.ktlint.ruleset.standard.rules.FunctionSignatureRule.Companion.FUNCTION_BODY_EXPRESSION_WRAPPING_PROPERTY\n+import com.pinterest.ktlint.ruleset.standard.rules.FunctionSignatureRule.FunctionBodyExpressionWrapping\n+import com.pinterest.ktlint.ruleset.standard.rules.FunctionSignatureRule.FunctionBodyExpressionWrapping.default\n import com.pinterest.ktlint.test.KtLintAssertThat.Companion.EOL_CHAR\n import com.pinterest.ktlint.test.KtLintAssertThat.Companion.MAX_LINE_LENGTH_MARKER\n import com.pinterest.ktlint.test.KtLintAssertThat.Companion.assertThatRule\n@@ -671,11 +673,11 @@ class FunctionSignatureRuleTest {\n inner class BodyExpressionOnSameLine {\n @ParameterizedTest(name = \"bodyExpressionWrapping: {0}\")\n @EnumSource(\n- value = FunctionSignatureRule.FunctionBodyExpressionWrapping::class,\n+ value = FunctionBodyExpressionWrapping::class,\n names = [\"default\", \"multiline\"],\n )\n fun `Given that the function signature and a single line body expression body fit on the same line then do not reformat function signature or body expression`(\n- bodyExpressionWrapping: FunctionSignatureRule.FunctionBodyExpressionWrapping,\n+ bodyExpressionWrapping: FunctionBodyExpressionWrapping,\n ) {\n val code =\n \"\"\"\n@@ -690,11 +692,11 @@ class FunctionSignatureRuleTest {\n \n @ParameterizedTest(name = \"bodyExpressionWrapping: {0}\")\n @EnumSource(\n- value = FunctionSignatureRule.FunctionBodyExpressionWrapping::class,\n+ value = FunctionBodyExpressionWrapping::class,\n names = [\"always\"],\n )\n fun `Given that the function signature and a single line body expression body fit on the same line then do not reformat function signature but move the body expression to a separate line`(\n- bodyExpressionWrapping: FunctionSignatureRule.FunctionBodyExpressionWrapping,\n+ bodyExpressionWrapping: FunctionBodyExpressionWrapping,\n ) {\n val code =\n \"\"\"\n@@ -717,11 +719,11 @@ class FunctionSignatureRuleTest {\n \n @ParameterizedTest(name = \"bodyExpressionWrapping: {0}\")\n @EnumSource(\n- value = FunctionSignatureRule.FunctionBodyExpressionWrapping::class,\n+ value = FunctionBodyExpressionWrapping::class,\n names = [\"multiline\", \"always\"],\n )\n fun `Given that the function signature and first line of a multiline body expression body fit on the same line then do not reformat the function signature, move the body expression to a separate line`(\n- bodyExpressionWrapping: FunctionSignatureRule.FunctionBodyExpressionWrapping,\n+ bodyExpressionWrapping: FunctionBodyExpressionWrapping,\n ) {\n val code =\n \"\"\"\n@@ -750,11 +752,11 @@ class FunctionSignatureRuleTest {\n inner class BodyExpressionOnSeparateLine {\n @ParameterizedTest(name = \"bodyExpressionWrapping: {0}\")\n @EnumSource(\n- value = FunctionSignatureRule.FunctionBodyExpressionWrapping::class,\n+ value = FunctionBodyExpressionWrapping::class,\n names = [\"default\", \"multiline\"],\n )\n fun `Given that the function signature and a single line body expression body fit on the same line then do reformat as single line signature`(\n- bodyExpressionWrapping: FunctionSignatureRule.FunctionBodyExpressionWrapping,\n+ bodyExpressionWrapping: FunctionBodyExpressionWrapping,\n ) {\n val code =\n \"\"\"\n@@ -784,11 +786,11 @@ class FunctionSignatureRuleTest {\n \n @ParameterizedTest(name = \"bodyExpressionWrapping: {0}\")\n @EnumSource(\n- value = FunctionSignatureRule.FunctionBodyExpressionWrapping::class,\n+ value = FunctionBodyExpressionWrapping::class,\n names = [\"default\", \"multiline\", \"always\"],\n )\n fun `Given that the function signature and first line of a multi line body expression body do not fit on the same line then do reformat`(\n- bodyExpressionWrapping: FunctionSignatureRule.FunctionBodyExpressionWrapping,\n+ bodyExpressionWrapping: FunctionBodyExpressionWrapping,\n ) {\n val code =\n \"\"\"\n@@ -818,11 +820,11 @@ class FunctionSignatureRuleTest {\n \n @ParameterizedTest(name = \"bodyExpressionWrapping: {0}\")\n @EnumSource(\n- value = FunctionSignatureRule.FunctionBodyExpressionWrapping::class,\n+ value = FunctionBodyExpressionWrapping::class,\n names = [\"multiline\", \"always\"],\n )\n fun `Given that the function signature and the first line of a multi line body expression body fit on the same line then reformat to single line signature but keep body expression on separate line`(\n- bodyExpressionWrapping: FunctionSignatureRule.FunctionBodyExpressionWrapping,\n+ bodyExpressionWrapping: FunctionBodyExpressionWrapping,\n ) {\n val code =\n \"\"\"\n@@ -854,11 +856,11 @@ class FunctionSignatureRuleTest {\n \n @ParameterizedTest(name = \"bodyExpressionWrapping: {0}\")\n @EnumSource(\n- value = FunctionSignatureRule.FunctionBodyExpressionWrapping::class,\n+ value = FunctionBodyExpressionWrapping::class,\n names = [\"default\"],\n )\n fun `Given that the function signature and first line of a multiline body expression body fit on the same line then do reformat as single line signature`(\n- bodyExpressionWrapping: FunctionSignatureRule.FunctionBodyExpressionWrapping,\n+ bodyExpressionWrapping: FunctionBodyExpressionWrapping,\n ) {\n val code =\n \"\"\"\n@@ -890,11 +892,11 @@ class FunctionSignatureRuleTest {\n \n @ParameterizedTest(name = \"bodyExpressionWrapping: {0}\")\n @EnumSource(\n- value = FunctionSignatureRule.FunctionBodyExpressionWrapping::class,\n+ value = FunctionBodyExpressionWrapping::class,\n names = [\"always\"],\n )\n fun `Given that the function signature and first line of a multiline body expression body fit on the same line then do reformat as single line signature, keep the body expression on a separate line`(\n- bodyExpressionWrapping: FunctionSignatureRule.FunctionBodyExpressionWrapping,\n+ bodyExpressionWrapping: FunctionBodyExpressionWrapping,\n ) {\n val code =\n \"\"\"\n@@ -927,10 +929,10 @@ class FunctionSignatureRuleTest {\n \n @ParameterizedTest(name = \"bodyExpressionWrapping: {0}\")\n @EnumSource(\n- value = FunctionSignatureRule.FunctionBodyExpressionWrapping::class,\n+ value = FunctionBodyExpressionWrapping::class,\n )\n fun `Given a multiline function signature without explicit return type and start of body expression on next line then keep first line of body expression body on the same line as the last line of the function signature`(\n- bodyExpressionWrapping: FunctionSignatureRule.FunctionBodyExpressionWrapping,\n+ bodyExpressionWrapping: FunctionBodyExpressionWrapping,\n ) {\n val code =\n \"\"\"\n@@ -961,10 +963,10 @@ class FunctionSignatureRuleTest {\n \n @ParameterizedTest(name = \"bodyExpressionWrapping: {0}\")\n @EnumSource(\n- value = FunctionSignatureRule.FunctionBodyExpressionWrapping::class,\n+ value = FunctionBodyExpressionWrapping::class,\n )\n fun `Given a multiline function signature without explicit return type and start of body expression on same line as last line of function signature then do not reformat`(\n- bodyExpressionWrapping: FunctionSignatureRule.FunctionBodyExpressionWrapping,\n+ bodyExpressionWrapping: FunctionBodyExpressionWrapping,\n ) {\n val code =\n \"\"\"\n@@ -1244,6 +1246,23 @@ class FunctionSignatureRuleTest {\n .hasNoLintViolations()\n }\n \n+ @Test\n+ fun `Issue 2043 - Given a function signature with an expression body that is an annotated expression then do not reformat to single line function signature`() {\n+ val code =\n+ \"\"\"\n+ // $MAX_LINE_LENGTH_MARKER $EOL_CHAR\n+ fun foo1(bar: String): String =\n+ @Bar\n+ bar\n+ fun foo2(bar: String): String =\n+ @Bar bar\n+ \"\"\".trimIndent()\n+ functionSignatureWrappingRuleAssertThat(code)\n+ .setMaxLineLength()\n+ .withEditorConfigOverride(FUNCTION_BODY_EXPRESSION_WRAPPING_PROPERTY to default)\n+ .hasNoLintViolations()\n+ }\n+\n private companion object {\n const val UNEXPECTED_SPACES = \" \"\n const val NO_SPACE = \"\"\n", "problem_statement": "Do not merge annotated expression with function signature rule\nGiven code below:\r\n```\r\nprivate fun getErrorMessage(value: String): String =\r\n @Suppress(\"DEPRECATION\")\r\n customMessage.takeUnless { it.isEmpty() } ?: String.format(DEFAULT_ERROR_MESSAGE_WITH_NO_REASON, value)\r\n```\r\n*and* assume that the `function-signature` rule is enabled *and* the (first line of the) function body expression has to be merged with the function signature.\r\n\r\nFor example with `.editorconfig`:\r\n```\r\n[{*.kt,*.kts}]\r\nktlint_code_style = android\r\nktlint_standard=enabled\r\nktlint_experimental=enabled\r\n```\r\nthe command `ktlint --relative` results in\r\n```\r\n17:41:39.417 [main] INFO com.pinterest.ktlint.cli.internal.KtlintCommandLine - Enable default patterns [**/*.kt, **/*.kts]\r\nx.kts:6:97: Unnecessary trailing comma before \")\" (standard:trailing-comma-on-call-site)\r\nsrc/main/kotlin/Foo.kt:1:53: First line of body expression fits on same line as function signature (standard:function-signature)\r\nsrc/main/kotlin/Foo.kt:3:1: Exceeded max line length (100) (standard:max-line-length)\r\nsrc/main/kotlin/Foo.kt:3:31: Missing newline after \"{\" (standard:wrapping)\r\nsrc/main/kotlin/Foo.kt:3:46: Expected newline (standard:annotation)\r\nsrc/main/kotlin/Foo.kt:3:64: Argument should be on a separate line (unless all arguments can fit a single line) (standard:argument-list-wrapping)\r\nsrc/main/kotlin/Foo.kt:3:102: Argument should be on a separate line (unless all arguments can fit a single line) (standard:argument-list-wrapping)\r\nsrc/main/kotlin/Foo.kt:3:107: Missing newline before \")\" (standard:argument-list-wrapping)\r\n\r\nSummary error count (descending) by rule:\r\n standard:argument-list-wrapping: 3\r\n standard:annotation: 1\r\n standard:function-signature: 1\r\n standard:max-line-length: 1\r\n standard:trailing-comma-on-call-site: 1\r\n standard:wrapping: 1\r\n```\r\nWhen running `format` the output changes to:\r\n```\r\n17:44:18.369 [main] INFO com.pinterest.ktlint.cli.internal.KtlintCommandLine - Enable default patterns [**/*.kt, **/*.kts]\r\nsrc/main/kotlin/Foo.kt:1:53: Expected newline before annotation (standard:annotation)\r\n\r\nSummary error count (descending) by rule:\r\n standard:annotation: 1\r\n```\r\nThis log message is rather confusing when you compare it with the original code sample. However, it should not be compared with the original but with the modified code to make sense.\r\nand the file is formatted as:\r\n```\r\nprivate fun getErrorMessage(value: String): String = @Suppress(\"DEPRECATION\")\r\ncustomMessage.takeUnless { it.isEmpty() }\r\n ?: String.format(DEFAULT_ERROR_MESSAGE_WITH_NO_REASON, value)\r\n```\r\n\r\nThe `function-signature` should not format in such a way that if violates the `annotation` rule.\r\n\r\n_Originally posted by @paul-dingemans in https://github.com/pinterest/ktlint/issues/2028#issuecomment-1551678889_\r\n \n", "hints_text": "", "created_at": "2023-05-20T13:01:30Z", "version": "0.49", "FAIL_TO_PASS": [ "gradle_test_execution" ], "PASS_TO_PASS": [], "ERROR_TO_PASS": [], "environment_setup_commit": "410d8849874f4d3600f9d4572e0850adccce4f2d" }, { "repo": "pinterest/ktlint", "pull_number": 1780, "instance_id": "pinterest__ktlint-1780", "issue_numbers": [ "1757" ], "base_commit": "1bf9c4612c1e6b8bdd35c87245cae2e6dbbf9906", "patch": "diff --git a/CHANGELOG.md b/CHANGELOG.md\nindex 7f60cd257c..eec18ea0c2 100644\n--- a/CHANGELOG.md\n+++ b/CHANGELOG.md\n@@ -57,6 +57,7 @@ If you do want to ignore the value of `ktlint_experimental` as set by the user,\n * Fix with array-syntax annotations on the same line as other annotations `annotation` ([#1765](https://github.com/pinterest/ktlint/issues/1765))\n * Do not enable the experimental rules by default when `.editorconfig` properties `disabled_rules` or `ktlint_disabled_rules` are set. ([#1771](https://github.com/pinterest/ktlint/issues/1771))\n * A function signature not having any parameters which exceeds the `max-line-length` should be ignored by rule `function-signature` ([#1773](https://github.com/pinterest/ktlint/issues/1773))\n+* Allow diacritics in names of classes, functions packages, and properties `class-naming`, `function-naming`, `package-name`, `property-naming` ([#1757](https://github.com/pinterest/ktlint/issues/1757))\n * Prevent violation of `file-name` rule on code snippets ([#1768](https://github.com/pinterest/ktlint/issues/1768))\n * Clarify that API Consumers have to enable experimental rules ([#1768](https://github.com/pinterest/ktlint/issues/1768))\n * Trim spaces in the `.editorconfig` property `ij_kotlin_imports_layout`'s entries ([#1770](https://github.com/pinterest/ktlint/pull/1770))\ndiff --git a/ktlint-ruleset-experimental/src/main/kotlin/com/pinterest/ktlint/ruleset/experimental/ClassNamingRule.kt b/ktlint-ruleset-experimental/src/main/kotlin/com/pinterest/ktlint/ruleset/experimental/ClassNamingRule.kt\nindex 1d2b695e61..0ba69536d7 100644\n--- a/ktlint-ruleset-experimental/src/main/kotlin/com/pinterest/ktlint/ruleset/experimental/ClassNamingRule.kt\n+++ b/ktlint-ruleset-experimental/src/main/kotlin/com/pinterest/ktlint/ruleset/experimental/ClassNamingRule.kt\n@@ -5,6 +5,7 @@ import com.pinterest.ktlint.core.ast.ElementType\n import com.pinterest.ktlint.core.ast.ElementType.CLASS\n import com.pinterest.ktlint.core.ast.ElementType.IDENTIFIER\n import com.pinterest.ktlint.core.ast.ElementType.OBJECT_DECLARATION\n+import com.pinterest.ktlint.ruleset.experimental.internal.regExIgnoringDiacriticsAndStrokesOnLetters\n import org.jetbrains.kotlin.com.intellij.lang.ASTNode\n \n /**\n@@ -51,7 +52,7 @@ public class ClassNamingRule : Rule(\"$EXPERIMENTAL_RULE_SET_ID:class-naming\") {\n text.matches(BACK_TICKED_FUNCTION_NAME_REGEXP)\n \n private companion object {\n- val VALID_CLASS_NAME_REGEXP = Regex(\"[A-Z][A-Za-z\\\\d]*\")\n+ val VALID_CLASS_NAME_REGEXP = \"[A-Z][A-Za-z\\\\d]*\".regExIgnoringDiacriticsAndStrokesOnLetters()\n val BACK_TICKED_FUNCTION_NAME_REGEXP = Regex(\"`.*`\")\n }\n }\ndiff --git a/ktlint-ruleset-experimental/src/main/kotlin/com/pinterest/ktlint/ruleset/experimental/FunctionNamingRule.kt b/ktlint-ruleset-experimental/src/main/kotlin/com/pinterest/ktlint/ruleset/experimental/FunctionNamingRule.kt\nindex 45c5904024..473ee008eb 100644\n--- a/ktlint-ruleset-experimental/src/main/kotlin/com/pinterest/ktlint/ruleset/experimental/FunctionNamingRule.kt\n+++ b/ktlint-ruleset-experimental/src/main/kotlin/com/pinterest/ktlint/ruleset/experimental/FunctionNamingRule.kt\n@@ -4,6 +4,7 @@ import com.pinterest.ktlint.core.Rule\n import com.pinterest.ktlint.core.ast.ElementType.FUN\n import com.pinterest.ktlint.core.ast.ElementType.IDENTIFIER\n import com.pinterest.ktlint.core.ast.ElementType.IMPORT_DIRECTIVE\n+import com.pinterest.ktlint.ruleset.experimental.internal.regExIgnoringDiacriticsAndStrokesOnLetters\n import org.jetbrains.kotlin.com.intellij.lang.ASTNode\n import org.jetbrains.kotlin.psi.KtFunction\n import org.jetbrains.kotlin.psi.KtImportDirective\n@@ -68,8 +69,8 @@ public class FunctionNamingRule : Rule(\"$EXPERIMENTAL_RULE_SET_ID:function-namin\n .matches(VALID_FUNCTION_NAME_REGEXP)\n \n private companion object {\n- val VALID_FUNCTION_NAME_REGEXP = Regex(\"[a-z][A-Za-z\\\\d]*\")\n- val VALID_TEST_FUNCTION_NAME_REGEXP = Regex(\"(`.*`)|([a-z][A-Za-z\\\\d_]*)\")\n+ val VALID_FUNCTION_NAME_REGEXP = \"[a-z][A-Za-z\\\\d]*\".regExIgnoringDiacriticsAndStrokesOnLetters()\n+ val VALID_TEST_FUNCTION_NAME_REGEXP = \"(`.*`)|([a-z][A-Za-z\\\\d_]*)\".regExIgnoringDiacriticsAndStrokesOnLetters()\n private const val KOTLIN_TEST = \"kotlin.test\"\n private const val ORG_JUNIT = \"org.junit\"\n private const val ORG_TESTNG = \"org.testng\"\ndiff --git a/ktlint-ruleset-experimental/src/main/kotlin/com/pinterest/ktlint/ruleset/experimental/PropertyNamingRule.kt b/ktlint-ruleset-experimental/src/main/kotlin/com/pinterest/ktlint/ruleset/experimental/PropertyNamingRule.kt\nindex 4b434e296b..591229dfd1 100644\n--- a/ktlint-ruleset-experimental/src/main/kotlin/com/pinterest/ktlint/ruleset/experimental/PropertyNamingRule.kt\n+++ b/ktlint-ruleset-experimental/src/main/kotlin/com/pinterest/ktlint/ruleset/experimental/PropertyNamingRule.kt\n@@ -13,6 +13,7 @@ import com.pinterest.ktlint.core.ast.ElementType.PROPERTY\n import com.pinterest.ktlint.core.ast.ElementType.PROPERTY_ACCESSOR\n import com.pinterest.ktlint.core.ast.ElementType.VAL_KEYWORD\n import com.pinterest.ktlint.core.ast.children\n+import com.pinterest.ktlint.ruleset.experimental.internal.regExIgnoringDiacriticsAndStrokesOnLetters\n import org.jetbrains.kotlin.com.intellij.lang.ASTNode\n import org.jetbrains.kotlin.com.intellij.psi.tree.IElementType\n \n@@ -136,8 +137,8 @@ public class PropertyNamingRule : Rule(\"$EXPERIMENTAL_RULE_SET_ID:property-namin\n .any { it.text == identifier }\n \n private companion object {\n- val LOWER_CAMEL_CASE_REGEXP = Regex(\"[a-z][a-zA-Z0-9]*\")\n- val SCREAMING_SNAKE_CASE_REGEXP = Regex(\"[A-Z][_A-Z0-9]*\")\n- val BACKING_PROPERTY_LOWER_CAMEL_CASE_REGEXP = Regex(\"_[a-z][a-zA-Z0-9]*\")\n+ val LOWER_CAMEL_CASE_REGEXP = \"[a-z][a-zA-Z0-9]*\".regExIgnoringDiacriticsAndStrokesOnLetters()\n+ val SCREAMING_SNAKE_CASE_REGEXP = \"[A-Z][_A-Z0-9]*\".regExIgnoringDiacriticsAndStrokesOnLetters()\n+ val BACKING_PROPERTY_LOWER_CAMEL_CASE_REGEXP = \"_[a-z][a-zA-Z0-9]*\".regExIgnoringDiacriticsAndStrokesOnLetters()\n }\n }\ndiff --git a/ktlint-ruleset-experimental/src/main/kotlin/com/pinterest/ktlint/ruleset/experimental/internal/RegExIgnoringDiacriticsAndStrokesOnLetters.kt b/ktlint-ruleset-experimental/src/main/kotlin/com/pinterest/ktlint/ruleset/experimental/internal/RegExIgnoringDiacriticsAndStrokesOnLetters.kt\nnew file mode 100644\nindex 0000000000..577376592a\n--- /dev/null\n+++ b/ktlint-ruleset-experimental/src/main/kotlin/com/pinterest/ktlint/ruleset/experimental/internal/RegExIgnoringDiacriticsAndStrokesOnLetters.kt\n@@ -0,0 +1,11 @@\n+package com.pinterest.ktlint.ruleset.experimental.internal\n+\n+/**\n+ * Transforms a string containing regular expression ranges like \"A-Z\" and \"a-z\" to a RegEx which checks whether a\n+ * unicode character has an uppercase versus a lowercase mapping to a letter. This function intents to keep the original\n+ * expression more readable\n+ */\n+internal fun String.regExIgnoringDiacriticsAndStrokesOnLetters() =\n+ replace(\"A-Z\", \"\\\\p{Lu}\")\n+ .replace(\"a-z\", \"\\\\p{Ll}\")\n+ .toRegex()\ndiff --git a/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/PackageNameRule.kt b/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/PackageNameRule.kt\nindex c492c24d9a..e96e4f4d1f 100644\n--- a/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/PackageNameRule.kt\n+++ b/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/PackageNameRule.kt\n@@ -4,6 +4,7 @@ import com.pinterest.ktlint.core.Rule\n import com.pinterest.ktlint.core.ast.ElementType\n import com.pinterest.ktlint.core.ast.ElementType.PACKAGE_DIRECTIVE\n import com.pinterest.ktlint.core.ast.nextCodeSibling\n+import com.pinterest.ktlint.ruleset.standard.internal.regExIgnoringDiacriticsAndStrokesOnLetters\n import org.jetbrains.kotlin.com.intellij.lang.ASTNode\n \n /**\n@@ -33,6 +34,6 @@ public class PackageNameRule : Rule(\"package-name\") {\n }\n \n private companion object {\n- val VALID_PACKAGE_NAME_REGEXP = Regex(\"[a-z_][a-zA-Z\\\\d_]*(\\\\.[a-z_][a-zA-Z\\\\d_]*)*\")\n+ val VALID_PACKAGE_NAME_REGEXP = \"[a-z_][a-zA-Z\\\\d_]*(\\\\.[a-z_][a-zA-Z\\\\d_]*)*\".regExIgnoringDiacriticsAndStrokesOnLetters()\n }\n }\n", "test_patch": "diff --git a/ktlint-ruleset-experimental/src/test/kotlin/com/pinterest/ktlint/ruleset/experimental/ClassNamingRuleTest.kt b/ktlint-ruleset-experimental/src/test/kotlin/com/pinterest/ktlint/ruleset/experimental/ClassNamingRuleTest.kt\nindex f48666c71c..dc43739946 100644\n--- a/ktlint-ruleset-experimental/src/test/kotlin/com/pinterest/ktlint/ruleset/experimental/ClassNamingRuleTest.kt\n+++ b/ktlint-ruleset-experimental/src/test/kotlin/com/pinterest/ktlint/ruleset/experimental/ClassNamingRuleTest.kt\n@@ -140,4 +140,13 @@ class ClassNamingRuleTest {\n classNamingRuleAssertThat(code).hasNoLintViolations()\n }\n }\n+\n+ @Test\n+ fun `Issue 1757 - Given a class name containing diacritics is allowed`() {\n+ val code =\n+ \"\"\"\n+ class \u0178\u00e8\u015bTh\u00eesIsAllowed123\n+ \"\"\".trimIndent()\n+ classNamingRuleAssertThat(code).hasNoLintViolations()\n+ }\n }\ndiff --git a/ktlint-ruleset-experimental/src/test/kotlin/com/pinterest/ktlint/ruleset/experimental/FunctionNamingRuleTest.kt b/ktlint-ruleset-experimental/src/test/kotlin/com/pinterest/ktlint/ruleset/experimental/FunctionNamingRuleTest.kt\nindex 905e9c11e1..178d4142b8 100644\n--- a/ktlint-ruleset-experimental/src/test/kotlin/com/pinterest/ktlint/ruleset/experimental/FunctionNamingRuleTest.kt\n+++ b/ktlint-ruleset-experimental/src/test/kotlin/com/pinterest/ktlint/ruleset/experimental/FunctionNamingRuleTest.kt\n@@ -140,4 +140,39 @@ class FunctionNamingRuleTest {\n \"\"\".trimIndent()\n functionNamingRuleAssertThat(code).hasNoLintViolations()\n }\n+\n+ @Test\n+ fun `Issue 1757 - Given a function name containing diacritics then do not report a violation on the diacritics`() {\n+ val code =\n+ \"\"\"\n+ fun \u00ff\u00e8\u015bTh\u00eesIsAllowed123() = \"foo\"\n+ \"\"\".trimIndent()\n+ functionNamingRuleAssertThat(code).hasNoLintViolations()\n+ }\n+\n+ @ParameterizedTest(name = \"Junit import: {0}\")\n+ @ValueSource(\n+ strings = [\n+ \"org.junit.jupiter.api.Test\",\n+ \"org.junit.jupiter.api.*\",\n+ \"org.junit.jupiter.*\",\n+ \"org.junit.*\",\n+ \"kotlin.test.*\",\n+ \"org.testng.*\",\n+ ],\n+ )\n+ fun `Given file which imports a class from the JUnit Jupiter then do not emit`(\n+ import: String,\n+ ) {\n+ val code =\n+ \"\"\"\n+ import $import\n+\n+ class FunTest {\n+ @Test\n+ fun `\u0178\u00e8\u015b th\u00ees is allowed 123`() {}\n+ }\n+ \"\"\".trimIndent()\n+ functionNamingRuleAssertThat(code).hasNoLintViolations()\n+ }\n }\ndiff --git a/ktlint-ruleset-experimental/src/test/kotlin/com/pinterest/ktlint/ruleset/experimental/PropertyNamingRuleTest.kt b/ktlint-ruleset-experimental/src/test/kotlin/com/pinterest/ktlint/ruleset/experimental/PropertyNamingRuleTest.kt\nindex f2096b2957..a7e5684845 100644\n--- a/ktlint-ruleset-experimental/src/test/kotlin/com/pinterest/ktlint/ruleset/experimental/PropertyNamingRuleTest.kt\n+++ b/ktlint-ruleset-experimental/src/test/kotlin/com/pinterest/ktlint/ruleset/experimental/PropertyNamingRuleTest.kt\n@@ -41,6 +41,7 @@ class PropertyNamingRuleTest {\n \"\"\"\n const val foo = \"foo\"\n const val FOO_BAR_2 = \"foo-bar-2\"\n+ const val \u0178\u00c8\u0160_TH\u00ceS_IS_ALLOWED_123 = \"Yes this is allowed\"\n \"\"\".trimIndent()\n propertyNamingRuleAssertThat(code)\n .hasLintViolationWithoutAutoCorrect(1, 11, \"Property name should use the screaming snake case notation when the value can not be changed\")\n@@ -106,9 +107,23 @@ class PropertyNamingRuleTest {\n val code =\n \"\"\"\n class Foo {\n- private val _element2List = mutableListOf()\n+ private val _elementList = mutableListOf()\n \n- val element2List: List\n+ val elementList: List\n+ get() = _elementList\n+ }\n+ \"\"\".trimIndent()\n+ propertyNamingRuleAssertThat(code).hasNoLintViolations()\n+ }\n+\n+ @Test\n+ fun `Given a backing val property name containing diacritics having a custom get function and not in screaming case notation then do not emit`() {\n+ val code =\n+ \"\"\"\n+ class Foo {\n+ private val _element\u0141\u00ee\u0161t = mutableListOf()\n+\n+ val element\u0141\u00ee\u0161t: List\n get() = _elementList\n }\n \"\"\".trimIndent()\ndiff --git a/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/PackageNameRuleTest.kt b/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/PackageNameRuleTest.kt\nindex 763b5907e2..cee6cafe5d 100644\n--- a/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/PackageNameRuleTest.kt\n+++ b/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/PackageNameRuleTest.kt\n@@ -90,4 +90,13 @@ class PackageNameRuleTest {\n \"\"\".trimIndent()\n packageNameRuleAssertThat(code).hasNoLintViolations()\n }\n+\n+ @Test\n+ fun `Issue 1757 - Given a package name containing diacritics then do no report a violation`() {\n+ val code =\n+ \"\"\"\n+ package \u00ff\u00e8\u015b.th\u00ees.can.be.used\n+ \"\"\".trimIndent()\n+ packageNameRuleAssertThat(code).hasNoLintViolations()\n+ }\n }\n", "problem_statement": "0.48.0 does not allow nordic chars \u00e5\u00e4\u00f6\u00e5\u00e6\u00f8 in package-names\nWhen upgrading from 0.47.1 to 0.48.0, ktlint complains on package names containing \u00e5\u00e6\u00f8.\r\n\r\n## Expected Behavior\r\nExpecting \u00e6\u00f8\u00e5 to be accepted\r\n\r\n## Observed Behavior\r\n` Package name contains a disallowed character (cannot be auto-corrected) (package-name)`\r\n\r\n## Steps to Reproduce\r\nCreate class `Bar` in package with name `f\u00f8\u00f8` and run `mvn antrun:run@ktlint`\r\n\r\n## Your Environment\r\n\r\n* Version of ktlint used: 0.48.0\r\n* Relevant parts of the `.editorconfig` settings\r\n* Name and version (or code for custom task) of integration used (Gradle plugin, Maven plugin, command line, custom Gradle task): Apache Maven 3.8.1\r\n* Operating System and version: macOS Ventura 13.1\n", "hints_text": "Similar to https://github.com/pinterest/ktlint/issues/1530\nMore problems like this are likely to occur in this release. `0.48.0` contains some rules which formerly where experimental but now have been added to the `standard` rules. Also new `experimental` naming rules have been added in `0.48.x`. Can you please run ktlint with `--experimental` once to identify which of the newly added experimental rules also break on nordic characters?\nIt seems like it also fails on property-, class- and function-names containing nordic characters when running with experimental rules:\r\n\r\n`Property name should start with a lowercase letter and use camel case (cannot be auto-corrected) (experimental:property-naming)\" on properties containing nordic characters.`\r\n`Class or object name should start with an uppercase letter and use camel case (cannot be auto-corrected) (experimental:class-naming)`\r\n`Function name should start with a lowercase letter (except factory methods) and use camel case (cannot be auto-corrected) (experimental:function-naming)`\nIndeed, that is not entirely unexpected. Thnx for confirming though. Sorry for the inconvenience.", "created_at": "2023-01-15T19:54:20Z", "version": "0.49", "FAIL_TO_PASS": [ "gradle_test_execution" ], "PASS_TO_PASS": [], "ERROR_TO_PASS": [], "environment_setup_commit": "410d8849874f4d3600f9d4572e0850adccce4f2d" }, { "repo": "pinterest/ktlint", "pull_number": 2060, "instance_id": "pinterest__ktlint-2060", "issue_numbers": [ "1324" ], "base_commit": "441a9c9234bd7bb83dfd2df802373ad59271a2b7", "patch": "diff --git a/CHANGELOG.md b/CHANGELOG.md\nindex 862b4428c6..e3a3166d0e 100644\n--- a/CHANGELOG.md\n+++ b/CHANGELOG.md\n@@ -39,6 +39,7 @@ At this point in time, it is not yet decided what the next steps will be. Ktlint\n * Do not flag a (potential) mutable extension property in case the getter is annotated or prefixed with a modifier `property-naming` ([#2024](https://github.com/pinterest/ktlint/issues/2024))\n * Do not merge an annotated expression body with the function signature even if it fits on a single line ([#2043](https://github.com/pinterest/ktlint/issues/2043))\n * Ignore property with name `serialVersionUID` in `property-naming` ([#2045](https://github.com/pinterest/ktlint/issues/2045))\n+* Prevent incorrect reporting of violations in case a nullable function type reference exceeds the maximum line length `parameter-list-wrapping` ([#1324](https://github.com/pinterest/ktlint/issues/1324)) \n \n ### Changed\n \ndiff --git a/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/ParameterListWrappingRule.kt b/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/ParameterListWrappingRule.kt\nindex ae7573bdfd..d9c4e10cb6 100644\n--- a/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/ParameterListWrappingRule.kt\n+++ b/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/ParameterListWrappingRule.kt\n@@ -22,6 +22,8 @@ import com.pinterest.ktlint.rule.engine.core.api.editorconfig.MAX_LINE_LENGTH_PR\n import com.pinterest.ktlint.rule.engine.core.api.firstChildLeafOrSelf\n import com.pinterest.ktlint.rule.engine.core.api.indent\n import com.pinterest.ktlint.rule.engine.core.api.isWhiteSpaceWithNewline\n+import com.pinterest.ktlint.rule.engine.core.api.leavesIncludingSelf\n+import com.pinterest.ktlint.rule.engine.core.api.nextLeaf\n import com.pinterest.ktlint.rule.engine.core.api.prevCodeLeaf\n import com.pinterest.ktlint.rule.engine.core.api.prevLeaf\n import com.pinterest.ktlint.rule.engine.core.api.prevSibling\n@@ -88,48 +90,55 @@ public class ParameterListWrappingRule :\n require(node.elementType == NULLABLE_TYPE)\n node\n .takeUnless {\n- // skip when max line length is not exceedd\n+ // skip when max line length is not exceeded\n (node.column - 1 + node.textLength) <= maxLineLength\n- }?.findChildByType(FUNCTION_TYPE)\n- ?.findChildByType(VALUE_PARAMETER_LIST)\n- ?.takeIf { it.findChildByType(VALUE_PARAMETER) != null }\n- ?.takeUnless { it.textContains('\\n') }\n- ?.let {\n- node\n- .children()\n- .forEach {\n- when (it.elementType) {\n- LPAR -> {\n- emit(\n- it.startOffset,\n- \"Parameter of nullable type should be on a separate line (unless the type fits on a single line)\",\n- true,\n- )\n- if (autoCorrect) {\n- it.upsertWhitespaceAfterMe(indentConfig.childIndentOf(node))\n- }\n- }\n- RPAR -> {\n- emit(it.startOffset, errorMessage(it), true)\n- if (autoCorrect) {\n- it.upsertWhitespaceBeforeMe(indentConfig.parentIndentOf(node))\n- }\n- }\n+ }?.takeUnless { it.textContains('\\n') }\n+ ?.takeIf { it.isFunctionTypeWithNonEmptyValueParameterList() }\n+ ?.let { nullableType ->\n+ nullableType\n+ .findChildByType(LPAR)\n+ ?.takeUnless { it.nextLeaf()?.isWhiteSpaceWithNewline() == true }\n+ ?.let { lpar ->\n+ emit(\n+ lpar.startOffset + 1,\n+ \"Expected new line before function type as it does not fit on a single line\",\n+ true,\n+ )\n+ if (autoCorrect) {\n+ lpar.upsertWhitespaceAfterMe(indentConfig.childIndentOf(node))\n+ }\n+ }\n+ nullableType\n+ .findChildByType(RPAR)\n+ ?.takeUnless { it.prevLeaf()?.isWhiteSpaceWithNewline() == true }\n+ ?.let { rpar ->\n+ emit(\n+ rpar.startOffset,\n+ \"Expected new line after function type as it does not fit on a single line\",\n+ true,\n+ )\n+ if (autoCorrect) {\n+ rpar.upsertWhitespaceBeforeMe(indentConfig.parentIndentOf(node))\n }\n }\n }\n }\n \n+ private fun ASTNode.isFunctionTypeWithNonEmptyValueParameterList() =\n+ null !=\n+ findChildByType(FUNCTION_TYPE)\n+ ?.findChildByType(VALUE_PARAMETER_LIST)\n+ ?.findChildByType(VALUE_PARAMETER)\n+\n private fun ASTNode.needToWrapParameterList() =\n when {\n hasNoParameters() -> false\n codeStyle != ktlint_official && isPartOfFunctionLiteralInNonKtlintOfficialCodeStyle() -> false\n codeStyle == ktlint_official && isPartOfFunctionLiteralStartingOnSameLineAsClosingParenthesisOfPrecedingReferenceExpression() ->\n false\n- isFunctionTypeWrappedInNullableType() -> false\n textContains('\\n') -> true\n codeStyle == ktlint_official && containsAnnotatedParameter() -> true\n- exceedsMaxLineLength() -> true\n+ isOnLineExceedingMaxLineLength() -> true\n else -> false\n }\n \n@@ -159,11 +168,6 @@ public class ParameterListWrappingRule :\n }\n }\n \n- private fun ASTNode.isFunctionTypeWrappedInNullableType(): Boolean {\n- require(elementType == VALUE_PARAMETER_LIST)\n- return treeParent.elementType == FUNCTION_TYPE && treeParent?.treeParent?.elementType == NULLABLE_TYPE\n- }\n-\n private fun ASTNode.containsAnnotatedParameter(): Boolean {\n require(elementType == VALUE_PARAMETER_LIST)\n return this.children()\n@@ -228,10 +232,12 @@ public class ParameterListWrappingRule :\n when (child.elementType) {\n LPAR -> {\n val prevLeaf = child.prevLeaf()\n- if (prevLeaf is PsiWhiteSpace && prevLeaf.textContains('\\n')) {\n+ if (!child.treeParent.isValueParameterListInFunctionType() &&\n+ prevLeaf.isWhiteSpaceWithNewline()\n+ ) {\n emit(child.startOffset, errorMessage(child), true)\n if (autoCorrect) {\n- prevLeaf.delete()\n+ (prevLeaf as PsiWhiteSpace).delete()\n }\n }\n }\n@@ -272,7 +278,24 @@ public class ParameterListWrappingRule :\n }\n }\n \n- private fun ASTNode.exceedsMaxLineLength() = (column - 1 + textLength) > maxLineLength && !textContains('\\n')\n+ private fun ASTNode.isValueParameterListInFunctionType() =\n+ FUNCTION_TYPE ==\n+ takeIf { it.elementType == VALUE_PARAMETER_LIST }\n+ ?.treeParent\n+ ?.elementType\n+\n+ private fun ASTNode.isOnLineExceedingMaxLineLength(): Boolean {\n+ val stopLeaf = nextLeaf { it.textContains('\\n') }?.nextLeaf()\n+ val lineContent =\n+ prevLeaf { it.textContains('\\n') }\n+ ?.leavesIncludingSelf()\n+ ?.takeWhile { it.prevLeaf() != stopLeaf }\n+ ?.joinToString(separator = \"\") { it.text }\n+ ?.substringAfter('\\n')\n+ ?.substringBefore('\\n')\n+ .orEmpty()\n+ return lineContent.length > maxLineLength\n+ }\n \n private fun errorMessage(node: ASTNode) =\n when (node.elementType) {\n", "test_patch": "diff --git a/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/ParameterListWrappingRuleTest.kt b/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/ParameterListWrappingRuleTest.kt\nindex 304c8675a1..911aeedb50 100644\n--- a/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/ParameterListWrappingRuleTest.kt\n+++ b/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/ParameterListWrappingRuleTest.kt\n@@ -4,7 +4,8 @@ import com.pinterest.ktlint.rule.engine.core.api.RuleProvider\n import com.pinterest.ktlint.rule.engine.core.api.editorconfig.CODE_STYLE_PROPERTY\n import com.pinterest.ktlint.rule.engine.core.api.editorconfig.CodeStyleValue\n import com.pinterest.ktlint.rule.engine.core.api.editorconfig.CodeStyleValue.ktlint_official\n-import com.pinterest.ktlint.rule.engine.core.api.editorconfig.MAX_LINE_LENGTH_PROPERTY\n+import com.pinterest.ktlint.test.KtLintAssertThat.Companion.EOL_CHAR\n+import com.pinterest.ktlint.test.KtLintAssertThat.Companion.MAX_LINE_LENGTH_MARKER\n import com.pinterest.ktlint.test.KtLintAssertThat.Companion.assertThatRule\n import com.pinterest.ktlint.test.LintViolation\n import org.junit.jupiter.api.Nested\n@@ -51,10 +52,12 @@ class ParameterListWrappingRuleTest {\n fun `Given a single line class header which exceeds the maximum line length`() {\n val code =\n \"\"\"\n+ // $MAX_LINE_LENGTH_MARKER $EOL_CHAR\n class ClassA(paramA: String, paramB: String, paramC: String)\n \"\"\".trimIndent()\n val formattedCode =\n \"\"\"\n+ // $MAX_LINE_LENGTH_MARKER $EOL_CHAR\n class ClassA(\n paramA: String,\n paramB: String,\n@@ -62,12 +65,12 @@ class ParameterListWrappingRuleTest {\n )\n \"\"\".trimIndent()\n parameterListWrappingRuleAssertThat(code)\n- .withEditorConfigOverride(MAX_LINE_LENGTH_PROPERTY to 10)\n+ .setMaxLineLength()\n .hasLintViolations(\n- LintViolation(1, 14, \"Parameter should start on a newline\"),\n- LintViolation(1, 30, \"Parameter should start on a newline\"),\n- LintViolation(1, 46, \"Parameter should start on a newline\"),\n- LintViolation(1, 60, \"\"\"Missing newline before \")\"\"\"\"),\n+ LintViolation(2, 14, \"Parameter should start on a newline\"),\n+ LintViolation(2, 30, \"Parameter should start on a newline\"),\n+ LintViolation(2, 46, \"Parameter should start on a newline\"),\n+ LintViolation(2, 60, \"\"\"Missing newline before \")\"\"\"\"),\n ).isFormattedAs(formattedCode)\n }\n \n@@ -75,10 +78,11 @@ class ParameterListWrappingRuleTest {\n fun `Given a class header with a very long name and without parameters which exceeds the maximum line length then do not change the class header`() {\n val code =\n \"\"\"\n- class ClassAWithALongName()\n+ // $MAX_LINE_LENGTH_MARKER $EOL_CHAR\n+ class ClassAWithALoooooongName()\n \"\"\".trimIndent()\n parameterListWrappingRuleAssertThat(code)\n- .withEditorConfigOverride(MAX_LINE_LENGTH_PROPERTY to 10)\n+ .setMaxLineLength()\n .hasNoLintViolations()\n }\n \n@@ -130,7 +134,7 @@ class ParameterListWrappingRuleTest {\n }\n \n @Test\n- fun `Given a multiline function with parameters wheren some parameters are on the same line then start each parameter and closing parenthesis on a separate line`() {\n+ fun `Given a multiline function with parameters where some parameters are on the same line then start each parameter and closing parenthesis on a separate line`() {\n val code =\n \"\"\"\n fun f(\n@@ -156,11 +160,13 @@ class ParameterListWrappingRuleTest {\n fun `Given a single line function which exceeds the maximum line length then start each parameter and the closing parenthesis on a separate line`() {\n val code =\n \"\"\"\n+ // $MAX_LINE_LENGTH_MARKER $EOL_CHAR\n fun f(a: Any, b: Any, c: Any) {\n }\n \"\"\".trimIndent()\n val formattedCode =\n \"\"\"\n+ // $MAX_LINE_LENGTH_MARKER $EOL_CHAR\n fun f(\n a: Any,\n b: Any,\n@@ -169,12 +175,12 @@ class ParameterListWrappingRuleTest {\n }\n \"\"\".trimIndent()\n parameterListWrappingRuleAssertThat(code)\n- .withEditorConfigOverride(MAX_LINE_LENGTH_PROPERTY to 10)\n+ .setMaxLineLength()\n .hasLintViolations(\n- LintViolation(1, 7, \"Parameter should start on a newline\"),\n- LintViolation(1, 15, \"Parameter should start on a newline\"),\n- LintViolation(1, 23, \"Parameter should start on a newline\"),\n- LintViolation(1, 29, \"\"\"Missing newline before \")\"\"\"\"),\n+ LintViolation(2, 7, \"Parameter should start on a newline\"),\n+ LintViolation(2, 15, \"Parameter should start on a newline\"),\n+ LintViolation(2, 23, \"Parameter should start on a newline\"),\n+ LintViolation(2, 29, \"\"\"Missing newline before \")\"\"\"\"),\n ).isFormattedAs(formattedCode)\n }\n \n@@ -248,6 +254,7 @@ class ParameterListWrappingRuleTest {\n fun `Given a function with annotated parameters then start each parameter on a separate line but preserve spacing between annotation and parameter name`() {\n val code =\n \"\"\"\n+ // $MAX_LINE_LENGTH_MARKER $EOL_CHAR\n class A {\n fun f(@Annotation\n a: Any,\n@@ -259,6 +266,7 @@ class ParameterListWrappingRuleTest {\n \"\"\".trimIndent()\n val formattedCode =\n \"\"\"\n+ // $MAX_LINE_LENGTH_MARKER $EOL_CHAR\n class A {\n fun f(\n @Annotation\n@@ -272,11 +280,11 @@ class ParameterListWrappingRuleTest {\n }\n \"\"\".trimIndent()\n parameterListWrappingRuleAssertThat(code)\n- .withEditorConfigOverride(MAX_LINE_LENGTH_PROPERTY to 10)\n+ .setMaxLineLength()\n .hasLintViolations(\n- LintViolation(2, 11, \"Parameter should start on a newline\"),\n- LintViolation(6, 19, \"Parameter should start on a newline\"),\n- LintViolation(6, 37, \"\"\"Missing newline before \")\"\"\"\"),\n+ LintViolation(3, 11, \"Parameter should start on a newline\"),\n+ LintViolation(7, 19, \"Parameter should start on a newline\"),\n+ LintViolation(7, 37, \"\"\"Missing newline before \")\"\"\"\"),\n ).isFormattedAs(formattedCode)\n }\n \n@@ -344,10 +352,12 @@ class ParameterListWrappingRuleTest {\n fun `Given a single line function with nested declarations which exceeds the maximum line length then format each parameter and closing parenthesis on a separate line`() {\n val code =\n \"\"\"\n+ // $MAX_LINE_LENGTH_MARKER $EOL_CHAR\n fun visit(node: ASTNode, autoCorrect: Boolean, emit: (offset: Int, errorMessage: String, canBeAutoCorrected: Boolean) -> Unit) {}\n \"\"\".trimIndent()\n val formattedCode =\n \"\"\"\n+ // $MAX_LINE_LENGTH_MARKER $EOL_CHAR\n fun visit(\n node: ASTNode,\n autoCorrect: Boolean,\n@@ -359,16 +369,16 @@ class ParameterListWrappingRuleTest {\n ) {}\n \"\"\".trimIndent()\n parameterListWrappingRuleAssertThat(code)\n- .withEditorConfigOverride(MAX_LINE_LENGTH_PROPERTY to 10)\n+ .setMaxLineLength()\n .hasLintViolations(\n- LintViolation(1, 11, \"Parameter should start on a newline\"),\n- LintViolation(1, 26, \"Parameter should start on a newline\"),\n- LintViolation(1, 48, \"Parameter should start on a newline\"),\n- LintViolation(1, 55, \"Parameter should start on a newline\"),\n- LintViolation(1, 68, \"Parameter should start on a newline\"),\n- LintViolation(1, 90, \"Parameter should start on a newline\"),\n- LintViolation(1, 117, \"Missing newline before \\\")\\\"\"),\n- LintViolation(1, 126, \"Missing newline before \\\")\\\"\"),\n+ LintViolation(2, 11, \"Parameter should start on a newline\"),\n+ LintViolation(2, 26, \"Parameter should start on a newline\"),\n+ LintViolation(2, 48, \"Parameter should start on a newline\"),\n+ LintViolation(2, 55, \"Parameter should start on a newline\"),\n+ LintViolation(2, 68, \"Parameter should start on a newline\"),\n+ LintViolation(2, 90, \"Parameter should start on a newline\"),\n+ LintViolation(2, 117, \"Missing newline before \\\")\\\"\"),\n+ LintViolation(2, 126, \"Missing newline before \\\")\\\"\"),\n ).isFormattedAs(formattedCode)\n }\n \n@@ -512,34 +522,117 @@ class ParameterListWrappingRuleTest {\n parameterListWrappingRuleAssertThat(code).hasNoLintViolations()\n }\n \n- @Test\n- fun `Issue 1255 - Given a variable declaration for nullable function type which exceeds the max-line-length then wrap the function type to a new line`() {\n- val code =\n- \"\"\"\n- var changesListener: ((width: Double?, depth: Double?, length: Double?, area: Double?) -> Unit)? = null\n- fun foo() {\n- var changesListener: ((width: Double?, depth: Double?, length: Double?, area: Double?) -> Unit)? = null\n- }\n- \"\"\".trimIndent()\n- val formattedCode =\n- \"\"\"\n- var changesListener: (\n- (width: Double?, depth: Double?, length: Double?, area: Double?) -> Unit\n- )? = null\n- fun foo() {\n- var changesListener: (\n- (width: Double?, depth: Double?, length: Double?, area: Double?) -> Unit\n+ @Nested\n+ inner class `Issue 1255 - Given a variable declaration for nullable function type` {\n+ @Test\n+ fun `Given a nullable function type for which the function type fits on a single line after wrapping the nullable type`() {\n+ val code =\n+ \"\"\"\n+ // $MAX_LINE_LENGTH_MARKER $EOL_CHAR\n+ var foo1: ((bar1: Bar, bar2: Bar, bar3: Bar) -> Unit)? = null\n+ var foo2: (\n+ (bar1: Bar, bar2: Bar, bar3: Bar) -> Unit\n )? = null\n- }\n- \"\"\".trimIndent()\n- parameterListWrappingRuleAssertThat(code)\n- .withEditorConfigOverride(MAX_LINE_LENGTH_PROPERTY to 80)\n- .hasLintViolations(\n- LintViolation(1, 22, \"Parameter of nullable type should be on a separate line (unless the type fits on a single line)\"),\n- LintViolation(1, 95, \"\"\"Missing newline before \")\"\"\"\"),\n- LintViolation(3, 26, \"Parameter of nullable type should be on a separate line (unless the type fits on a single line)\"),\n- LintViolation(3, 99, \"\"\"Missing newline before \")\"\"\"\"),\n- ).isFormattedAs(formattedCode)\n+ \"\"\".trimIndent()\n+ val formattedCode =\n+ \"\"\"\n+ // $MAX_LINE_LENGTH_MARKER $EOL_CHAR\n+ var foo1: (\n+ (bar1: Bar, bar2: Bar, bar3: Bar) -> Unit\n+ )? = null\n+ var foo2: (\n+ (bar1: Bar, bar2: Bar, bar3: Bar) -> Unit\n+ )? = null\n+ \"\"\".trimIndent()\n+ parameterListWrappingRuleAssertThat(code)\n+ .setMaxLineLength()\n+ .hasLintViolations(\n+ // Some violations below are only reported during linting but not on formatting. After wrapping the\n+ // nullable type, there is no need to wrap the parameters.\n+ LintViolation(2, 12, \"Expected new line before function type as it does not fit on a single line\"),\n+ LintViolation(2, 13, \"Parameter should start on a newline\"),\n+ LintViolation(2, 24, \"Parameter should start on a newline\"),\n+ LintViolation(2, 35, \"Parameter should start on a newline\"),\n+ LintViolation(2, 44, \"Missing newline before \\\")\\\"\"),\n+ LintViolation(2, 53, \"Expected new line after function type as it does not fit on a single line\"),\n+ ).isFormattedAs(formattedCode)\n+ }\n+\n+ @Test\n+ fun `Given a nullable function type for which the function type fits does not fit on a single line after wrapping the nullable type`() {\n+ val code =\n+ \"\"\"\n+ // $MAX_LINE_LENGTH_MARKER $EOL_CHAR\n+ var foo1: ((bar1: Bar, bar2: Bar, bar3: Bar) -> Unit)? = null\n+ var foo2: (\n+ (bar1: Bar, bar2: Bar, bar3: Bar) -> Unit\n+ )? = null\n+ \"\"\".trimIndent()\n+ val formattedCode =\n+ \"\"\"\n+ // $MAX_LINE_LENGTH_MARKER $EOL_CHAR\n+ var foo1: (\n+ (\n+ bar1: Bar,\n+ bar2: Bar,\n+ bar3: Bar\n+ ) -> Unit\n+ )? = null\n+ var foo2: (\n+ (\n+ bar1: Bar,\n+ bar2: Bar,\n+ bar3: Bar\n+ ) -> Unit\n+ )? = null\n+ \"\"\".trimIndent()\n+ parameterListWrappingRuleAssertThat(code)\n+ .setMaxLineLength()\n+ .hasLintViolations(\n+ LintViolation(2, 12, \"Expected new line before function type as it does not fit on a single line\"),\n+ LintViolation(2, 13, \"Parameter should start on a newline\"),\n+ LintViolation(2, 24, \"Parameter should start on a newline\"),\n+ LintViolation(2, 35, \"Parameter should start on a newline\"),\n+ LintViolation(2, 44, \"Missing newline before \\\")\\\"\"),\n+ LintViolation(2, 53, \"Expected new line after function type as it does not fit on a single line\"),\n+ LintViolation(4, 6, \"Parameter should start on a newline\"),\n+ LintViolation(4, 17, \"Parameter should start on a newline\"),\n+ LintViolation(4, 28, \"Parameter should start on a newline\"),\n+ LintViolation(4, 37, \"Missing newline before \\\")\\\"\"),\n+ ).isFormattedAs(formattedCode)\n+ }\n+\n+ @Test\n+ fun `Given a function containing a nullable function type for which the function type fits does not fit on a single line after wrapping the nullable type`() {\n+ val code =\n+ \"\"\"\n+ // $MAX_LINE_LENGTH_MARKER $EOL_CHAR\n+ fun foo() {\n+ var changesListener: ((bar1: Bar, bar2: Bar, bar3: Bar) -> Unit)? = null\n+ }\n+ \"\"\".trimIndent()\n+ val formattedCode =\n+ \"\"\"\n+ // $MAX_LINE_LENGTH_MARKER $EOL_CHAR\n+ fun foo() {\n+ var changesListener: (\n+ (bar1: Bar, bar2: Bar, bar3: Bar) -> Unit\n+ )? = null\n+ }\n+ \"\"\".trimIndent()\n+ parameterListWrappingRuleAssertThat(code)\n+ .setMaxLineLength()\n+ .hasLintViolations(\n+ // Some violations below are only reported during linting but not on formatting. After wrapping the\n+ // nullable type, there is no need to wrap the parameters.\n+ LintViolation(3, 27, \"Expected new line before function type as it does not fit on a single line\"),\n+ LintViolation(3, 28, \"Parameter should start on a newline\"),\n+ LintViolation(3, 39, \"Parameter should start on a newline\"),\n+ LintViolation(3, 50, \"Parameter should start on a newline\"),\n+ LintViolation(3, 59, \"Missing newline before \\\")\\\"\"),\n+ LintViolation(3, 68, \"Expected new line after function type as it does not fit on a single line\"),\n+ ).isFormattedAs(formattedCode)\n+ }\n }\n \n @Nested\n", "problem_statement": "Bug on parameter's class that reached maximum line\n\r\n\r\n## Expected Behavior\r\nNo error.\r\n\r\n## Observed Behavior\r\nError.\r\n\r\n## Steps to Reproduce\r\nI have parameter lambda code like this, let say my parameter is reached maximum limit of line :\r\n\"image\"\r\n\r\n\r\nThere is error detected on `open bracket (`. I already clicked `Format with ktlint`, but still error.\r\n\r\n## Your Environment\r\n\r\n* Version of ktlint used: 0.43.2\r\n* Version of Gradle used (if applicable): AGP 7\r\n* Operating System and version: MacOS Big Sur\r\n\n", "hints_text": "Next time, please post your code instead of an image. It is more convenient when trying to reproduce a problem.\r\n\r\nThe code below is comparable to your example:\r\n```\r\n// Assume, the line breaks at the pipe symbol on the right -> |\r\nval foo1: ((s1: String, s2: String, s3: String, s4: String, s5: String, s6: String) -> Unit)? = null\r\n```\r\n\r\nThe `ktlint --verbose --relative` command results in:\r\n```\r\nsrc/main/kotlin/Issue1324.kt:1:1: Exceeded max line length (80) (cannot be auto-corrected) (max-line-length)\r\nsrc/main/kotlin/Issue1324.kt:1:13: Parameter should be on a separate line (unless all parameters can fit a single line) (parameter-list-wrapping)\r\nsrc/main/kotlin/Issue1324.kt:1:25: Parameter should be on a separate line (unless all parameters can fit a single line) (parameter-list-wrapping)\r\nsrc/main/kotlin/Issue1324.kt:1:37: Parameter should be on a separate line (unless all parameters can fit a single line) (parameter-list-wrapping)\r\nsrc/main/kotlin/Issue1324.kt:1:49: Parameter should be on a separate line (unless all parameters can fit a single line) (parameter-list-wrapping)\r\nsrc/main/kotlin/Issue1324.kt:1:61: Parameter should be on a separate line (unless all parameters can fit a single line) (parameter-list-wrapping)\r\nsrc/main/kotlin/Issue1324.kt:1:73: Parameter should be on a separate line (unless all parameters can fit a single line) (parameter-list-wrapping)\r\nsrc/main/kotlin/Issue1324.kt:1:83: Missing newline before \")\" (parameter-list-wrapping)\r\n```\r\nFrom this it can be seen that both the `max-line-length` and the `parameter-list-wrapping` report violations in the original code.\r\n\r\nAuto-correct by the `parameter-list-wrapping` resolves the max line length violation and results in code below:\r\n```\r\n// Assume, next line exceeds the max line length -> |\r\nval foo1: (\r\n (\r\n s1: String,\r\n s2: String,\r\n s3: String,\r\n s4: String,\r\n s5: String,\r\n s6: String\r\n ) -> Unit\r\n )? = null\r\n```\r\nbut that same rule immediately reports now another lint error as you reported as well:\r\n```\r\nsrc/main/kotlin/Issue1324.kt:3:5: Unnecessary newline before \"(\" (parameter-list-wrapping)\r\n```\r\n\r\nSo far, I have found no way to refactor the code manually in such a way that the code is accepted by both *ktlint* as well as by the IntelliJ default code formatting which nowadays is a requirement when we make (bugfixes on) rules. For example, the previous code sample will be transformed by IntelliJ default formatting to following:\r\n```\r\n// Assume, next line exceeds the max line length -> |\r\nval foo1: (\r\n (\r\n s1: String,\r\n s2: String,\r\n s3: String,\r\n s4: String,\r\n s5: String,\r\n s6: String\r\n) -> Unit\r\n)? = null\r\n```\r\nThis is horrible code.\r\n\r\nFor now, I see no other way for you to disable both rules and stick with one really long line:\r\n```\r\nval foo1: ((s1: String, s2: String, s3: String, s4: String, s5: String, s6: String) -> Unit)? = null // ktlint-disable max-line-length parameter-list-wrapping\r\n```\r\n\r\nMaybe, someone else has a briljant idea how to the resulting code should look like in such a way that both ktlint as well as IntelliJ default formatting do not alter that code. Next step would then be to fix the rules do that the code will be formatted as such.", "created_at": "2023-05-27T17:12:01Z", "version": "0.49", "FAIL_TO_PASS": [ "gradle_test_execution" ], "PASS_TO_PASS": [], "ERROR_TO_PASS": [], "environment_setup_commit": "410d8849874f4d3600f9d4572e0850adccce4f2d" }, { "repo": "wordpress-mobile/WordPress-Android", "pull_number": 20745, "instance_id": "wordpress-mobile__WordPress-Android-20745", "issue_numbers": [ "20272" ], "base_commit": "3be32dad0b5dbc6c12e47d03d1cf2196fee416fc", "patch": "diff --git a/WordPress/src/main/java/org/wordpress/android/ui/posts/PublishSettingsViewModel.kt b/WordPress/src/main/java/org/wordpress/android/ui/posts/PublishSettingsViewModel.kt\nindex 6b9ac3478a36..0c3a87edcbef 100644\n--- a/WordPress/src/main/java/org/wordpress/android/ui/posts/PublishSettingsViewModel.kt\n+++ b/WordPress/src/main/java/org/wordpress/android/ui/posts/PublishSettingsViewModel.kt\n@@ -71,8 +71,9 @@ constructor(\n \n open fun start(postRepository: EditPostRepository?) {\n editPostRepository = postRepository\n- val startCalendar = postRepository?.let { getCurrentPublishDateAsCalendar(it) }\n- ?: localeManagerWrapper.getCurrentCalendar()\n+ val startCalendar = postRepository?.takeIf { it.hasPost() }?.let {\n+ getCurrentPublishDateAsCalendar(it)\n+ } ?: localeManagerWrapper.getCurrentCalendar()\n updateDateAndTimeFromCalendar(startCalendar)\n onPostStatusChanged(postRepository?.getPost())\n }\n", "test_patch": "diff --git a/WordPress/src/test/java/org/wordpress/android/ui/posts/EditPostPublishSettingsViewModelTest.kt b/WordPress/src/test/java/org/wordpress/android/ui/posts/EditPostPublishSettingsViewModelTest.kt\nindex ff79f33bbd8f..ecd6b449465b 100644\n--- a/WordPress/src/test/java/org/wordpress/android/ui/posts/EditPostPublishSettingsViewModelTest.kt\n+++ b/WordPress/src/test/java/org/wordpress/android/ui/posts/EditPostPublishSettingsViewModelTest.kt\n@@ -95,6 +95,7 @@ class EditPostPublishSettingsViewModelTest : BaseUnitTest() {\n null\n }\n whenever(editPostRepository.getPost()).thenReturn(post)\n+ whenever(editPostRepository.hasPost()).thenReturn(true)\n }\n \n @Test\n@@ -450,4 +451,25 @@ class EditPostPublishSettingsViewModelTest : BaseUnitTest() {\n \n assertThat(schedulingReminderPeriod).isEqualTo(ONE_HOUR)\n }\n+\n+ @Test\n+ fun `on start sets current date when post not present in the repository`() {\n+ var uiModel: PublishUiModel? = null\n+ viewModel.onUiModel.observeForever {\n+ uiModel = it\n+ }\n+\n+ whenever(editPostRepository.hasPost()).thenReturn(false)\n+ whenever(editPostRepository.getPost()).thenReturn(null)\n+\n+ viewModel.start(editPostRepository)\n+\n+ assertThat(viewModel.year).isEqualTo(2019)\n+ assertThat(viewModel.month).isEqualTo(6)\n+ assertThat(viewModel.day).isEqualTo(6)\n+ assertThat(viewModel.hour).isEqualTo(10)\n+ assertThat(viewModel.minute).isEqualTo(20)\n+\n+ assertThat(uiModel!!.publishDateLabel).isEqualTo(\"Immediately\")\n+ }\n }\n", "problem_statement": "NullPointerException\nSentry Issue: [JETPACK-ANDROID-JPV](https://a8c.sentry.io/issues/5004070666/?referrer=github_integration)\n\n```\nNullPointerException: None\n at org.wordpress.android.ui.posts.EditPostRepository.getDateCreated(EditPostRepository.kt:86)\n at org.wordpress.android.ui.posts.PublishSettingsViewModel.getCurrentPublishDateAsCalendar(PublishSettingsViewModel.kt:209)\n at org.wordpress.android.ui.posts.PublishSettingsViewModel.start(PublishSettingsViewModel.kt:74)\n at org.wordpress.android.ui.posts.prepublishing.publishsettings.PrepublishingPublishSettingsViewModel.start(PrepublishingPublishSettingsViewModel.kt:38)\n at org.wordpress.android.ui.posts.PublishSettingsFragment.onCreateView(PublishSettingsFragment.kt:75)\n...\n(15 additional frame(s) were not displayed)\n```\n", "hints_text": "Thanks for reporting! \ud83d\udc4d \n", "created_at": "2024-05-01T15:02:34Z", "version": "24.82", "FAIL_TO_PASS": [ "gradle_test_execution" ], "PASS_TO_PASS": [], "ERROR_TO_PASS": [], "environment_setup_commit": "0b525f6e4925757f0a6b94849797684b5bf2d4a5" }, { "repo": "wordpress-mobile/WordPress-Android", "pull_number": 18959, "instance_id": "wordpress-mobile__WordPress-Android-18959", "issue_numbers": [ "18958" ], "base_commit": "361bc30a324fc87355c6f7883c340d89f79743cc", "patch": "diff --git a/WordPress/src/main/java/org/wordpress/android/ui/uploads/UploadStarter.kt b/WordPress/src/main/java/org/wordpress/android/ui/uploads/UploadStarter.kt\nindex 66bff7046d62..ceca1428fc62 100644\n--- a/WordPress/src/main/java/org/wordpress/android/ui/uploads/UploadStarter.kt\n+++ b/WordPress/src/main/java/org/wordpress/android/ui/uploads/UploadStarter.kt\n@@ -136,7 +136,7 @@ class UploadStarter @Inject constructor(\n }\n \n sites.forEach {\n- launch(ioDispatcher) {\n+ launch {\n upload(site = it)\n }\n }\n@@ -148,8 +148,8 @@ class UploadStarter @Inject constructor(\n private suspend fun upload(site: SiteModel) = coroutineScope {\n try {\n mutex.withLock {\n- val posts = async { postStore.getPostsWithLocalChanges(site) }\n- val pages = async { pageStore.getPagesWithLocalChanges(site) }\n+ val posts = async(ioDispatcher) { postStore.getPostsWithLocalChanges(site) }\n+ val pages = async(ioDispatcher) { pageStore.getPagesWithLocalChanges(site) }\n val list = posts.await() + pages.await()\n \n list.asSequence()\n@@ -181,9 +181,7 @@ class UploadStarter @Inject constructor(\n }\n } catch (e: CancellationException) {\n AppLog.e(T.MEDIA, e)\n- // Do any needed actions while we are still holding the mutex lock, then release it and rethrow the\n- // exception so it can be handled upstream\n- mutex.unlock()\n+ // rethrow the exception so it can be handled upstream\n throw e\n }\n }\n", "test_patch": "diff --git a/WordPress/src/test/java/org/wordpress/android/ui/uploads/UploadStarterMutexTest.kt b/WordPress/src/test/java/org/wordpress/android/ui/uploads/UploadStarterMutexTest.kt\nnew file mode 100644\nindex 000000000000..611e018567a2\n--- /dev/null\n+++ b/WordPress/src/test/java/org/wordpress/android/ui/uploads/UploadStarterMutexTest.kt\n@@ -0,0 +1,142 @@\n+package org.wordpress.android.ui.uploads\n+\n+import android.content.Context\n+import androidx.lifecycle.MutableLiveData\n+import kotlinx.coroutines.ExperimentalCoroutinesApi\n+import kotlinx.coroutines.asCoroutineDispatcher\n+import kotlinx.coroutines.delay\n+import org.junit.Before\n+import org.junit.Test\n+import org.mockito.Mock\n+import org.mockito.kotlin.any\n+import org.mockito.kotlin.doAnswer\n+import org.mockito.kotlin.doSuspendableAnswer\n+import org.mockito.kotlin.mock\n+import org.mockito.kotlin.whenever\n+import org.wordpress.android.BaseUnitTest\n+import org.wordpress.android.fluxc.Dispatcher\n+import org.wordpress.android.fluxc.model.PostModel\n+import org.wordpress.android.fluxc.store.PageStore\n+import org.wordpress.android.fluxc.store.PostStore\n+import org.wordpress.android.fluxc.store.SiteStore\n+import org.wordpress.android.util.NetworkUtilsWrapper\n+import org.wordpress.android.util.analytics.AnalyticsTrackerWrapper\n+import org.wordpress.android.viewmodel.helpers.ConnectionStatus\n+import java.util.concurrent.Executors\n+\n+/**\n+ * This class tries to reproduce the situation of trying to start the upload service when the device is in the\n+ * background. Such situation causes the system to throw a IllegalStateException, as it's not allowed to create\n+ * services from the background, which in turns causes a failure in the coroutine jobs, which should be cancelled\n+ * without crashing the application.\n+ *\n+ * This was created because the situation above was causing a crash in our app:\n+ * https://a8c.sentry.io/issues/4295575735/?project=573168\n+ */\n+@OptIn(ExperimentalCoroutinesApi::class)\n+class UploadStarterMutexTest : BaseUnitTest() {\n+ private val bgDispatcher = Executors.newFixedThreadPool(DEFAULT_THREADS).asCoroutineDispatcher()\n+ private val ioDispatcher = Executors.newFixedThreadPool(IO_THREADS).asCoroutineDispatcher()\n+\n+ @Mock\n+ lateinit var context: Context\n+\n+ @Mock\n+ lateinit var dispatcher: Dispatcher\n+\n+ @Mock\n+ lateinit var postStore: PostStore\n+\n+ @Mock\n+ lateinit var pageStore: PageStore\n+\n+ @Mock\n+ lateinit var siteStore: SiteStore\n+\n+ @Mock\n+ lateinit var uploadActionUseCase: UploadActionUseCase\n+\n+ @Mock\n+ lateinit var tracker: AnalyticsTrackerWrapper\n+\n+ @Mock\n+ lateinit var uploadServiceFacade: UploadServiceFacade\n+\n+ @Mock\n+ lateinit var networkUtilsWrapper: NetworkUtilsWrapper\n+\n+ private var connectionStatus: MutableLiveData = MutableLiveData()\n+\n+ private lateinit var uploadStarter: UploadStarter\n+\n+ @Before\n+ fun setUp() {\n+ uploadStarter = UploadStarter(\n+ context = context,\n+ dispatcher = dispatcher,\n+ postStore = postStore,\n+ pageStore = pageStore,\n+ siteStore = siteStore,\n+ uploadActionUseCase = uploadActionUseCase,\n+ tracker = tracker,\n+ bgDispatcher = bgDispatcher,\n+ ioDispatcher = ioDispatcher,\n+ uploadServiceFacade = uploadServiceFacade,\n+ networkUtilsWrapper = networkUtilsWrapper,\n+ connectionStatus = connectionStatus\n+ )\n+ }\n+\n+ @Test\n+ fun `should not crash if uploadPost throws an exception`() = test {\n+ // network is available\n+ whenever(networkUtilsWrapper.isNetworkAvailable()).thenReturn(true)\n+ // return 10 sites for queuing\n+ whenever(siteStore.sites).thenReturn(List(10) { mock() })\n+ // each site has 10 posts with local changes\n+ whenever(postStore.getPostsWithLocalChanges(any())).doAnswer {\n+ Thread.sleep(10)\n+ List(10) { fakePostModel(it, false) }\n+ }\n+ // each site has 5 pages with local changes\n+ whenever(pageStore.getPagesWithLocalChanges(any())).doSuspendableAnswer {\n+ delay(10)\n+ List(5) {\n+ fakePostModel(\n+ 100 + it,\n+ true\n+ )\n+ }\n+ }\n+\n+ whenever(uploadActionUseCase.getAutoUploadAction(any(), any()))\n+ .thenReturn(UploadActionUseCase.UploadAction.UPLOAD)\n+\n+ // throw IllegalStateException when uploading post (emulate trying to start background service)\n+ whenever(uploadServiceFacade.uploadPost(any(), any(), any()))\n+ .thenThrow(IllegalStateException(\"FAKE: Not allowed to start service intent\"))\n+\n+ // ACT\n+ uploadStarter.queueUploadFromAllSites().join()\n+ }\n+\n+ companion object {\n+ // # of threads in Dispatchers.Default is equal to the # of CPU cores, 8 is a common # of cores in modern phones\n+ // https://kotlinlang.org/api/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-dispatchers/-default.html\n+ private const val DEFAULT_THREADS = 8\n+\n+ // default # of threads in Dispatchers.IO is 64 but it can be even larger, let's use 64, which is enough\n+ // https://kotlinlang.org/api/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-dispatchers/-i-o.html\n+ private const val IO_THREADS = 64\n+\n+ private fun fakePostModel(\n+ id: Int,\n+ isPage: Boolean,\n+ ) = PostModel().apply {\n+ setId(id)\n+ setIsPage(isPage)\n+ setTitle(\"Title $id\")\n+ setStatus(\"draft\")\n+ }\n+ }\n+}\n", "problem_statement": "CompletionHandlerException: Exception in resume onCancellation handler for CancellableContinuation(DispatchedContinuation[Dis...\nSentry Issue: [JETPACK-ANDROID-92S](https://a8c.sentry.io/issues/4295575735/?referrer=github_integration)\n\n```\nIllegalStateException: This mutex is not locked\n at kotlinx.coroutines.sync.MutexImpl.unlock(Mutex.kt:207)\n at kotlinx.coroutines.sync.MutexImpl$CancellableContinuationWithOwner$tryResume$token$1.invoke(Mutex.kt:255)\n at kotlinx.coroutines.sync.MutexImpl$CancellableContinuationWithOwner$tryResume$token$1.invoke(Mutex.kt:252)\n at kotlinx.coroutines.CancellableContinuationImpl.callOnCancellation(CancellableContinuationImpl.kt:259)\n at kotlinx.coroutines.CompletedContinuation.invokeHandlers(CancellableContinuationImpl.kt:659)\n...\n(8 additional frame(s) were not displayed)\n\nCompletionHandlerException: Exception in resume onCancellation handler for CancellableContinuation(DispatchedContinuation[Dispatchers.IO, Continuation at org.wordpress.android.ui.uploads.UploadStarter$upload$2.invokeSuspend(UploadStarter.kt:211)@df58903]){Completed}@c9c7080\n at kotlinx.coroutines.CancellableContinuationImpl.callOnCancellation(CancellableContinuationImpl.kt:264)\n at kotlinx.coroutines.CompletedContinuation.invokeHandlers(CancellableContinuationImpl.kt:659)\n at kotlinx.coroutines.CancellableContinuationImpl.cancelCompletedResult$kotlinx_coroutines_core(CancellableContinuationImpl.kt:180)\n at kotlinx.coroutines.DispatchedTask.run(DispatchedTask.kt:100)\n at kotlinx.coroutines.internal.LimitedDispatcher$Worker.run(LimitedDispatcher.kt:115)\n...\n(5 additional frame(s) were not displayed)\n```\n\nThis is not a duplicate of #17463 since this is now happening on coroutines 1.7.1 which fixed the underlying root cause of that other ticket. This has a similar stacktrace, but it looks like we might be misusing the Mutex in our `UploadStarter` implementation.\n", "hints_text": "**TLDR:**\u00a0I think our code is silently making the crash look like it\u2019s an internal Mutex problem but in reality, we might be calling\u00a0`unlock`\u00a0unnecessarily when the Mutex internals are not expecting it. We should remove\u00a0[this line](https://github.com/wordpress-mobile/WordPress-Android/blob/1b5e1f3fc97e13d0068ea803d5df7777f421180b/WordPress/src/main/java/org/wordpress/android/ui/uploads/UploadStarter.kt#L186)\u00a0and I\u00a0think\u00a0it might solve our issues on coroutines 1.7.1.\r\n\r\nBased on the\u00a0[breadcrumbs](https://a8c.sentry.io/issues/4295575735/?project=5731682&referrer=issue-stream&sort=freq&statsPeriod=14d&stream_index=1#breadcrumbs) I believe the actual issue is that we tried to\u00a0[start the post upload service](https://github.com/wordpress-mobile/WordPress-Android/blob/1b5e1f3fc97e13d0068ea803d5df7777f421180b/WordPress/src/main/java/org/wordpress/android/ui/uploads/UploadStarter.kt#L175-L179)\u00a0while the app was in the background and the system didn\u2019t let us, which caused all\u00a0`upload`\u00a0jobs (created\u00a0[here](https://github.com/wordpress-mobile/WordPress-Android/blob/1b5e1f3fc97e13d0068ea803d5df7777f421180b/WordPress/src/main/java/org/wordpress/android/ui/uploads/UploadStarter.kt#L138-L142)) to be canceled since the\u00a0[Parent Job](https://github.com/wordpress-mobile/WordPress-Android/blob/1b5e1f3fc97e13d0068ea803d5df7777f421180b/WordPress/src/main/java/org/wordpress/android/ui/uploads/UploadStarter.kt#L68) is not a\u00a0`SupervisorJob`.\r\n\r\nThis made all jobs (except the first one which failed because of an\u00a0`IllegalStateException`)\u00a0[fall here](https://github.com/wordpress-mobile/WordPress-Android/blob/1b5e1f3fc97e13d0068ea803d5df7777f421180b/WordPress/src/main/java/org/wordpress/android/ui/uploads/UploadStarter.kt#L183-L187)\u00a0(as can be seen in the breadcrumb logs).\r\n\r\n**What I first thought could be happening is:**\r\n\r\nWe use the\u00a0`bgDispatcher`\u00a0([Dispatchers.Default](https://github.com/wordpress-mobile/WordPress-Android/blob/e03d208247c7487a7497f873d91f6b0e52a3622e/WordPress/src/main/java/org/wordpress/android/modules/ThreadModule.kt#L40-L42)) which has several threads in the pool and we use the same\u00a0`mutex`\u00a0for all upload jobs. Because of that, multiple coroutines (running in different threads) are suspended awaiting the to\u00a0[acquire](https://github.com/Kotlin/kotlinx.coroutines/blob/02382479398518ea1c4507170aa92692595b6839/kotlinx-coroutines-core/common/src/sync/Semaphore.kt#L196-L201C6)\u00a0the semaphore (which\u00a0[creates a queue of segments](https://github.com/Kotlin/kotlinx.coroutines/blob/02382479398518ea1c4507170aa92692595b6839/kotlinx-coroutines-core/common/src/sync/Semaphore.kt#L285-L315)).\r\n\r\nSince multiple jobs are being canceled at once, I\u00a0think\u00a0that the cancellation was not able to be properly propagated and the\u00a0`segment`\u00a0state for one of them was not marked as\u00a0`CANCELLED`\u00a0making the\u00a0`Semaphore#tryResumeNextFromQueue`\u00a0([which is\u00a0called on](https://github.com/Kotlin/kotlinx.coroutines/blob/1.7.1/kotlinx-coroutines-core/common/src/sync/Semaphore.kt#L265)\u00a0`Semaphore#release`\u00a0[via the](https://github.com/Kotlin/kotlinx.coroutines/blob/02382479398518ea1c4507170aa92692595b6839/kotlinx-coroutines-core/common/src/sync/Mutex.kt#L216)\u00a0`Mutex#unlock`)\u00a0[call the](https://github.com/Kotlin/kotlinx.coroutines/blob/02382479398518ea1c4507170aa92692595b6839/kotlinx-coroutines-core/common/src/sync/Semaphore.kt#L329-L341)\u00a0`tryResumeAcquire`. Which in turn\u00a0[calls](https://github.com/Kotlin/kotlinx.coroutines/blob/02382479398518ea1c4507170aa92692595b6839/kotlinx-coroutines-core/common/src/sync/Semaphore.kt#L347C23-L347C23)\u00a0`Mutex#tryResume`\u00a0but since that is canceled it runs the\u00a0`onCancellation`\u00a0[callback](https://github.com/Kotlin/kotlinx.coroutines/blob/02382479398518ea1c4507170aa92692595b6839/kotlinx-coroutines-core/common/src/sync/Mutex.kt#L253-L255)\u00a0when trying to resume the underlying continuation, which is\u00a0[where the crash is happening](https://github.com/Kotlin/kotlinx.coroutines/blob/02382479398518ea1c4507170aa92692595b6839/kotlinx-coroutines-core/common/src/sync/Mutex.kt#L250-L262).\r\n\r\nBut I am not 100% sure about that, as I feel like this scenario would be pretty common for a synchronization mechanism using coroutines (like `Mutex` and `Semaphore`), which is why I believe that\u00a0`onCancellation`\u00a0callback also\u00a0unlocks\u00a0the `Mutex`, in case of that late propagation of the cancellation to the mutex\u00a0`Segment`.\r\n\r\n**So, considering that the code makes sense and works (hopefully) what I\u00a0think\u00a0might be the issue is:**\r\n\r\nWe also have a\u00a0[call to](https://github.com/wordpress-mobile/WordPress-Android/blob/1b5e1f3fc97e13d0068ea803d5df7777f421180b/WordPress/src/main/java/org/wordpress/android/ui/uploads/UploadStarter.kt#L186)\u00a0`unlock`\u00a0on our side\u00a0and from the breadcrumbs we know that the code is reaching that line. So it might be that this\u00a0`unlock`\u00a0is actually unlocking the mutex\u00a0**at the same time as**\u00a0the whole cancellation flow I mentioned above is happening (_which would be possible because of the multiple threads in the Dispatcher pool_), so when the cancelation reaches the\u00a0`onCancellation`\u00a0[callback here](https://github.com/Kotlin/kotlinx.coroutines/blob/02382479398518ea1c4507170aa92692595b6839/kotlinx-coroutines-core/common/src/sync/Mutex.kt#L253-L255) our code already unlocked it, causing the crash to happen in the\u00a0`Mutex`\u00a0internals.\r\n\r\nThis is my best guess, but the Mutex/Semaphore code is a bit complex and I didn\u2019t fully understand it yet (and probably never will\u00a0\ud83d\ude06).\r\n\r\n### Suggestion\r\nRemove that `unlock`\u00a0[call ASAP](https://github.com/wordpress-mobile/WordPress-Android/blob/1b5e1f3fc97e13d0068ea803d5df7777f421180b/WordPress/src/main/java/org/wordpress/android/ui/uploads/UploadStarter.kt#L186)\u00a0as we really don\u2019t need it since we use\u00a0`withLock`\u00a0which is better in 2 ways:\r\n1. It makes sure to\u00a0`unlock`\u00a0when exceptions happen ([try/finally](https://github.com/Kotlin/kotlinx.coroutines/blob/02382479398518ea1c4507170aa92692595b6839/kotlinx-coroutines-core/common/src/sync/Mutex.kt#L120-L131))\r\n2. It only calls\u00a0`unlock`\u00a0if it was successfully locked before running the\u00a0`action`, so if my hypothesis above is correct, the internal\u00a0`lockSuspend`\u00a0code will cause a cancellation before reaching that\u00a0`try/finally`\u00a0block\r\n", "created_at": "2023-08-11T20:54:10Z", "version": "23.01", "FAIL_TO_PASS": [ "gradle_test_execution" ], "PASS_TO_PASS": [], "ERROR_TO_PASS": [], "environment_setup_commit": "cfb329ae952a18c517e71c9f66efb257da1fe136" }, { "repo": "wordpress-mobile/WordPress-Android", "pull_number": 20756, "instance_id": "wordpress-mobile__WordPress-Android-20756", "issue_numbers": [ "20691" ], "base_commit": "6c79ab16dc342b470d0be18d904120db267682aa", "patch": "diff --git a/RELEASE-NOTES.txt b/RELEASE-NOTES.txt\nindex ca376cca8b49..70f9185bdb38 100644\n--- a/RELEASE-NOTES.txt\n+++ b/RELEASE-NOTES.txt\n@@ -2,7 +2,7 @@\n \n 24.9\n -----\n-\n+* [***] [Jetpack-only] Reorganized Stats to include updated Traffic and Insights tabs, along with a newly added Subscribers tab to improve subscriber metrics analysis [https://github.com/wordpress-mobile/WordPress-Android/pull/20756]\n \n 24.8\n -----\ndiff --git a/WordPress/src/main/java/org/wordpress/android/ui/deeplinks/handlers/StatsLinkHandler.kt b/WordPress/src/main/java/org/wordpress/android/ui/deeplinks/handlers/StatsLinkHandler.kt\nindex ceed1dbb5b12..c083f900c464 100644\n--- a/WordPress/src/main/java/org/wordpress/android/ui/deeplinks/handlers/StatsLinkHandler.kt\n+++ b/WordPress/src/main/java/org/wordpress/android/ui/deeplinks/handlers/StatsLinkHandler.kt\n@@ -2,11 +2,11 @@ package org.wordpress.android.ui.deeplinks.handlers\n \n import org.wordpress.android.fluxc.model.SiteModel\n import org.wordpress.android.ui.deeplinks.DeepLinkNavigator.NavigateAction\n+import org.wordpress.android.ui.deeplinks.DeepLinkNavigator.NavigateAction.OpenJetpackStaticPosterView\n import org.wordpress.android.ui.deeplinks.DeepLinkNavigator.NavigateAction.OpenStats\n import org.wordpress.android.ui.deeplinks.DeepLinkNavigator.NavigateAction.OpenStatsForSite\n import org.wordpress.android.ui.deeplinks.DeepLinkNavigator.NavigateAction.OpenStatsForSiteAndTimeframe\n import org.wordpress.android.ui.deeplinks.DeepLinkNavigator.NavigateAction.OpenStatsForTimeframe\n-import org.wordpress.android.ui.deeplinks.DeepLinkNavigator.NavigateAction.OpenJetpackStaticPosterView\n import org.wordpress.android.ui.deeplinks.DeepLinkUriUtils\n import org.wordpress.android.ui.deeplinks.DeepLinkingIntentReceiverViewModel.Companion.APPLINK_SCHEME\n import org.wordpress.android.ui.deeplinks.DeepLinkingIntentReceiverViewModel.Companion.HOST_WORDPRESS_COM\n@@ -32,7 +32,8 @@ class StatsLinkHandler\n val pathSegments = uri.pathSegments\n val length = pathSegments.size\n val site = pathSegments.getOrNull(length - 1)?.toSite()\n- val statsTimeframe = pathSegments.getOrNull(length - 2)?.toStatsTimeframe()\n+ val timeframeIndex = if (site == null) (length - 1) else (length - 2)\n+ val statsTimeframe = pathSegments.getOrNull(timeframeIndex)?.toStatsTimeframe()\n return when {\n jetpackFeatureRemovalPhaseHelper.shouldShowStaticPage() -> OpenJetpackStaticPosterView\n site != null && statsTimeframe != null -> {\n@@ -98,6 +99,7 @@ class StatsLinkHandler\n \"month\" -> StatsTimeframe.MONTH\n \"year\" -> StatsTimeframe.YEAR\n \"insights\" -> StatsTimeframe.INSIGHTS\n+ \"subscribers\" -> StatsTimeframe.SUBSCRIBERS\n else -> null\n }\n }\ndiff --git a/WordPress/src/main/java/org/wordpress/android/ui/stats/refresh/StatsFragment.kt b/WordPress/src/main/java/org/wordpress/android/ui/stats/refresh/StatsFragment.kt\nindex 915d8637eb93..faabf6c0f856 100644\n--- a/WordPress/src/main/java/org/wordpress/android/ui/stats/refresh/StatsFragment.kt\n+++ b/WordPress/src/main/java/org/wordpress/android/ui/stats/refresh/StatsFragment.kt\n@@ -19,6 +19,7 @@ import dagger.hilt.android.AndroidEntryPoint\n import org.wordpress.android.R\n import org.wordpress.android.WordPress\n import org.wordpress.android.databinding.StatsFragmentBinding\n+import org.wordpress.android.models.JetpackPoweredScreen\n import org.wordpress.android.ui.ScrollableViewInitializedListener\n import org.wordpress.android.ui.jetpackoverlay.JetpackFeatureFullScreenOverlayFragment\n import org.wordpress.android.ui.jetpackoverlay.JetpackFeatureRemovalOverlayUtil.JetpackFeatureOverlayScreenType\n@@ -38,13 +39,12 @@ import org.wordpress.android.ui.stats.refresh.lists.StatsListViewModel.StatsSect\n import org.wordpress.android.ui.stats.refresh.lists.StatsListViewModel.StatsSection.TOTAL_COMMENTS_DETAIL\n import org.wordpress.android.ui.stats.refresh.lists.StatsListViewModel.StatsSection.TOTAL_FOLLOWERS_DETAIL\n import org.wordpress.android.ui.stats.refresh.lists.StatsListViewModel.StatsSection.TOTAL_LIKES_DETAIL\n+import org.wordpress.android.ui.stats.refresh.lists.StatsListViewModel.StatsSection.TRAFFIC\n import org.wordpress.android.ui.stats.refresh.lists.StatsListViewModel.StatsSection.WEEKS\n import org.wordpress.android.ui.stats.refresh.lists.StatsListViewModel.StatsSection.YEARS\n import org.wordpress.android.ui.stats.refresh.utils.StatsSiteProvider.SiteUpdateResult\n import org.wordpress.android.ui.utils.UiHelpers\n import org.wordpress.android.util.JetpackBrandingUtils\n-import org.wordpress.android.models.JetpackPoweredScreen\n-import org.wordpress.android.ui.stats.refresh.lists.StatsListViewModel.StatsSection.TRAFFIC\n import org.wordpress.android.util.WPSwipeToRefreshHelper\n import org.wordpress.android.util.config.StatsTrafficSubscribersTabFeatureConfig\n import org.wordpress.android.util.helpers.SwipeToRefreshHelper\n@@ -224,10 +224,7 @@ class StatsFragment : Fragment(R.layout.stats_fragment), ScrollableViewInitializ\n }\n }\n \n- @Suppress(\"MagicNumber\")\n- private fun StatsFragmentBinding.handleSelectedSectionWithTrafficTab(\n- selectedSection: StatsSection\n- ) {\n+ private fun StatsFragmentBinding.handleSelectedSectionWithTrafficTab(selectedSection: StatsSection) {\n val position = when (selectedSection) {\n TRAFFIC -> 0\n INSIGHTS -> 1\n@@ -243,16 +240,14 @@ class StatsFragment : Fragment(R.layout.stats_fragment), ScrollableViewInitializ\n position?.let {\n if (statsPager.currentItem != position) {\n tabLayout.removeOnTabSelectedListener(selectedTabListener)\n- statsPager.setCurrentItem(position, false)\n+ statsPager.currentItem = position\n tabLayout.addOnTabSelectedListener(selectedTabListener)\n }\n }\n }\n \n @Suppress(\"MagicNumber\")\n- private fun StatsFragmentBinding.handleSelectedSection(\n- selectedSection: StatsSection\n- ) {\n+ private fun StatsFragmentBinding.handleSelectedSection(selectedSection: StatsSection) {\n val position = when (selectedSection) {\n INSIGHTS -> 0\n DAYS -> 1\n@@ -270,7 +265,7 @@ class StatsFragment : Fragment(R.layout.stats_fragment), ScrollableViewInitializ\n position?.let {\n if (statsPager.currentItem != position) {\n tabLayout.removeOnTabSelectedListener(selectedTabListener)\n- statsPager.setCurrentItem(position, false)\n+ statsPager.currentItem = position\n tabLayout.addOnTabSelectedListener(selectedTabListener)\n }\n }\n", "test_patch": "diff --git a/WordPress/src/test/java/org/wordpress/android/ui/deeplinks/handlers/StatsLinkHandlerTest.kt b/WordPress/src/test/java/org/wordpress/android/ui/deeplinks/handlers/StatsLinkHandlerTest.kt\nindex 1c6984ff5c9d..35fa892d67c7 100644\n--- a/WordPress/src/test/java/org/wordpress/android/ui/deeplinks/handlers/StatsLinkHandlerTest.kt\n+++ b/WordPress/src/test/java/org/wordpress/android/ui/deeplinks/handlers/StatsLinkHandlerTest.kt\n@@ -15,6 +15,7 @@ import org.wordpress.android.ui.jetpackoverlay.JetpackFeatureRemovalPhaseHelper\n import org.wordpress.android.ui.stats.StatsTimeframe.DAY\n import org.wordpress.android.ui.stats.StatsTimeframe.INSIGHTS\n import org.wordpress.android.ui.stats.StatsTimeframe.MONTH\n+import org.wordpress.android.ui.stats.StatsTimeframe.SUBSCRIBERS\n import org.wordpress.android.ui.stats.StatsTimeframe.WEEK\n import org.wordpress.android.ui.stats.StatsTimeframe.YEAR\n \n@@ -108,7 +109,8 @@ class StatsLinkHandlerTest {\n \"week\" to WEEK,\n \"month\" to MONTH,\n \"year\" to YEAR,\n- \"insights\" to INSIGHTS\n+ \"insights\" to INSIGHTS,\n+ \"subscribers\" to SUBSCRIBERS\n )\n timeframes.forEach { (key, timeframe) ->\n val uri = buildUri(host = null, \"stats\", key, siteUrl)\n@@ -125,6 +127,25 @@ class StatsLinkHandlerTest {\n }\n }\n \n+ @Test\n+ fun `opens stats screen for a stats timeframe and no site present in URL`() {\n+ val timeframes = mapOf(\n+ \"day\" to DAY,\n+ \"week\" to WEEK,\n+ \"month\" to MONTH,\n+ \"year\" to YEAR,\n+ \"insights\" to INSIGHTS,\n+ \"subscribers\" to SUBSCRIBERS\n+ )\n+ timeframes.forEach { (key, timeframe) ->\n+ val uri = buildUri(host = null, \"stats\", key)\n+\n+ val buildNavigateAction = statsLinkHandler.buildNavigateAction(uri)\n+\n+ assertThat(buildNavigateAction).isEqualTo(NavigateAction.OpenStatsForTimeframe(timeframe))\n+ }\n+ }\n+\n @Test\n fun `opens stats screen for a site when timeframe not valid`() {\n val siteUrl = \"example.com\"\n", "problem_statement": "Deep link support\nFull Scope: https://github.com/Automattic/wordpress-mobile/issues/47\nDesign: [IqhXWz3Iir7RMb5XH5gGfZ-fi-883%3A4006](https://href.li/?https://www.figma.com/file/IqhXWz3Iir7RMb5XH5gGfZ/?node-id=883%3A4006)\n\n- Deep link to Subscribers tab\n- Deep link to Traffic tab with appropriate granularity selected\n", "hints_text": "Thanks for reporting! \ud83d\udc4d \n", "created_at": "2024-05-02T20:22:12Z", "version": "24.83", "FAIL_TO_PASS": [ "gradle_test_execution" ], "PASS_TO_PASS": [], "ERROR_TO_PASS": [], "environment_setup_commit": "400df84278f796e2638f14ff71e9115f9062cf59" }, { "repo": "wordpress-mobile/WordPress-Android", "pull_number": 19574, "instance_id": "wordpress-mobile__WordPress-Android-19574", "issue_numbers": [ "19563" ], "base_commit": "44a38b0844874b5dfd1caa198ee678dd6264ff3e", "patch": "diff --git a/WordPress/src/main/java/org/wordpress/android/ui/domains/management/newdomainsearch/NewDomainSearchViewModel.kt b/WordPress/src/main/java/org/wordpress/android/ui/domains/management/newdomainsearch/NewDomainSearchViewModel.kt\nindex 9c79f4b6a217..f1a3a1af30d2 100644\n--- a/WordPress/src/main/java/org/wordpress/android/ui/domains/management/newdomainsearch/NewDomainSearchViewModel.kt\n+++ b/WordPress/src/main/java/org/wordpress/android/ui/domains/management/newdomainsearch/NewDomainSearchViewModel.kt\n@@ -3,6 +3,7 @@ package org.wordpress.android.ui.domains.management.newdomainsearch\n import androidx.lifecycle.viewModelScope\n import dagger.hilt.android.lifecycle.HiltViewModel\n import kotlinx.coroutines.CoroutineDispatcher\n+import kotlinx.coroutines.ExperimentalCoroutinesApi\n import kotlinx.coroutines.FlowPreview\n import kotlinx.coroutines.flow.Flow\n import kotlinx.coroutines.flow.MutableSharedFlow\n@@ -10,11 +11,14 @@ import kotlinx.coroutines.flow.MutableStateFlow\n import kotlinx.coroutines.flow.asStateFlow\n import kotlinx.coroutines.flow.debounce\n import kotlinx.coroutines.flow.filter\n+import kotlinx.coroutines.flow.flatMapLatest\n+import kotlinx.coroutines.flow.flowOf\n import kotlinx.coroutines.flow.launchIn\n import kotlinx.coroutines.flow.onEach\n import org.wordpress.android.analytics.AnalyticsTracker\n import org.wordpress.android.modules.UI_THREAD\n import org.wordpress.android.ui.domains.management.newdomainsearch.domainsfetcher.NewDomainsSearchRepository\n+import org.wordpress.android.ui.domains.management.newdomainsearch.domainsfetcher.NewDomainsSearchRepository.DomainsResult\n import org.wordpress.android.ui.domains.management.newdomainsearch.domainsfetcher.ProposedDomain\n import org.wordpress.android.util.analytics.AnalyticsTrackerWrapper\n import org.wordpress.android.viewmodel.ScopedViewModel\n@@ -23,7 +27,7 @@ import javax.inject.Named\n \n private const val SEARCH_QUERY_DELAY_MS = 250L\n \n-@OptIn(FlowPreview::class)\n+@OptIn(FlowPreview::class, ExperimentalCoroutinesApi::class)\n @HiltViewModel\n class NewDomainSearchViewModel @Inject constructor(\n @Named(UI_THREAD) private val mainDispatcher: CoroutineDispatcher,\n@@ -43,24 +47,28 @@ class NewDomainSearchViewModel @Inject constructor(\n debouncedQuery\n .filter { it.isNotBlank() }\n .debounce(SEARCH_QUERY_DELAY_MS)\n- .onEach(::fetchDomains)\n+ .flatMapLatest { query -> flowOf(fetchDomains(query)) }\n+ .onEach(::handleDomainsResult)\n .launchIn(viewModelScope)\n }\n \n- private suspend fun fetchDomains(query: String) {\n+ private suspend fun fetchDomains(query: String): DomainsResult {\n _uiStateFlow.emit(UiState.Loading)\n- val result = newDomainsSearchRepository.searchForDomains(query)\n+ return newDomainsSearchRepository.searchForDomains(query)\n+ }\n+\n+ private suspend fun handleDomainsResult(result: DomainsResult) {\n _uiStateFlow.emit(\n when (result) {\n- is NewDomainsSearchRepository.DomainsResult.Success -> UiState.PopulatedDomains(result.proposedDomains)\n- is NewDomainsSearchRepository.DomainsResult.Error -> UiState.Error\n+ is DomainsResult.Success -> UiState.PopulatedDomains(result.proposedDomains)\n+ is DomainsResult.Error -> UiState.Error\n }\n )\n }\n \n fun onSearchQueryChanged(query: String) {\n launch {\n- debouncedQuery.emit(query.trim())\n+ debouncedQuery.emit(query.trim())\n }\n }\n \n@@ -99,6 +107,7 @@ class NewDomainSearchViewModel @Inject constructor(\n val domain: String,\n val supportsPrivacy: Boolean\n ) : ActionEvent()\n+\n data class TransferDomain(val url: String) : ActionEvent()\n object GoBack : ActionEvent()\n }\n", "test_patch": "diff --git a/WordPress/src/test/java/org/wordpress/android/ui/domains/management/newdomainsearch/NewDomainSearchViewModelTest.kt b/WordPress/src/test/java/org/wordpress/android/ui/domains/management/newdomainsearch/NewDomainSearchViewModelTest.kt\nindex 6298a2ee56d5..c27fdfb1fe44 100644\n--- a/WordPress/src/test/java/org/wordpress/android/ui/domains/management/newdomainsearch/NewDomainSearchViewModelTest.kt\n+++ b/WordPress/src/test/java/org/wordpress/android/ui/domains/management/newdomainsearch/NewDomainSearchViewModelTest.kt\n@@ -11,6 +11,7 @@ import org.junit.Test\n import org.mockito.Mock\n import org.mockito.MockitoAnnotations\n import org.mockito.kotlin.argWhere\n+import org.mockito.kotlin.doSuspendableAnswer\n import org.mockito.kotlin.eq\n import org.mockito.kotlin.never\n import org.mockito.kotlin.times\n@@ -89,11 +90,11 @@ class NewDomainSearchViewModelTest : BaseUnitTest() {\n \n @Test\n fun `WHEN transfer domain button pressed THEN track DOMAIN_MANAGEMENT_TRANSFER_DOMAIN_TAPPED event`() = test {\n- viewModel.onTransferDomainClicked()\n- advanceUntilIdle()\n+ viewModel.onTransferDomainClicked()\n+ advanceUntilIdle()\n \n- verify(analyticsTracker).track(AnalyticsTracker.Stat.DOMAIN_MANAGEMENT_TRANSFER_DOMAIN_TAPPED)\n- }\n+ verify(analyticsTracker).track(AnalyticsTracker.Stat.DOMAIN_MANAGEMENT_TRANSFER_DOMAIN_TAPPED)\n+ }\n \n @Test\n fun `WHEN back button pressed THEN send GoBack action event`() = testWithActionEvents { events ->\n@@ -106,8 +107,9 @@ class NewDomainSearchViewModelTest : BaseUnitTest() {\n @Suppress(\"MaxLineLength\")\n @Test\n fun `GIVEN few queries requested within 250 ms query delay WHEN onSearchQueryChanged THEN search for domains with the last query only`() =\n- test {\n- whenever(repository.searchForDomains(\"third\")).thenReturn(DomainsResult.Success(emptyList()))\n+ testWithUiStates { states ->\n+ val result = listOf(ProposedDomain(0, \"\", \"\", \"\", true))\n+ whenever(repository.searchForDomains(\"third\")).thenReturn(DomainsResult.Success(result))\n \n viewModel.onSearchQueryChanged(\"first\")\n delay(200)\n@@ -118,16 +120,22 @@ class NewDomainSearchViewModelTest : BaseUnitTest() {\n \n verify(repository, never()).searchForDomains(\"first\")\n verify(repository, never()).searchForDomains(\"second\")\n- verify(repository).searchForDomains(\"third\")\n+\n+ assertThat(states.first()).isEqualTo(UiState.PopulatedDomains(emptyList())) // Initial\n+ assertThat(states[1]).isEqualTo(UiState.Loading)\n+ assertThat(states[2]).isEqualTo(UiState.PopulatedDomains(result))\n }\n \n @Suppress(\"MaxLineLength\")\n @Test\n fun `GIVEN few queries requested outside 250 ms delay WHEN onSearchQueryChanged THEN search for domains with all the queries`() =\n- test {\n- whenever(repository.searchForDomains(\"first\")).thenReturn(DomainsResult.Success(emptyList()))\n- whenever(repository.searchForDomains(\"second\")).thenReturn(DomainsResult.Success(emptyList()))\n- whenever(repository.searchForDomains(\"third\")).thenReturn(DomainsResult.Success(emptyList()))\n+ testWithUiStates { states ->\n+ val firstResult = listOf(ProposedDomain(0, \"\", \"\", \"\", true))\n+ val secondResult = listOf(ProposedDomain(1, \"\", \"\", \"\", true))\n+ val thirdResult = listOf(ProposedDomain(2, \"\", \"\", \"\", true))\n+ whenever(repository.searchForDomains(\"first\")).thenReturn(DomainsResult.Success(firstResult))\n+ whenever(repository.searchForDomains(\"second\")).thenReturn(DomainsResult.Success(secondResult))\n+ whenever(repository.searchForDomains(\"third\")).thenReturn(DomainsResult.Success(thirdResult))\n \n viewModel.onSearchQueryChanged(\"first\")\n delay(250)\n@@ -136,9 +144,36 @@ class NewDomainSearchViewModelTest : BaseUnitTest() {\n viewModel.onSearchQueryChanged(\"third\")\n advanceUntilIdle()\n \n- verify(repository).searchForDomains(\"first\")\n- verify(repository).searchForDomains(\"second\")\n- verify(repository).searchForDomains(\"third\")\n+ assertThat(states.first()).isEqualTo(UiState.PopulatedDomains(emptyList())) // Initial\n+ assertThat(states[1]).isEqualTo(UiState.Loading)\n+ assertThat(states[2]).isEqualTo(UiState.PopulatedDomains(firstResult))\n+ assertThat(states[3]).isEqualTo(UiState.Loading)\n+ assertThat(states[4]).isEqualTo(UiState.PopulatedDomains(secondResult))\n+ assertThat(states[5]).isEqualTo(UiState.Loading)\n+ assertThat(states[6]).isEqualTo(UiState.PopulatedDomains(thirdResult))\n+ }\n+\n+ @Suppress(\"MaxLineLength\")\n+ @Test\n+ fun `GIVEN recent query is appeared when previous request is in progress WHEN onSearchQueryChanged THEN cancel previous request and return result for the last query only`() =\n+ testWithUiStates { states ->\n+ val firstResult = listOf(ProposedDomain(0, \"\", \"\", \"\", true))\n+ val secondResult = listOf(ProposedDomain(1, \"\", \"\", \"\", true))\n+\n+ whenever(repository.searchForDomains(\"first\")).doSuspendableAnswer {\n+ delay(301)\n+ DomainsResult.Success(firstResult)\n+ }\n+ whenever(repository.searchForDomains(\"second\")).thenReturn(DomainsResult.Success(secondResult))\n+\n+ viewModel.onSearchQueryChanged(\"first\")\n+ delay(300)\n+ viewModel.onSearchQueryChanged(\"second\")\n+ advanceUntilIdle()\n+\n+ assertThat(states.first()).isEqualTo(UiState.PopulatedDomains(emptyList())) // Initial\n+ assertThat(states[1]).isEqualTo(UiState.Loading)\n+ assertThat(states[2]).isEqualTo(UiState.PopulatedDomains(secondResult))\n }\n \n @Test\n@@ -186,20 +221,21 @@ class NewDomainSearchViewModelTest : BaseUnitTest() {\n \n @Suppress(\"MaxLineLength\")\n @Test\n- fun `GIVEN repeated queries with redundant blank symbols WHEN onSearchQueryChanged THEN fetch domains only once`() = test {\n- whenever(repository.searchForDomains(\"query\")).thenReturn(DomainsResult.Success(emptyList()))\n+ fun `GIVEN repeated queries with redundant blank symbols WHEN onSearchQueryChanged THEN fetch domains only once`() =\n+ test {\n+ whenever(repository.searchForDomains(\"query\")).thenReturn(DomainsResult.Success(emptyList()))\n \n- viewModel.onSearchQueryChanged(\"query\")\n- delay(250)\n- viewModel.onSearchQueryChanged(\" query\")\n- delay(250)\n- viewModel.onSearchQueryChanged(\"query \")\n- advanceUntilIdle()\n+ viewModel.onSearchQueryChanged(\"query\")\n+ delay(250)\n+ viewModel.onSearchQueryChanged(\" query\")\n+ delay(250)\n+ viewModel.onSearchQueryChanged(\"query \")\n+ advanceUntilIdle()\n \n- verify(repository, times(1)).searchForDomains(\"query\")\n- verify(repository, never()).searchForDomains(\" query\")\n- verify(repository, never()).searchForDomains(\"query \")\n- }\n+ verify(repository, times(1)).searchForDomains(\"query\")\n+ verify(repository, never()).searchForDomains(\" query\")\n+ verify(repository, never()).searchForDomains(\"query \")\n+ }\n \n private fun testWithActionEvents(block: suspend TestScope.(events: List) -> Unit) = test {\n val actionEvents = mutableListOf()\n", "problem_statement": "\ud83e\udd16 Cancel stale requests on domain search screen\nWhen searching for a new domain (to purchase) within the domain management flow, the results of multiple requests are loaded sequentially after typing. Only the latest request should be used to update the pending / loading screen.\n\nNote that this is a separate concern from the debounce delay (used to throttle requests and reduce wasted fetches on keystrokes). Increasing the debounce delay _could_ mitigate the buggy results ux, but this has a tradeoff of increasing the total time to success. Instead, we should ensure that only the response to the latest request can update the ui state.\n", "hints_text": "", "created_at": "2023-11-08T19:58:24Z", "version": "23.61", "FAIL_TO_PASS": [ "gradle_test_execution" ], "PASS_TO_PASS": [], "ERROR_TO_PASS": [], "environment_setup_commit": "9fc79ceb9a6bcbdaa7adfd45dd9e6f80636120a6" }, { "repo": "wordpress-mobile/WordPress-Android", "pull_number": 20057, "instance_id": "wordpress-mobile__WordPress-Android-20057", "issue_numbers": [ "19898" ], "base_commit": "e01610c0eaaccf7a8b20976ca58a628ee6efcce8", "patch": "diff --git a/WordPress/src/main/java/org/wordpress/android/ui/reader/ReaderConstants.java b/WordPress/src/main/java/org/wordpress/android/ui/reader/ReaderConstants.java\nindex 504d71f1de01..c0798c5824ca 100644\n--- a/WordPress/src/main/java/org/wordpress/android/ui/reader/ReaderConstants.java\n+++ b/WordPress/src/main/java/org/wordpress/android/ui/reader/ReaderConstants.java\n@@ -67,7 +67,7 @@ public class ReaderConstants {\n static final String KEY_FIRST_LOAD = \"first_load\";\n static final String KEY_ACTIVITY_TITLE = \"activity_title\";\n static final String KEY_TRACKED_POSITIONS = \"tracked_positions\";\n- static final String KEY_IS_REFRESHING = \"is_refreshing\";\n+ static final String KEY_CURRENT_UPDATE_ACTIONS = \"current_update_actions\";\n static final String KEY_ACTIVE_SEARCH_TAB = \"active_search_tab\";\n static final String KEY_SITE_ID = \"site_id\";\n \ndiff --git a/WordPress/src/main/java/org/wordpress/android/ui/reader/ReaderPostListFragment.java b/WordPress/src/main/java/org/wordpress/android/ui/reader/ReaderPostListFragment.java\nindex 445ac315c255..763d944c130c 100644\n--- a/WordPress/src/main/java/org/wordpress/android/ui/reader/ReaderPostListFragment.java\n+++ b/WordPress/src/main/java/org/wordpress/android/ui/reader/ReaderPostListFragment.java\n@@ -144,8 +144,10 @@\n import org.wordpress.android.widgets.RecyclerItemDecoration;\n import org.wordpress.android.widgets.WPSnackbar;\n \n+import java.io.Serializable;\n import java.util.ArrayList;\n import java.util.EnumSet;\n+import java.util.HashSet;\n import java.util.List;\n import java.util.Stack;\n \n@@ -210,9 +212,9 @@ public class ReaderPostListFragment extends ViewPagerFragment\n private int mPostSearchAdapterPos;\n private int mSiteSearchAdapterPos;\n private int mSearchTabsPos = NO_POSITION;\n- private boolean mIsUpdating;\n private boolean mIsFilterableScreen;\n private boolean mIsFiltered = false;\n+ @NonNull private HashSet mCurrentUpdateActions = new HashSet<>();\n /*\n * called by post adapter to load older posts when user scrolls to the last post\n */\n@@ -957,8 +959,8 @@ public void onSaveInstanceState(@NonNull Bundle outState) {\n outState.putBoolean(ReaderConstants.KEY_ALREADY_REQUESTED, mHasRequestedPosts);\n outState.putBoolean(ReaderConstants.KEY_ALREADY_UPDATED, mHasUpdatedPosts);\n outState.putBoolean(ReaderConstants.KEY_FIRST_LOAD, mFirstLoad);\n+ outState.putSerializable(ReaderConstants.KEY_CURRENT_UPDATE_ACTIONS, mCurrentUpdateActions);\n if (mRecyclerView != null) {\n- outState.putBoolean(ReaderConstants.KEY_IS_REFRESHING, mRecyclerView.isRefreshing());\n outState.putInt(ReaderConstants.KEY_RESTORE_POSITION, getCurrentPosition());\n }\n outState.putSerializable(ReaderConstants.ARG_POST_LIST_TYPE, getPostListType());\n@@ -1180,9 +1182,12 @@ public void onShowCustomEmptyView(EmptyViewMessageType emptyViewMsgType) {\n }\n }\n \n- if (savedInstanceState != null && savedInstanceState.getBoolean(ReaderConstants.KEY_IS_REFRESHING)) {\n- mIsUpdating = true;\n- mRecyclerView.setRefreshing(true);\n+ if (savedInstanceState != null) {\n+ Serializable actions = savedInstanceState.getSerializable(ReaderConstants.KEY_CURRENT_UPDATE_ACTIONS);\n+ if (actions instanceof HashSet) {\n+ mCurrentUpdateActions = (HashSet) actions;\n+ updateProgressIndicators();\n+ }\n }\n \n return rootView;\n@@ -1699,7 +1704,7 @@ private void setEmptyTitleDescriptionAndButton(boolean requestFailed) {\n setEmptyTitleAndDescriptionForBookmarksList();\n return;\n } else if (!NetworkUtils.isNetworkAvailable(getActivity())) {\n- mIsUpdating = false;\n+ clearCurrentUpdateActions();\n title = getString(R.string.reader_empty_posts_no_connection);\n } else if (requestFailed) {\n if (isSearching()) {\n@@ -2304,7 +2309,7 @@ public void run() {\n }\n \n private boolean isUpdating() {\n- return mIsUpdating;\n+ return mCurrentUpdateActions.size() > 0;\n }\n \n /*\n@@ -2321,27 +2326,45 @@ private void showLoadingProgress(boolean showProgress) {\n }\n }\n \n- private void setIsUpdating(boolean isUpdating, UpdateAction updateAction) {\n- if (!isAdded() || mIsUpdating == isUpdating) {\n- return;\n- }\n+ private void clearCurrentUpdateActions() {\n+ if (!isAdded() || !isUpdating()) return;\n \n- if (updateAction == UpdateAction.REQUEST_OLDER) {\n- // show/hide progress bar at bottom if these are older posts\n- showLoadingProgress(isUpdating);\n- } else if (isUpdating) {\n- // show swipe-to-refresh if update started\n- mRecyclerView.setRefreshing(true);\n+ mCurrentUpdateActions.clear();\n+ updateProgressIndicators();\n+ }\n+\n+ private void setIsUpdating(boolean isUpdating, @NonNull UpdateAction updateAction) {\n+ if (!isAdded()) return;\n+\n+ boolean isUiUpdateNeeded;\n+ if (isUpdating) {\n+ isUiUpdateNeeded = mCurrentUpdateActions.add(updateAction);\n } else {\n- // hide swipe-to-refresh progress if update is complete\n+ isUiUpdateNeeded = mCurrentUpdateActions.remove(updateAction);\n+ }\n+\n+ if (isUiUpdateNeeded) updateProgressIndicators();\n+ }\n+\n+ private void updateProgressIndicators() {\n+ if (!isUpdating()) {\n+ // when there's no update in progress, hide the bottom and swipe-to-refresh progress bars\n+ showLoadingProgress(false);\n mRecyclerView.setRefreshing(false);\n+ } else if (mCurrentUpdateActions.size() == 1 && mCurrentUpdateActions.contains(UpdateAction.REQUEST_OLDER)) {\n+ // if only older posts are being updated, show only the bottom progress bar\n+ showLoadingProgress(true);\n+ mRecyclerView.setRefreshing(false);\n+ } else {\n+ // if anything else is being updated, show only the swipe-to-refresh progress bar\n+ showLoadingProgress(false);\n+ mRecyclerView.setRefreshing(true);\n }\n- mIsUpdating = isUpdating;\n \n // if swipe-to-refresh isn't active, keep it disabled during an update - this prevents\n // doing a refresh while another update is already in progress\n- if (mRecyclerView != null && !mRecyclerView.isRefreshing()) {\n- mRecyclerView.setSwipeToRefreshEnabled(!isUpdating && isSwipeToRefreshSupported());\n+ if (!mRecyclerView.isRefreshing()) {\n+ mRecyclerView.setSwipeToRefreshEnabled(!isUpdating() && isSwipeToRefreshSupported());\n }\n }\n \ndiff --git a/WordPress/src/main/java/org/wordpress/android/ui/reader/tracker/ReaderTracker.kt b/WordPress/src/main/java/org/wordpress/android/ui/reader/tracker/ReaderTracker.kt\nindex 15822295422c..b40dfc0380ee 100644\n--- a/WordPress/src/main/java/org/wordpress/android/ui/reader/tracker/ReaderTracker.kt\n+++ b/WordPress/src/main/java/org/wordpress/android/ui/reader/tracker/ReaderTracker.kt\n@@ -388,6 +388,7 @@ class ReaderTracker @Inject constructor(\n readerTag.isPostsILike -> \"liked\"\n readerTag.isA8C -> \"a8c\"\n readerTag.isListTopic -> \"list\"\n+ readerTag.isP2 -> \"p2\"\n else -> null\n }?.let { trackingId ->\n analyticsTrackerWrapper.track(\ndiff --git a/WordPress/src/main/java/org/wordpress/android/ui/reader/utils/ReaderTopBarMenuHelper.kt b/WordPress/src/main/java/org/wordpress/android/ui/reader/utils/ReaderTopBarMenuHelper.kt\nindex 05f6f28d8c1b..26e2f876a83c 100644\n--- a/WordPress/src/main/java/org/wordpress/android/ui/reader/utils/ReaderTopBarMenuHelper.kt\n+++ b/WordPress/src/main/java/org/wordpress/android/ui/reader/utils/ReaderTopBarMenuHelper.kt\n@@ -31,6 +31,12 @@ class ReaderTopBarMenuHelper @Inject constructor() {\n readerTagsList.indexOrNull { it.isA8C }?.let { a8cIndex ->\n add(createAutomatticItem(getMenuItemIdFromReaderTagIndex(a8cIndex)))\n }\n+ readerTagsList.indexOrNull { it.isP2 }?.let { followedP2sIndex ->\n+ add(createFollowedP2sItem(\n+ id = getMenuItemIdFromReaderTagIndex(followedP2sIndex),\n+ text = readerTagsList[followedP2sIndex].tagTitle,\n+ ))\n+ }\n readerTagsList\n .foldIndexed(SparseArrayCompat()) { index, sparseArray, readerTag ->\n if (readerTag.tagType == ReaderTagType.CUSTOM_LIST) {\n@@ -85,6 +91,13 @@ class ReaderTopBarMenuHelper @Inject constructor() {\n )\n }\n \n+ private fun createFollowedP2sItem(id: String, text: String): MenuElementData.Item.Single {\n+ return MenuElementData.Item.Single(\n+ id = id,\n+ text = UiString.UiStringText(text),\n+ )\n+ }\n+\n private fun createCustomListsItem(customLists: SparseArrayCompat): MenuElementData.Item.SubMenu {\n val customListsMenuItems = mutableListOf()\n customLists.forEach { index, readerTag ->\n", "test_patch": "diff --git a/WordPress/src/test/java/org/wordpress/android/ui/reader/utils/ReaderTopBarMenuHelperTest.kt b/WordPress/src/test/java/org/wordpress/android/ui/reader/utils/ReaderTopBarMenuHelperTest.kt\nindex b8a4180dff9d..0279f25bee2d 100644\n--- a/WordPress/src/test/java/org/wordpress/android/ui/reader/utils/ReaderTopBarMenuHelperTest.kt\n+++ b/WordPress/src/test/java/org/wordpress/android/ui/reader/utils/ReaderTopBarMenuHelperTest.kt\n@@ -23,9 +23,10 @@ class ReaderTopBarMenuHelperTest {\n add(mockSavedTag()) // item 2\n add(mockLikedTag()) // item 3\n add(mockA8CTag()) // item 4\n- add(createCustomListTag(\"custom-list-1\")) // item 5\n- add(createCustomListTag(\"custom-list-2\")) // item 6\n- add(createCustomListTag(\"custom-list-3\")) // item 7\n+ add(mockFollowedP2sTag()) // item 5\n+ add(createCustomListTag(\"custom-list-1\")) // item 6\n+ add(createCustomListTag(\"custom-list-2\")) // item 7\n+ add(createCustomListTag(\"custom-list-3\")) // item 8\n }\n \n val menu = helper.createMenu(tags)\n@@ -46,18 +47,21 @@ class ReaderTopBarMenuHelperTest {\n val a8cItem = menu.findSingleItem { it.id == \"4\" }!!\n assertThat(a8cItem.text).isEqualTo(UiStringRes(R.string.reader_dropdown_menu_automattic))\n \n+ val followedP2sItem = menu.findSingleItem { it.id == \"5\" }!!\n+ assertThat(followedP2sItem.text).isEqualTo(UiStringText(\"Followed P2s\"))\n+\n assertThat(menu).contains(MenuElementData.Divider)\n \n val customListsItem = menu.findSubMenu()!!\n assertThat(customListsItem.text).isEqualTo(UiStringRes(R.string.reader_dropdown_menu_lists))\n \n- val customList1Item = customListsItem.children.findSingleItem { it.id == \"5\" }!!\n+ val customList1Item = customListsItem.children.findSingleItem { it.id == \"6\" }!!\n assertThat(customList1Item.text).isEqualTo(UiStringText(\"custom-list-1\"))\n \n- val customList2Item = customListsItem.children.findSingleItem { it.id == \"6\" }!!\n+ val customList2Item = customListsItem.children.findSingleItem { it.id == \"7\" }!!\n assertThat(customList2Item.text).isEqualTo(UiStringText(\"custom-list-2\"))\n \n- val customList3Item = customListsItem.children.findSingleItem { it.id == \"7\" }!!\n+ val customList3Item = customListsItem.children.findSingleItem { it.id == \"8\" }!!\n assertThat(customList3Item.text).isEqualTo(UiStringText(\"custom-list-3\"))\n }\n \n@@ -264,6 +268,13 @@ class ReaderTopBarMenuHelperTest {\n }\n }\n \n+ private fun mockFollowedP2sTag(): ReaderTag {\n+ return mock {\n+ on { isP2 } doReturn true\n+ on { tagTitle } doReturn \"Followed P2s\"\n+ }\n+ }\n+\n private fun createCustomListTag(title: String): ReaderTag {\n return ReaderTag(\n title,\n", "problem_statement": "[Reader IA - Bug] Followed P2s feed not showing in drop-down\n![image](https://github.com/wordpress-mobile/WordPress-Android/assets/47797566/e0725f07-6802-477c-9f39-d6bbe0baa8ea)\r\n\r\n>While comparing the viewpager tabs and feeds content for before / after, I see a missing menu item for \"Followed P2S\" (that is a filterable with only Sites and no Tags elements, I think similarly to the Automattic item)\r\n\r\nWhat I was trying to say here is (using the same user for the before/after):\r\n- the \"Followed P2s\" item is missing in the after\r\n\r\nAbout how to get the Followed P2s on your side, what follows is my best guess\r\n>I think that menu is related to P2 the product sites that I think I created in that account from https://p2help.wordpress.com/getting-started/creating-a-new-workspace/ if it's useful to create the test scenario.\r\n\r\nbut I can share my test account with you if it's quicker (just dm me in slack \ud83d\udc4d )\r\n\r\n_Originally posted by @develric in https://github.com/wordpress-mobile/WordPress-Android/issues/19856#issuecomment-1881059568_\n", "hints_text": "We should also consider adding the analytics event for when this menu item is clicked.", "created_at": "2024-01-26T20:57:01Z", "version": "24.12", "FAIL_TO_PASS": [ "gradle_test_execution" ], "PASS_TO_PASS": [], "ERROR_TO_PASS": [], "environment_setup_commit": "eeec54055af88943943cebf98b94519a527e1c7a" }, { "repo": "wordpress-mobile/WordPress-Android", "pull_number": 20480, "instance_id": "wordpress-mobile__WordPress-Android-20480", "issue_numbers": [ "20479" ], "base_commit": "3e2363d0223dd2b1feb74308e8cb433de4611af3", "patch": "diff --git a/WordPress/src/main/java/org/wordpress/android/ui/sitecreation/services/SiteCreationServiceManager.kt b/WordPress/src/main/java/org/wordpress/android/ui/sitecreation/services/SiteCreationServiceManager.kt\nindex 86a62720f401..b4dc3824e639 100644\n--- a/WordPress/src/main/java/org/wordpress/android/ui/sitecreation/services/SiteCreationServiceManager.kt\n+++ b/WordPress/src/main/java/org/wordpress/android/ui/sitecreation/services/SiteCreationServiceManager.kt\n@@ -136,7 +136,7 @@ class SiteCreationServiceManager @Inject constructor(\n */\n val errorMsg = \"Site already exists - seems like an issue with domain suggestions endpoint\"\n AppLog.e(T.SITE_CREATION, errorMsg)\n- throw IllegalStateException(errorMsg)\n+ executePhase(FAILURE)\n }\n } else {\n executePhase(FAILURE)\n", "test_patch": "diff --git a/WordPress/src/test/java/org/wordpress/android/ui/sitecreation/services/SiteCreationServiceManagerTest.kt b/WordPress/src/test/java/org/wordpress/android/ui/sitecreation/services/SiteCreationServiceManagerTest.kt\nindex a70333b10838..ed8ecd68a3a2 100644\n--- a/WordPress/src/test/java/org/wordpress/android/ui/sitecreation/services/SiteCreationServiceManagerTest.kt\n+++ b/WordPress/src/test/java/org/wordpress/android/ui/sitecreation/services/SiteCreationServiceManagerTest.kt\n@@ -134,6 +134,22 @@ class SiteCreationServiceManagerTest : BaseUnitTest() {\n }\n }\n \n+ @Test\n+ fun verifyFailureFlowWhenTheSiteExistsAndIsNotARetry() = test {\n+ setSiteExistsErrorResponses()\n+ val stateBeforeFailure = CREATE_SITE_STATE\n+ whenever(serviceListener.getCurrentState()).thenReturn(stateBeforeFailure)\n+\n+ startFlow()\n+ \n+ argumentCaptor().apply {\n+ verify(serviceListener, times(3)).updateState(capture())\n+ assertThat(allValues[0]).isEqualTo(IDLE_STATE)\n+ assertThat(allValues[1]).isEqualTo(CREATE_SITE_STATE)\n+ assertThat(allValues[2]).isEqualTo(FAILURE_STATE.copy(payload = stateBeforeFailure))\n+ }\n+ }\n+\n @Test\n fun verifyRetryWorksWhenCreateSiteRequestFailed() = test {\n setGenericErrorResponses()\n", "problem_statement": "IllegalStateException: Site already exists - seems like an issue with domain suggestions endpoint\nSentry Issue: [JETPACK-ANDROID-DZ0](https://a8c.sentry.io/issues/4584356763/?referrer=github_integration)\n\n```\nIllegalStateException: Site already exists - seems like an issue with domain suggestions endpoint\n at org.wordpress.android.ui.sitecreation.services.SiteCreationServiceManager$createSite$1.invokeSuspend(SiteCreationServiceManager.kt:139)\n at kotlin.coroutines.jvm.internal.BaseContinuationImpl.resumeWith(ContinuationImpl.kt:33)\n at kotlinx.coroutines.CoroutineContextKt.withContinuationContext\n at kotlinx.coroutines.DispatchedTask.run(DispatchedTask.kt:90)\n at kotlinx.coroutines.DispatchedTask.run(DispatchedTask.kt:108)\n...\n(4 additional frame(s) were not displayed)\n```\n", "hints_text": "Thanks for reporting! \ud83d\udc4d \n\nSentry Issue: [JETPACK-ANDROID-1RW](https://a8c.sentry.io/issues/3857462344/?referrer=github_integration)\nChecking the sentry logs all of them contain the following error:\r\n```\r\ne/WordPress-SITE_CREATION: Site already exists - seems like an issue with domain suggestions endpoint\r\n\r\nStackTrace: com.android.volley.ClientError\r\n\tat com.android.volley.toolbox.NetworkUtility.shouldRetryException(NetworkUtility.java:193)\r\n\tat com.android.volley.toolbox.BasicNetwork.performRequest(BasicNetwork.java:145)\r\n\tat com.android.volley.NetworkDispatcher.processRequest(NetworkDispatcher.java:132)\r\n\tat com.android.volley.NetworkDispatcher.processRequest(NetworkDispatcher.java:111)\r\n\tat com.android.volley.NetworkDispatcher.run(NetworkDispatcher.java:90)\r\nVolley error on https://public-api.wordpress.com/rest/v1.1/sites/new/?locale=en_GB Status Code: 400 - exception: null\r\n```\r\n[Checking the Volley code](https://github.com/google/volley/blob/master/core/src/main/java/com/android/volley/toolbox/NetworkUtility.java#L191) the above should indicate that no retry is possible.\r\n\r\nChecking the stats ~2 users per day experience this crash\r\n\r\n![Screenshot 2024-03-15 at 1 07 54\u202fPM](https://github.com/wordpress-mobile/WordPress-Android/assets/304044/ff71f77b-ac3f-4d89-937f-eb8625f90d5c)\r\n![Screenshot 2024-03-15 at 1 18 55\u202fPM](https://github.com/wordpress-mobile/WordPress-Android/assets/304044/6bb14303-d964-4103-9012-520475cd494d)\r\n", "created_at": "2024-03-15T11:23:39Z", "version": "24.42", "FAIL_TO_PASS": [ "gradle_test_execution" ], "PASS_TO_PASS": [], "ERROR_TO_PASS": [], "environment_setup_commit": "3e2363d0223dd2b1feb74308e8cb433de4611af3" }, { "repo": "wordpress-mobile/WordPress-Android", "pull_number": 19387, "instance_id": "wordpress-mobile__WordPress-Android-19387", "issue_numbers": [ "19376" ], "base_commit": "1f67fab3cec29e0a96423985f5b9118084c246db", "patch": "diff --git a/RELEASE-NOTES.txt b/RELEASE-NOTES.txt\nindex 16c947e95b2f..d8cd410b4491 100644\n--- a/RELEASE-NOTES.txt\n+++ b/RELEASE-NOTES.txt\n@@ -4,6 +4,7 @@\n -----\n * [*] Block Editor: Split formatted text on triple Enter [https://github.com/WordPress/gutenberg/pull/53354]\n * [*] Block Editor: Quote block: Ensure border is visible with block-based themes in dark [https://github.com/WordPress/gutenberg/pull/54964]\n+* [***] [internal][Jetpack-only] [***] Added domain selection, plan selection, and checkout screens in site creation flow [https://github.com/wordpress-mobile/WordPress-Android/pull/19304]\n * [**] [Jetpack-only] Reader: Improvement of core UI elements, including feed cards, tag and site headers, buttons and recommendation sections [https://github.com/wordpress-mobile/WordPress-Android/pull/19267]\n \n 23.4\ndiff --git a/WordPress/src/main/java/org/wordpress/android/ui/sitecreation/SiteCreationMainVM.kt b/WordPress/src/main/java/org/wordpress/android/ui/sitecreation/SiteCreationMainVM.kt\nindex 3c52ce378bf6..aa95ec7b3a3a 100644\n--- a/WordPress/src/main/java/org/wordpress/android/ui/sitecreation/SiteCreationMainVM.kt\n+++ b/WordPress/src/main/java/org/wordpress/android/ui/sitecreation/SiteCreationMainVM.kt\n@@ -276,18 +276,6 @@ class SiteCreationMainVM @Inject constructor(\n \n fun onPlanSelection(plan: PlanModel) {\n siteCreationState = siteCreationState.copy(plan = plan)\n- if (plan.productSlug == \"free_plan\") {\n- // if they select a paid domain, then choose a free plan, with free domain on plan selection screen\n- siteCreationState = siteCreationState.copy(\n- domain = DomainModel(\n- domainName = plan.productName.orEmpty(),\n- isFree = true,\n- cost = \"\",\n- productId = 0,\n- supportsPrivacy = false\n- )\n- )\n- }\n wizardManager.showNextStep()\n }\n \n@@ -334,7 +322,7 @@ class SiteCreationMainVM @Inject constructor(\n \n fun onFreeSiteCreated(site: SiteModel) {\n siteCreationState = siteCreationState.copy(result = CreatedButNotFetched.NotInLocalDb(site))\n- if (checkNotNull(siteCreationState.domain).isFree) {\n+ if (siteCreationState.plan?.productSlug == \"free_plan\") {\n wizardManager.showNextStep()\n }\n }\ndiff --git a/WordPress/src/main/java/org/wordpress/android/ui/sitecreation/previews/SitePreviewViewModel.kt b/WordPress/src/main/java/org/wordpress/android/ui/sitecreation/previews/SitePreviewViewModel.kt\nindex 5e0fdb6ac0a6..bd7061edf214 100644\n--- a/WordPress/src/main/java/org/wordpress/android/ui/sitecreation/previews/SitePreviewViewModel.kt\n+++ b/WordPress/src/main/java/org/wordpress/android/ui/sitecreation/previews/SitePreviewViewModel.kt\n@@ -31,6 +31,7 @@ import org.wordpress.android.ui.utils.UiString.UiStringRes\n import org.wordpress.android.ui.utils.UiString.UiStringResWithParams\n import org.wordpress.android.util.AppLog\n import org.wordpress.android.util.AppLog.T\n+import org.wordpress.android.util.StringUtils\n import org.wordpress.android.util.UrlUtilsWrapper\n import org.wordpress.android.viewmodel.SingleLiveEvent\n import javax.inject.Inject\n@@ -84,7 +85,7 @@ class SitePreviewViewModel @Inject constructor(\n siteDesign = siteCreationState.siteDesign\n result = siteCreationState.result\n isFree = requireNotNull(siteCreationState.domain).isFree\n- domainName = requireNotNull(siteCreationState.domain).domainName\n+ domainName = getCleanUrl(result.site.url) ?: \"\"\n startPreLoadingWebView()\n if (result is CreatedButNotFetched) {\n launch {\n@@ -159,6 +160,8 @@ class SitePreviewViewModel @Inject constructor(\n }\n }\n \n+ private fun getCleanUrl(url: String) = StringUtils.removeTrailingSlash(urlUtils.removeScheme(url))\n+\n private fun createSitePreviewData(): UrlData {\n val url = domainName\n val subDomain = urlUtils.extractSubDomain(url)\ndiff --git a/WordPress/src/main/java/org/wordpress/android/ui/sitecreation/progress/SiteCreationProgressViewModel.kt b/WordPress/src/main/java/org/wordpress/android/ui/sitecreation/progress/SiteCreationProgressViewModel.kt\nindex 92ff9a618bb6..f72caa53fac7 100644\n--- a/WordPress/src/main/java/org/wordpress/android/ui/sitecreation/progress/SiteCreationProgressViewModel.kt\n+++ b/WordPress/src/main/java/org/wordpress/android/ui/sitecreation/progress/SiteCreationProgressViewModel.kt\n@@ -172,8 +172,12 @@ class SiteCreationProgressViewModel @Inject constructor(\n IDLE, CREATE_SITE -> Unit\n SUCCESS -> {\n site = mapPayloadToSiteModel(event.payload)\n- _onFreeSiteCreated.postValue(site) // MainVM will navigate forward if the domain is free\n- if (!domain.isFree && siteCreationState.plan?.productId != 0) {\n+\n+ val isFreePlan = siteCreationState.plan?.productSlug == \"free_plan\"\n+\n+ if (isFreePlan) {\n+ _onFreeSiteCreated.postValue(site) // MainVM will navigate forward if the domain is free\n+ } else {\n createCart()\n }\n }\n", "test_patch": "diff --git a/WordPress/src/test/java/org/wordpress/android/ui/sitecreation/SiteCreationFixtures.kt b/WordPress/src/test/java/org/wordpress/android/ui/sitecreation/SiteCreationFixtures.kt\nindex 0f9e67d2fa2e..91e4a571addb 100644\n--- a/WordPress/src/test/java/org/wordpress/android/ui/sitecreation/SiteCreationFixtures.kt\n+++ b/WordPress/src/test/java/org/wordpress/android/ui/sitecreation/SiteCreationFixtures.kt\n@@ -27,15 +27,23 @@ const val URL_CUSTOM = \"$SUB_DOMAIN.host.com\"\n const val SITE_SLUG = \"${SUB_DOMAIN}host0.wordpress.com\"\n val FREE_DOMAIN = DomainModel(URL, true, \"\", 1, false)\n val PAID_DOMAIN = DomainModel(URL_CUSTOM, false, \"$1\", 2, true)\n-val PLAN_MODEL = PlanModel(1009, \"paid_plan\", \"Personal\", isCurrentPlan = false, hasDomainCredit = false)\n+val PAID_PLAN = PlanModel(1009, \"paid_plan\", \"Personal\", isCurrentPlan = false, hasDomainCredit = false)\n+val FREE_PLAN = PlanModel(0, \"free_plan\", \"\", isCurrentPlan = false, hasDomainCredit = false)\n \n const val SITE_REMOTE_ID = 1L\n \n val SITE_CREATION_STATE = SiteCreationState(\n+ segmentId = 1,\n+ siteDesign = defaultTemplateSlug,\n+ domain = PAID_DOMAIN,\n+ plan = PAID_PLAN\n+)\n+\n+val SITE_CREATION_STATE_FREE = SiteCreationState(\n segmentId = 1,\n siteDesign = defaultTemplateSlug,\n domain = FREE_DOMAIN,\n- plan = PLAN_MODEL\n+ plan = FREE_PLAN\n )\n \n val SITE_MODEL = SiteModel().apply { siteId = SITE_REMOTE_ID; url = SITE_SLUG }\ndiff --git a/WordPress/src/test/java/org/wordpress/android/ui/sitecreation/SiteCreationMainVMTest.kt b/WordPress/src/test/java/org/wordpress/android/ui/sitecreation/SiteCreationMainVMTest.kt\nindex 2f800cb33c6a..96f79c2d1070 100644\n--- a/WordPress/src/test/java/org/wordpress/android/ui/sitecreation/SiteCreationMainVMTest.kt\n+++ b/WordPress/src/test/java/org/wordpress/android/ui/sitecreation/SiteCreationMainVMTest.kt\n@@ -200,6 +200,7 @@ class SiteCreationMainVMTest : BaseUnitTest() {\n @Test\n fun `on site created updates result`() = test {\n viewModel.onDomainsScreenFinished(FREE_DOMAIN)\n+ viewModel.onPlanSelection(FREE_PLAN)\n viewModel.onFreeSiteCreated(SITE_MODEL)\n assertThat(currentWizardState(viewModel).result).isEqualTo(RESULT_NOT_IN_LOCAL_DB)\n }\n@@ -208,6 +209,7 @@ class SiteCreationMainVMTest : BaseUnitTest() {\n fun `on site created for free domain shows next step`() {\n viewModel.onDomainsScreenFinished(FREE_DOMAIN).run { clearInvocations(wizardManager) }\n viewModel.onFreeSiteCreated(SITE_MODEL)\n+ viewModel.onPlanSelection(FREE_PLAN)\n verify(wizardManager).showNextStep()\n }\n \ndiff --git a/WordPress/src/test/java/org/wordpress/android/ui/sitecreation/progress/SiteCreationProgressViewModelTest.kt b/WordPress/src/test/java/org/wordpress/android/ui/sitecreation/progress/SiteCreationProgressViewModelTest.kt\nindex 2be76a5a723c..c54fa3b7fd51 100644\n--- a/WordPress/src/test/java/org/wordpress/android/ui/sitecreation/progress/SiteCreationProgressViewModelTest.kt\n+++ b/WordPress/src/test/java/org/wordpress/android/ui/sitecreation/progress/SiteCreationProgressViewModelTest.kt\n@@ -38,6 +38,7 @@ import org.wordpress.android.ui.sitecreation.RESULT_IN_CART\n import org.wordpress.android.ui.sitecreation.SERVICE_ERROR\n import org.wordpress.android.ui.sitecreation.SERVICE_SUCCESS\n import org.wordpress.android.ui.sitecreation.SITE_CREATION_STATE\n+import org.wordpress.android.ui.sitecreation.SITE_CREATION_STATE_FREE\n import org.wordpress.android.ui.sitecreation.SITE_REMOTE_ID\n import org.wordpress.android.ui.sitecreation.SITE_SLUG\n import org.wordpress.android.ui.sitecreation.SiteCreationState\n@@ -103,7 +104,7 @@ class SiteCreationProgressViewModelTest : BaseUnitTest() {\n \n @Test\n fun `on start emits service event for free domains with isFree true`() = test {\n- startViewModel(SITE_CREATION_STATE)\n+ startViewModel(SITE_CREATION_STATE_FREE)\n val request = assertNotNull(viewModel.startCreateSiteService.value).serviceData\n assertTrue(request.isFree)\n }\n@@ -131,7 +132,7 @@ class SiteCreationProgressViewModelTest : BaseUnitTest() {\n \n @Test\n fun `on start changes the loading text with animation after delay`() = test {\n- startViewModel()\n+ startViewModelFree()\n advanceTimeBy(LOADING_STATE_TEXT_ANIMATION_DELAY)\n verify(uiStateObserver).onChanged(check { it.animate })\n }\n@@ -188,7 +189,7 @@ class SiteCreationProgressViewModelTest : BaseUnitTest() {\n \n @Test\n fun `on service success propagates site`() {\n- startViewModel()\n+ startViewModelFree()\n viewModel.onSiteCreationServiceStateUpdated(SERVICE_SUCCESS)\n verify(onRemoteSiteCreatedObserver).onChanged(argThat {\n assertEquals(SITE_REMOTE_ID, siteId)\n@@ -308,5 +309,9 @@ class SiteCreationProgressViewModelTest : BaseUnitTest() {\n viewModel.start(state)\n }\n \n+ private fun startViewModelFree(state: SiteCreationState = SITE_CREATION_STATE_FREE) {\n+ viewModel.start(state)\n+ }\n+\n // endregion\n }\n", "problem_statement": "Update RELEASE-NOTES\n`[***] Added plan selection, domain selection, and checkout screens in site creation flow (...)`\n", "hints_text": "", "created_at": "2023-10-16T00:00:54Z", "version": "23.4", "FAIL_TO_PASS": [ "gradle_test_execution" ], "PASS_TO_PASS": [], "ERROR_TO_PASS": [], "environment_setup_commit": "1f67fab3cec29e0a96423985f5b9118084c246db" }, { "repo": "wordpress-mobile/WordPress-Android", "pull_number": 20103, "instance_id": "wordpress-mobile__WordPress-Android-20103", "issue_numbers": [ "20091" ], "base_commit": "eeec54055af88943943cebf98b94519a527e1c7a", "patch": "diff --git a/WordPress/src/main/java/org/wordpress/android/ui/reader/discover/ReaderDiscoverViewModel.kt b/WordPress/src/main/java/org/wordpress/android/ui/reader/discover/ReaderDiscoverViewModel.kt\nindex c9b02681ea84..2e7c7b954b95 100644\n--- a/WordPress/src/main/java/org/wordpress/android/ui/reader/discover/ReaderDiscoverViewModel.kt\n+++ b/WordPress/src/main/java/org/wordpress/android/ui/reader/discover/ReaderDiscoverViewModel.kt\n@@ -16,6 +16,7 @@ import org.wordpress.android.models.discover.ReaderDiscoverCard.ReaderRecommende\n import org.wordpress.android.models.discover.ReaderDiscoverCards\n import org.wordpress.android.modules.IO_THREAD\n import org.wordpress.android.modules.UI_THREAD\n+import org.wordpress.android.ui.bloggingprompts.BloggingPromptsPostTagProvider.Companion.BLOGGING_PROMPT_TAG\n import org.wordpress.android.ui.pages.SnackbarMessageHolder\n import org.wordpress.android.ui.reader.ReaderTypes.ReaderPostListType.TAG_FOLLOWED\n import org.wordpress.android.ui.reader.discover.ReaderCardUiState.ReaderPostNewUiState\n@@ -149,7 +150,10 @@ class ReaderDiscoverViewModel @Inject constructor(\n _uiState.addSource(readerDiscoverDataProvider.discoverFeed) { posts ->\n launch {\n val userTags = getFollowedTagsUseCase.get()\n- if (userTags.isEmpty()) {\n+\n+ // since new users have the dailyprompt tag followed by default, we need to ignore them when\n+ // checking if the user has any tags followed, so we show the onboarding state (ShowNoFollowedTags)\n+ if (userTags.filterNot { it.tagSlug == BLOGGING_PROMPT_TAG }.isEmpty()) {\n _uiState.value = DiscoverUiState.EmptyUiState.ShowNoFollowedTagsUiState {\n parentViewModel.onShowReaderInterests()\n }\ndiff --git a/WordPress/src/main/java/org/wordpress/android/ui/reader/discover/interests/ReaderInterestsViewModel.kt b/WordPress/src/main/java/org/wordpress/android/ui/reader/discover/interests/ReaderInterestsViewModel.kt\nindex fc06dca994c3..67be5e9cd0ec 100644\n--- a/WordPress/src/main/java/org/wordpress/android/ui/reader/discover/interests/ReaderInterestsViewModel.kt\n+++ b/WordPress/src/main/java/org/wordpress/android/ui/reader/discover/interests/ReaderInterestsViewModel.kt\n@@ -11,6 +11,7 @@ import org.wordpress.android.R\n import org.wordpress.android.analytics.AnalyticsTracker\n import org.wordpress.android.models.ReaderTag\n import org.wordpress.android.models.ReaderTagList\n+import org.wordpress.android.ui.bloggingprompts.BloggingPromptsPostTagProvider.Companion.BLOGGING_PROMPT_TAG\n import org.wordpress.android.ui.pages.SnackbarMessageHolder\n import org.wordpress.android.ui.reader.discover.interests.ReaderInterestsFragment.EntryPoint\n import org.wordpress.android.ui.reader.discover.interests.ReaderInterestsViewModel.DoneButtonUiState.DoneButtonDisabledUiState\n@@ -92,7 +93,9 @@ class ReaderInterestsViewModel @Inject constructor(\n }\n \n private fun checkAndLoadInterests(userTags: ReaderTagList) {\n- if (userTags.isEmpty()) {\n+ // since new users have the dailyprompt tag followed by default, we need to ignore them when\n+ // checking if the user has any tags followed, so we show the onboarding state (ShowNoFollowedTags)\n+ if (userTags.filterNot { it.tagSlug == BLOGGING_PROMPT_TAG }.isEmpty()) {\n loadInterests(userTags)\n } else {\n parentViewModel?.onCloseReaderInterests()\ndiff --git a/WordPress/src/main/res/layout/reader_interests_fragment_layout.xml b/WordPress/src/main/res/layout/reader_interests_fragment_layout.xml\nindex 22d0129f84ce..519613821ede 100644\n--- a/WordPress/src/main/res/layout/reader_interests_fragment_layout.xml\n+++ b/WordPress/src/main/res/layout/reader_interests_fragment_layout.xml\n@@ -66,7 +66,7 @@\n More from %s\n More on WordPress.com\n Visit site\n- Choose your topics\n+ Choose your interests\n View comments\n Welcome to Reader. Discover millions of blogs at your fingertips.\n Back\n", "test_patch": "diff --git a/WordPress/src/test/java/org/wordpress/android/ui/reader/discover/ReaderDiscoverViewModelTest.kt b/WordPress/src/test/java/org/wordpress/android/ui/reader/discover/ReaderDiscoverViewModelTest.kt\nindex 1db7219634ec..064409261b3c 100644\n--- a/WordPress/src/test/java/org/wordpress/android/ui/reader/discover/ReaderDiscoverViewModelTest.kt\n+++ b/WordPress/src/test/java/org/wordpress/android/ui/reader/discover/ReaderDiscoverViewModelTest.kt\n@@ -24,6 +24,7 @@ import org.wordpress.android.models.ReaderBlog\n import org.wordpress.android.models.ReaderPost\n import org.wordpress.android.models.ReaderTag\n import org.wordpress.android.models.ReaderTagList\n+import org.wordpress.android.models.ReaderTagType\n import org.wordpress.android.models.discover.ReaderDiscoverCard.InterestsYouMayLikeCard\n import org.wordpress.android.models.discover.ReaderDiscoverCard.ReaderPostCard\n import org.wordpress.android.models.discover.ReaderDiscoverCard.ReaderRecommendedBlogsCard\n@@ -292,6 +293,29 @@ class ReaderDiscoverViewModelTest : BaseUnitTest() {\n assertThat(uiStates[1]).isInstanceOf(ShowNoFollowedTagsUiState::class.java)\n }\n \n+ @Test\n+ fun `ShowFollowInterestsEmptyUiState is shown when the user follows only the daily prompt tag`() = test {\n+ // Arrange\n+ val tagsWithDailyPrompt = ReaderTagList().apply {\n+ add(\n+ ReaderTag(\n+ \"dailyprompt\",\n+ \"dailyprompt\",\n+ \"dailyprompt\",\n+ \"https://public-api.wordpress.com/rest/v1.2/read/tags/dailyprompt/posts\",\n+ ReaderTagType.DEFAULT\n+ )\n+ )\n+ }\n+ whenever(getFollowedTagsUseCase.get()).thenReturn(tagsWithDailyPrompt)\n+ val uiStates = init().uiStates\n+ // Act\n+ viewModel.start(parentViewModel)\n+ // Assert\n+ assertThat(uiStates.size).isEqualTo(2)\n+ assertThat(uiStates[1]).isInstanceOf(ShowNoFollowedTagsUiState::class.java)\n+ }\n+\n @Test\n fun `ShowNoPostsUiState is shown when the discoverFeed does not contain any posts`() = test {\n // Arrange\ndiff --git a/WordPress/src/test/java/org/wordpress/android/ui/reader/discover/interests/ReaderInterestsViewModelTest.kt b/WordPress/src/test/java/org/wordpress/android/ui/reader/discover/interests/ReaderInterestsViewModelTest.kt\nindex 4b3451b7141c..1943a6a2f15a 100644\n--- a/WordPress/src/test/java/org/wordpress/android/ui/reader/discover/interests/ReaderInterestsViewModelTest.kt\n+++ b/WordPress/src/test/java/org/wordpress/android/ui/reader/discover/interests/ReaderInterestsViewModelTest.kt\n@@ -87,6 +87,20 @@ class ReaderInterestsViewModelTest : BaseUnitTest() {\n verify(readerTagRepository, times(1)).getInterests()\n }\n \n+ @Test\n+ fun `getInterests invoked if only daily prompt user tag received from repo`() =\n+ testWithDailyPromptUserTag {\n+ // Given\n+ val interests = getInterests()\n+ whenever(readerTagRepository.getInterests()).thenReturn(SuccessWithData(interests))\n+\n+ // When\n+ initViewModel()\n+\n+ // Then\n+ verify(readerTagRepository, times(1)).getInterests()\n+ }\n+\n @Test\n fun `discover close reader screen triggered if non empty user tags are received from repo`() =\n testWithNonEmptyUserTags {\n@@ -602,6 +616,25 @@ class ReaderInterestsViewModelTest : BaseUnitTest() {\n }\n }\n \n+ private fun testWithDailyPromptUserTag(block: suspend CoroutineScope.() -> T) {\n+ test {\n+ val tagsWithDailyPrompt = ReaderTagList().apply {\n+ add(\n+ ReaderTag(\n+ \"dailyprompt\",\n+ \"dailyprompt\",\n+ \"dailyprompt\",\n+ \"https://public-api.wordpress.com/rest/v1.2/read/tags/dailyprompt/posts\",\n+ ReaderTagType.DEFAULT\n+ )\n+ )\n+ }\n+\n+ whenever(readerTagRepository.getUserTags()).thenReturn(SuccessWithData(tagsWithDailyPrompt))\n+ block()\n+ }\n+ }\n+\n private fun testWithFailedUserTags(block: suspend CoroutineScope.() -> T) {\n test {\n whenever(readerTagRepository.getUserTags()).thenReturn(NetworkUnavailable)\n", "problem_statement": "[Reader IA] Bring back the Discover Onboarding for new users\nWhen a new user entered the Reader for the first time we would show the `Discover` feed with a \"Welcome\" message and a button leading to a \"Choose your topics\" screen, which essentially followed those tags and made Discover be populated with stuff based on those tags.\r\n\r\nAll the code for that is still present in the app and is still shown if the user unsubscribes from ALL their tags (when the user has 0 subscribed tags), here's an example:\r\n\r\nhttps://github.com/wordpress-mobile/WordPress-Android/assets/5091503/7b77b04a-fa3d-4e6a-852c-95ac587b97cd\r\n\r\nThis (0 tags subscribed) used to be the state of a new account as well, but recently the `dailyprompt` tag is being subscribed to by default on new accounts, which causes the Welcome screen to be skipped and the Reader Discover feed to be populated, which makes it hard for the user to configure their tags and see interesting stuff in that feed for the first time accessing the Reader in the app.\r\n\r\nWe want to bring back this simple Onboarding Flow to provide a better user experience, especially on the first time using the Reader.\n", "hints_text": "", "created_at": "2024-02-01T19:41:03Z", "version": "24.12", "FAIL_TO_PASS": [ "gradle_test_execution" ], "PASS_TO_PASS": [], "ERROR_TO_PASS": [], "environment_setup_commit": "eeec54055af88943943cebf98b94519a527e1c7a" }, { "repo": "wordpress-mobile/WordPress-Android", "pull_number": 19424, "instance_id": "wordpress-mobile__WordPress-Android-19424", "issue_numbers": [ "19340" ], "base_commit": "35191692826400b4f84db84daecb8723fcd3a971", "patch": "diff --git a/WordPress/src/main/java/org/wordpress/android/ui/posts/PostListFragment.kt b/WordPress/src/main/java/org/wordpress/android/ui/posts/PostListFragment.kt\nindex 2bed7dde2923..a467fb5ea7d3 100644\n--- a/WordPress/src/main/java/org/wordpress/android/ui/posts/PostListFragment.kt\n+++ b/WordPress/src/main/java/org/wordpress/android/ui/posts/PostListFragment.kt\n@@ -8,7 +8,6 @@ import android.view.ViewGroup\n import android.widget.Button\n import android.widget.ProgressBar\n import androidx.fragment.app.FragmentActivity\n-import androidx.lifecycle.Observer\n import androidx.lifecycle.ViewModelProvider\n import androidx.recyclerview.widget.LinearLayoutManager\n import androidx.recyclerview.widget.RecyclerView\n@@ -18,8 +17,6 @@ import org.wordpress.android.fluxc.model.SiteModel\n import org.wordpress.android.ui.ActionableEmptyView\n import org.wordpress.android.ui.ViewPagerFragment\n import org.wordpress.android.ui.posts.PostListType.SEARCH\n-import org.wordpress.android.ui.posts.PostListViewLayoutType.COMPACT\n-import org.wordpress.android.ui.posts.PostListViewLayoutType.STANDARD\n import org.wordpress.android.ui.posts.adapters.PostListAdapter\n import org.wordpress.android.ui.utils.UiHelpers\n import org.wordpress.android.ui.utils.UiString\n@@ -61,7 +58,6 @@ class PostListFragment : ViewPagerFragment() {\n private var actionableEmptyView: ActionableEmptyView? = null\n private var progressLoadMore: ProgressBar? = null\n \n- private lateinit var itemDecorationCompactLayout: RecyclerItemDecoration\n private lateinit var itemDecorationStandardLayout: RecyclerItemDecoration\n \n private lateinit var postListType: PostListType\n@@ -107,26 +103,6 @@ class PostListFragment : ViewPagerFragment() {\n \n mainViewModel = ViewModelProvider(nonNullActivity, viewModelFactory)[PostListMainViewModel::class.java]\n \n- mainViewModel.viewLayoutType.observe(viewLifecycleOwner, Observer { optionaLayoutType ->\n- optionaLayoutType?.let { layoutType ->\n- recyclerView?.removeItemDecoration(itemDecorationCompactLayout)\n- recyclerView?.removeItemDecoration(itemDecorationStandardLayout)\n-\n- when (layoutType) {\n- STANDARD -> {\n- recyclerView?.addItemDecoration(itemDecorationStandardLayout)\n- }\n- COMPACT -> {\n- recyclerView?.addItemDecoration(itemDecorationCompactLayout)\n- }\n- }\n-\n- if (postListAdapter.updateItemLayoutType(layoutType)) {\n- recyclerView?.scrollToPosition(0)\n- }\n- }\n- })\n-\n mainViewModel.authorSelectionUpdated.observe(viewLifecycleOwner) {\n if (it != null) {\n if (viewModel.updateAuthorFilterIfNotSearch(it)) {\n@@ -157,34 +133,34 @@ class PostListFragment : ViewPagerFragment() {\n \n private fun initObservers() {\n if (postListType == SEARCH) {\n- mainViewModel.searchQuery.observe(viewLifecycleOwner, Observer {\n+ mainViewModel.searchQuery.observe(viewLifecycleOwner) {\n if (TextUtils.isEmpty(it)) {\n postListAdapter.submitList(null)\n }\n viewModel.search(it)\n- })\n+ }\n }\n \n- viewModel.emptyViewState.observe(viewLifecycleOwner, Observer {\n+ viewModel.emptyViewState.observe(viewLifecycleOwner) {\n it?.let { emptyViewState -> updateEmptyViewForState(emptyViewState) }\n- })\n+ }\n \n- viewModel.isFetchingFirstPage.observe(viewLifecycleOwner, Observer {\n+ viewModel.isFetchingFirstPage.observe(viewLifecycleOwner) {\n swipeRefreshLayout?.isRefreshing = it == true\n- })\n+ }\n \n- viewModel.pagedListData.observe(viewLifecycleOwner, Observer {\n+ viewModel.pagedListData.observe(viewLifecycleOwner) {\n it?.let { pagedListData -> updatePagedListData(pagedListData) }\n- })\n+ }\n \n- viewModel.isLoadingMore.observe(viewLifecycleOwner, Observer {\n+ viewModel.isLoadingMore.observe(viewLifecycleOwner) {\n progressLoadMore?.visibility = if (it == true) View.VISIBLE else View.GONE\n- })\n- viewModel.scrollToPosition.observe(viewLifecycleOwner, Observer {\n+ }\n+ viewModel.scrollToPosition.observe(viewLifecycleOwner) {\n it?.let { index ->\n recyclerView?.scrollToPosition(index)\n }\n- })\n+ }\n }\n \n override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {\n@@ -200,12 +176,9 @@ class PostListFragment : ViewPagerFragment() {\n 0,\n context.resources.getDimensionPixelSize(R.dimen.margin_medium)\n )\n- itemDecorationCompactLayout = RecyclerItemDecoration(\n- 0,\n- context.resources.getDimensionPixelSize(R.dimen.list_divider_height)\n- )\n recyclerView?.layoutManager = LinearLayoutManager(context)\n recyclerView?.adapter = postListAdapter\n+ recyclerView?.addItemDecoration(itemDecorationStandardLayout)\n \n swipeRefreshLayout?.let {\n swipeToRefreshHelper = buildSwipeToRefreshHelper(it) {\ndiff --git a/WordPress/src/main/java/org/wordpress/android/ui/posts/PostListItemViewHolder.kt b/WordPress/src/main/java/org/wordpress/android/ui/posts/PostListItemViewHolder.kt\nindex ebf15f435320..7a737eb77871 100644\n--- a/WordPress/src/main/java/org/wordpress/android/ui/posts/PostListItemViewHolder.kt\n+++ b/WordPress/src/main/java/org/wordpress/android/ui/posts/PostListItemViewHolder.kt\n@@ -11,7 +11,6 @@ import android.view.Menu\n import android.view.View\n import android.view.ViewGroup\n import android.widget.FrameLayout\n-import android.widget.ImageButton\n import android.widget.ImageView\n import android.widget.ImageView.ScaleType\n import android.widget.PopupMenu\n@@ -26,7 +25,6 @@ import androidx.recyclerview.widget.RecyclerView\n import org.wordpress.android.R\n import org.wordpress.android.ui.utils.UiHelpers\n import org.wordpress.android.ui.utils.UiString\n-import org.wordpress.android.util.extensions.expandTouchTargetArea\n import org.wordpress.android.util.extensions.getColorFromAttribute\n import org.wordpress.android.util.extensions.getDrawableFromAttribute\n import org.wordpress.android.util.image.ImageManager\n@@ -135,23 +133,6 @@ sealed class PostListItemViewHolder(\n }\n }\n \n- class Compact(\n- parent: ViewGroup,\n- imageManager: ImageManager,\n- private val uiHelpers: UiHelpers\n- ) : PostListItemViewHolder(R.layout.post_list_item_compact, parent, imageManager, uiHelpers) {\n- private val moreButton: ImageButton = itemView.findViewById(R.id.more_button)\n-\n- override fun onBind(item: PostListItemUiState) {\n- setBasicValues(item.data)\n-\n- itemView.setOnClickListener { item.onSelected.invoke() }\n- uiHelpers.updateVisibility(moreButton, item.compactActions.actions.isNotEmpty())\n- moreButton.expandTouchTargetArea(R.dimen.post_list_more_button_extra_padding)\n- moreButton.setOnClickListener { onMoreClicked(item.compactActions.actions, moreButton) }\n- }\n- }\n-\n protected fun setBasicValues(data: PostListItemUiStateData) {\n uiHelpers.setTextOrHide(titleTextView, data.title)\n updatePostInfoLabel(postInfoTextView, data.postInfo)\n@@ -249,7 +230,7 @@ sealed class PostListItemViewHolder(\n private fun getMenuItemTitleWithIcon(context: Context, item: PostListItemAction): SpannableStringBuilder {\n var icon: Drawable? = setTint(\n context,\n- context.getDrawable(item.buttonType.iconResId)!!, item.buttonType.colorAttrId\n+ ContextCompat.getDrawable(context, item.buttonType.iconResId)!!, item.buttonType.colorAttrId\n )\n // If there's no icon, we insert a transparent one to keep the title aligned with the items which have icons.\n if (icon == null) icon = ColorDrawable(Color.TRANSPARENT)\ndiff --git a/WordPress/src/main/java/org/wordpress/android/ui/posts/PostListMainViewModel.kt b/WordPress/src/main/java/org/wordpress/android/ui/posts/PostListMainViewModel.kt\nindex 57449b607220..3f483486cba5 100644\n--- a/WordPress/src/main/java/org/wordpress/android/ui/posts/PostListMainViewModel.kt\n+++ b/WordPress/src/main/java/org/wordpress/android/ui/posts/PostListMainViewModel.kt\n@@ -38,10 +38,6 @@ import org.wordpress.android.ui.posts.PostListType.DRAFTS\n import org.wordpress.android.ui.posts.PostListType.PUBLISHED\n import org.wordpress.android.ui.posts.PostListType.SCHEDULED\n import org.wordpress.android.ui.posts.PostListType.TRASHED\n-import org.wordpress.android.ui.posts.PostListViewLayoutType.COMPACT\n-import org.wordpress.android.ui.posts.PostListViewLayoutType.STANDARD\n-import org.wordpress.android.ui.posts.PostListViewLayoutTypeMenuUiState.CompactViewLayoutTypeMenuUiState\n-import org.wordpress.android.ui.posts.PostListViewLayoutTypeMenuUiState.StandardViewLayoutTypeMenuUiState\n import org.wordpress.android.ui.prefs.AppPrefsWrapper\n import org.wordpress.android.ui.uploads.UploadActionUseCase\n import org.wordpress.android.ui.uploads.UploadStarter\n@@ -134,12 +130,6 @@ class PostListMainViewModel @Inject constructor(\n private val _postUploadAction = SingleLiveEvent()\n val postUploadAction: LiveData = _postUploadAction\n \n- private val _viewLayoutType = MutableLiveData()\n- val viewLayoutType: LiveData = _viewLayoutType\n-\n- private val _viewLayoutTypeMenuUiState = MutableLiveData()\n- val viewLayoutTypeMenuUiState: LiveData = _viewLayoutTypeMenuUiState\n-\n private val _isSearchExpanded = MutableLiveData()\n val isSearchExpanded: LiveData = _isSearchExpanded\n \n@@ -243,12 +233,6 @@ class PostListMainViewModel @Inject constructor(\n this.site = site\n this.editPostRepository = editPostRepository\n \n- if (isSearchExpanded.value == true) {\n- setViewLayoutAndIcon(COMPACT, false)\n- } else {\n- setUserPreferredViewLayoutType()\n- }\n-\n val authorFilterSelection: AuthorFilterSelection = if (isFilteringByAuthorSupported) {\n prefs.postListAuthorSelection\n } else {\n@@ -334,7 +318,6 @@ class PostListMainViewModel @Inject constructor(\n \n fun onSearchExpanded(restorePreviousSearch: Boolean) {\n if (isSearchExpanded.value != true) {\n- setViewLayoutAndIcon(COMPACT, false)\n AnalyticsUtils.trackWithSiteDetails(POST_LIST_SEARCH_ACCESSED, site)\n \n if (!restorePreviousSearch) {\n@@ -347,7 +330,6 @@ class PostListMainViewModel @Inject constructor(\n }\n \n fun onSearchCollapsed(delay: Long = SEARCH_COLLAPSE_DELAY) {\n- setUserPreferredViewLayoutType()\n _isSearchExpanded.value = false\n clearSearch()\n \n@@ -569,32 +551,6 @@ class PostListMainViewModel @Inject constructor(\n )\n }\n \n- fun toggleViewLayout() {\n- val currentLayoutType = viewLayoutType.value ?: PostListViewLayoutType.defaultValue\n- val toggledValue = when (currentLayoutType) {\n- STANDARD -> COMPACT\n- COMPACT -> STANDARD\n- }\n- AnalyticsUtils.trackAnalyticsPostListToggleLayout(toggledValue)\n- setViewLayoutAndIcon(toggledValue, true)\n- }\n-\n- private fun setViewLayoutAndIcon(layout: PostListViewLayoutType, storeIntoPreferences: Boolean = true) {\n- _viewLayoutType.value = layout\n- _viewLayoutTypeMenuUiState.value = when (layout) {\n- STANDARD -> StandardViewLayoutTypeMenuUiState\n- COMPACT -> CompactViewLayoutTypeMenuUiState\n- }\n- if (storeIntoPreferences) {\n- prefs.postListViewLayoutType = layout\n- }\n- }\n-\n- private fun setUserPreferredViewLayoutType() {\n- val savedLayoutType = prefs.postListViewLayoutType\n- setViewLayoutAndIcon(savedLayoutType, false)\n- }\n-\n fun onBottomSheetPublishButtonClicked() {\n editPostRepository.getEditablePost()?.let {\n postActionHandler.publishPost(it)\ndiff --git a/WordPress/src/main/java/org/wordpress/android/ui/posts/PostListMainViewState.kt b/WordPress/src/main/java/org/wordpress/android/ui/posts/PostListMainViewState.kt\nindex 4b4e389d5c66..9379ad939be0 100644\n--- a/WordPress/src/main/java/org/wordpress/android/ui/posts/PostListMainViewState.kt\n+++ b/WordPress/src/main/java/org/wordpress/android/ui/posts/PostListMainViewState.kt\n@@ -14,18 +14,6 @@ data class PostListMainViewState(\n val authorFilterItems: List\n )\n \n-sealed class PostListViewLayoutTypeMenuUiState(@DrawableRes val iconRes: Int, val title: UiString) {\n- object StandardViewLayoutTypeMenuUiState : PostListViewLayoutTypeMenuUiState(\n- iconRes = R.drawable.ic_view_post_compact_white_24dp,\n- title = UiStringRes(R.string.post_list_toggle_item_layout_list_view)\n- )\n-\n- object CompactViewLayoutTypeMenuUiState : PostListViewLayoutTypeMenuUiState(\n- iconRes = R.drawable.ic_view_post_full_white_24dp,\n- title = UiStringRes(R.string.post_list_toggle_item_layout_cards_view)\n- )\n-}\n-\n sealed class AuthorFilterListItemUIState(\n val id: Long,\n val text: UiString,\ndiff --git a/WordPress/src/main/java/org/wordpress/android/ui/posts/PostListViewLayoutType.kt b/WordPress/src/main/java/org/wordpress/android/ui/posts/PostListViewLayoutType.kt\ndeleted file mode 100644\nindex a0dca37c3b34..000000000000\n--- a/WordPress/src/main/java/org/wordpress/android/ui/posts/PostListViewLayoutType.kt\n+++ /dev/null\n@@ -1,16 +0,0 @@\n-package org.wordpress.android.ui.posts\n-\n-enum class PostListViewLayoutType(val id: Long) {\n- STANDARD(id = 0),\n- COMPACT(id = 1);\n-\n- companion object {\n- @JvmStatic\n- val defaultValue = STANDARD\n-\n- @JvmStatic\n- fun fromId(id: Long): PostListViewLayoutType {\n- return values().firstOrNull { it.id == id } ?: defaultValue\n- }\n- }\n-}\ndiff --git a/WordPress/src/main/java/org/wordpress/android/ui/posts/adapters/PostListAdapter.kt b/WordPress/src/main/java/org/wordpress/android/ui/posts/adapters/PostListAdapter.kt\nindex 87d557146e4b..9a5b180b1804 100644\n--- a/WordPress/src/main/java/org/wordpress/android/ui/posts/adapters/PostListAdapter.kt\n+++ b/WordPress/src/main/java/org/wordpress/android/ui/posts/adapters/PostListAdapter.kt\n@@ -11,9 +11,6 @@ import org.wordpress.android.R\n import org.wordpress.android.fluxc.model.LocalOrRemoteId.LocalId\n import org.wordpress.android.fluxc.model.LocalOrRemoteId.RemoteId\n import org.wordpress.android.ui.posts.PostListItemViewHolder\n-import org.wordpress.android.ui.posts.PostListViewLayoutType\n-import org.wordpress.android.ui.posts.PostListViewLayoutType.COMPACT\n-import org.wordpress.android.ui.posts.PostListViewLayoutType.STANDARD\n import org.wordpress.android.ui.utils.UiHelpers\n import org.wordpress.android.util.extensions.setVisible\n import org.wordpress.android.util.image.ImageManager\n@@ -24,10 +21,8 @@ import org.wordpress.android.viewmodel.posts.PostListItemType.PostListItemUiStat\n import org.wordpress.android.viewmodel.uistate.ProgressBarUiState\n \n private const val VIEW_TYPE_POST = 0\n-private const val VIEW_TYPE_POST_COMPACT = 1\n private const val VIEW_TYPE_ENDLIST_INDICATOR = 2\n private const val VIEW_TYPE_LOADING = 3\n-private const val VIEW_TYPE_LOADING_COMPACT = 4\n \n class PostListAdapter(\n context: Context,\n@@ -35,23 +30,12 @@ class PostListAdapter(\n private val uiHelpers: UiHelpers\n ) : PagedListAdapter(PostListDiffItemCallback) {\n private val layoutInflater: LayoutInflater = LayoutInflater.from(context)\n- private var itemLayoutType: PostListViewLayoutType = PostListViewLayoutType.defaultValue\n \n override fun getItemViewType(position: Int): Int {\n return when (getItem(position)) {\n is EndListIndicatorItem -> VIEW_TYPE_ENDLIST_INDICATOR\n- is PostListItemUiState -> {\n- when (itemLayoutType) {\n- STANDARD -> VIEW_TYPE_POST\n- COMPACT -> VIEW_TYPE_POST_COMPACT\n- }\n- }\n- is LoadingItem, null -> {\n- when (itemLayoutType) {\n- STANDARD -> VIEW_TYPE_LOADING\n- COMPACT -> VIEW_TYPE_LOADING_COMPACT\n- }\n- }\n+ is PostListItemUiState -> VIEW_TYPE_POST\n+ is LoadingItem, null -> VIEW_TYPE_LOADING\n }\n }\n \n@@ -66,16 +50,9 @@ class PostListAdapter(\n val view = layoutInflater.inflate(R.layout.post_list_item_skeleton, parent, false)\n LoadingViewHolder(view)\n }\n- VIEW_TYPE_LOADING_COMPACT -> {\n- val view = layoutInflater.inflate(R.layout.post_list_item_skeleton_compact, parent, false)\n- LoadingViewHolder(view)\n- }\n VIEW_TYPE_POST -> {\n PostListItemViewHolder.Standard(parent, imageManager, uiHelpers)\n }\n- VIEW_TYPE_POST_COMPACT -> {\n- PostListItemViewHolder.Compact(parent, imageManager, uiHelpers)\n- }\n else -> {\n // Fail fast if a new view type is added so the we can handle it\n throw IllegalStateException(\"The view type '$viewType' needs to be handled\")\n@@ -104,15 +81,6 @@ class PostListAdapter(\n }\n }\n \n- fun updateItemLayoutType(updatedItemLayoutType: PostListViewLayoutType): Boolean {\n- if (updatedItemLayoutType == itemLayoutType) {\n- return false\n- }\n- itemLayoutType = updatedItemLayoutType\n- notifyDataSetChanged()\n- return true\n- }\n-\n private class LoadingViewHolder(view: View) : ViewHolder(view) {\n val editButton: View? = view.findViewById(R.id.skeleton_button_edit)\n val viewButton: View? = view.findViewById(R.id.skeleton_button_view)\ndiff --git a/WordPress/src/main/java/org/wordpress/android/ui/prefs/AppPrefs.java b/WordPress/src/main/java/org/wordpress/android/ui/prefs/AppPrefs.java\nindex c79843ddad58..9d213b42725e 100644\n--- a/WordPress/src/main/java/org/wordpress/android/ui/prefs/AppPrefs.java\n+++ b/WordPress/src/main/java/org/wordpress/android/ui/prefs/AppPrefs.java\n@@ -24,7 +24,6 @@\n import org.wordpress.android.ui.mysite.SelectedSiteRepository;\n import org.wordpress.android.ui.mysite.tabs.MySiteTabType;\n import org.wordpress.android.ui.posts.AuthorFilterSelection;\n-import org.wordpress.android.ui.posts.PostListViewLayoutType;\n import org.wordpress.android.ui.quickstart.QuickStartType;\n import org.wordpress.android.ui.quickstart.QuickStartType.NewSiteQuickStartType;\n import org.wordpress.android.ui.reader.tracker.ReaderTab;\n@@ -1131,16 +1130,6 @@ public static void setAuthorFilterSelection(@NonNull AuthorFilterSelection selec\n setLong(DeletablePrefKey.POST_LIST_AUTHOR_FILTER, selection.getId());\n }\n \n- @NonNull public static PostListViewLayoutType getPostsListViewLayoutType() {\n- long id = getLong(DeletablePrefKey.POST_LIST_VIEW_LAYOUT_TYPE,\n- PostListViewLayoutType.getDefaultValue().getId());\n- return PostListViewLayoutType.fromId(id);\n- }\n-\n- public static void setPostsListViewLayoutType(@NonNull PostListViewLayoutType type) {\n- setLong(DeletablePrefKey.POST_LIST_VIEW_LAYOUT_TYPE, type.getId());\n- }\n-\n public static void setStatsWidgetSelectedSiteId(long siteId, int appWidgetId) {\n prefs().edit().putLong(getSiteIdWidgetKey(appWidgetId), siteId).apply();\n }\ndiff --git a/WordPress/src/main/java/org/wordpress/android/ui/prefs/AppPrefsWrapper.kt b/WordPress/src/main/java/org/wordpress/android/ui/prefs/AppPrefsWrapper.kt\nindex 60c17a1f20df..50c21033b4cd 100644\n--- a/WordPress/src/main/java/org/wordpress/android/ui/prefs/AppPrefsWrapper.kt\n+++ b/WordPress/src/main/java/org/wordpress/android/ui/prefs/AppPrefsWrapper.kt\n@@ -5,7 +5,6 @@ import org.wordpress.android.fluxc.store.QuickStartStore.QuickStartTask\n import org.wordpress.android.models.ReaderTag\n import org.wordpress.android.ui.jetpackoverlay.JetpackFeatureRemovalPhase\n import org.wordpress.android.ui.posts.AuthorFilterSelection\n-import org.wordpress.android.ui.posts.PostListViewLayoutType\n import org.wordpress.android.ui.prefs.AppPrefs.PrefKey\n import org.wordpress.android.ui.prefs.AppPrefs.getBoolean\n import org.wordpress.android.ui.quickstart.QuickStartType\n@@ -52,10 +51,6 @@ class AppPrefsWrapper @Inject constructor() {\n get() = AppPrefs.getAuthorFilterSelection()\n set(value) = AppPrefs.setAuthorFilterSelection(value)\n \n- var postListViewLayoutType: PostListViewLayoutType\n- get() = AppPrefs.getPostsListViewLayoutType()\n- set(value) = AppPrefs.setPostsListViewLayoutType(value)\n-\n var systemNotificationsEnabled: Boolean\n get() = AppPrefs.getSystemNotificationsEnabled()\n set(value) = AppPrefs.setSystemNotificationsEnabled(value)\ndiff --git a/WordPress/src/main/java/org/wordpress/android/util/analytics/AnalyticsUtils.java b/WordPress/src/main/java/org/wordpress/android/util/analytics/AnalyticsUtils.java\nindex 01434123b88f..a0257c4686ad 100644\n--- a/WordPress/src/main/java/org/wordpress/android/util/analytics/AnalyticsUtils.java\n+++ b/WordPress/src/main/java/org/wordpress/android/util/analytics/AnalyticsUtils.java\n@@ -32,7 +32,6 @@\n import org.wordpress.android.models.ReaderPost;\n import org.wordpress.android.ui.PagePostCreationSourcesDetail;\n import org.wordpress.android.ui.posts.EditPostActivity;\n-import org.wordpress.android.ui.posts.PostListViewLayoutType;\n import org.wordpress.android.ui.posts.PostUtils;\n import org.wordpress.android.util.AppLog;\n import org.wordpress.android.util.FluxCUtils;\n@@ -642,12 +641,6 @@ public static void trackAnalyticsAccountCreated(String username, String email, M\n AnalyticsTracker.track(AnalyticsTracker.Stat.CREATED_ACCOUNT, properties);\n }\n \n- public static void trackAnalyticsPostListToggleLayout(PostListViewLayoutType viewLayoutType) {\n- Map properties = new HashMap<>();\n- properties.put(\"post_list_view_layout_type\", viewLayoutType.toString());\n- AnalyticsTracker.track(AnalyticsTracker.Stat.POST_LIST_VIEW_LAYOUT_TOGGLED, properties);\n- }\n-\n private static Map createNewsCardProperties(String origin, int version) {\n Map properties = new HashMap<>();\n properties.put(NEWS_CARD_ORIGIN, origin);\ndiff --git a/WordPress/src/main/res/drawable/ic_view_post_compact_white_24dp.xml b/WordPress/src/main/res/drawable/ic_view_post_compact_white_24dp.xml\ndeleted file mode 100644\nindex b0a5371c3d49..000000000000\n--- a/WordPress/src/main/res/drawable/ic_view_post_compact_white_24dp.xml\n+++ /dev/null\n@@ -1,9 +0,0 @@\n-\n- \n-\ndiff --git a/WordPress/src/main/res/drawable/ic_view_post_full_white_24dp.xml b/WordPress/src/main/res/drawable/ic_view_post_full_white_24dp.xml\ndeleted file mode 100644\nindex 91317955ffb9..000000000000\n--- a/WordPress/src/main/res/drawable/ic_view_post_full_white_24dp.xml\n+++ /dev/null\n@@ -1,9 +0,0 @@\n-\n- \n-\ndiff --git a/WordPress/src/main/res/layout/post_list_item_compact.xml b/WordPress/src/main/res/layout/post_list_item_compact.xml\ndeleted file mode 100644\nindex c44c59566aab..000000000000\n--- a/WordPress/src/main/res/layout/post_list_item_compact.xml\n+++ /dev/null\n@@ -1,136 +0,0 @@\n-\n-\n-\n- \n-\n- \n-\n- \n-\n- \n-\n- \n-\n- \n-\n- \n-\n- \n-\n- \n-\n- \n-\ndiff --git a/WordPress/src/main/res/layout/post_list_item_skeleton_compact.xml b/WordPress/src/main/res/layout/post_list_item_skeleton_compact.xml\ndeleted file mode 100644\nindex 27319a99a982..000000000000\n--- a/WordPress/src/main/res/layout/post_list_item_skeleton_compact.xml\n+++ /dev/null\n@@ -1,66 +0,0 @@\n-\n-\n-\n- \n-\n- \n-\n- \n-\n- \n-\n- \n-\n- \n- \n-\ndiff --git a/WordPress/src/main/res/values/dimens.xml b/WordPress/src/main/res/values/dimens.xml\nindex 9e6cd3021bbc..0fc787e76dcd 100644\n--- a/WordPress/src/main/res/values/dimens.xml\n+++ b/WordPress/src/main/res/values/dimens.xml\n@@ -93,7 +93,6 @@\n 0dp\n @dimen/content_margin_none\n @dimen/content_margin_none\n- @dimen/content_margin_none\n @dimen/content_margin_none\n \n \n- 80dp\n- 40dp\n- 24dp\n-\n-\n \n 16dp\n 16dp\n", "test_patch": "diff --git a/WordPress/src/test/java/org/wordpress/android/ui/posts/PostListMainViewModelTest.kt b/WordPress/src/test/java/org/wordpress/android/ui/posts/PostListMainViewModelTest.kt\nindex 1aac211ab4fb..57bbb125e1b5 100644\n--- a/WordPress/src/test/java/org/wordpress/android/ui/posts/PostListMainViewModelTest.kt\n+++ b/WordPress/src/test/java/org/wordpress/android/ui/posts/PostListMainViewModelTest.kt\n@@ -7,7 +7,6 @@ import org.junit.Before\n import org.junit.Test\n import org.mockito.Mock\n import org.mockito.kotlin.any\n-import org.mockito.kotlin.doReturn\n import org.mockito.kotlin.eq\n import org.mockito.kotlin.mock\n import org.mockito.kotlin.times\n@@ -19,8 +18,6 @@ import org.wordpress.android.fluxc.model.LocalOrRemoteId.LocalId\n import org.wordpress.android.fluxc.model.PostModel\n import org.wordpress.android.fluxc.model.SiteModel\n import org.wordpress.android.ui.jetpackoverlay.JetpackFeatureRemovalPhaseHelper\n-import org.wordpress.android.ui.posts.PostListViewLayoutType.COMPACT\n-import org.wordpress.android.ui.posts.PostListViewLayoutType.STANDARD\n import org.wordpress.android.ui.prefs.AppPrefsWrapper\n import org.wordpress.android.ui.uploads.UploadStarter\n import org.wordpress.android.viewmodel.Event\n@@ -48,12 +45,10 @@ class PostListMainViewModelTest : BaseUnitTest() {\n \n private lateinit var viewModel: PostListMainViewModel\n \n+ @Mock\n+ lateinit var prefs: AppPrefsWrapper\n @Before\n fun setUp() {\n- val prefs = mock {\n- on { postListViewLayoutType } doReturn STANDARD\n- }\n-\n whenever(editPostRepository.postChanged).thenReturn(MutableLiveData(Event(PostModel())))\n \n viewModel = PostListMainViewModel(\n@@ -138,25 +133,6 @@ class PostListMainViewModelTest : BaseUnitTest() {\n assertThat(searchQuery).isNull()\n }\n \n- @Test\n- fun `search is using compact view mode independently from normal post list`() {\n- viewModel.start(site, PostListRemotePreviewState.NONE, currentBottomSheetPostId, editPostRepository)\n- assertThat(viewModel.viewLayoutType.value).isEqualTo(STANDARD) // default value\n-\n- var viewLayoutType: PostListViewLayoutType? = null\n- viewModel.viewLayoutType.observeForever {\n- viewLayoutType = it\n- }\n-\n- viewModel.onSearchExpanded(false)\n-\n- assertThat(viewLayoutType).isEqualTo(COMPACT)\n-\n- viewModel.onSearchCollapsed()\n-\n- assertThat(viewLayoutType).isEqualTo(STANDARD)\n- }\n-\n @Test\n fun `if currentBottomSheetPostId isn't 0 then set the post in editPostRepository from the postStore`() {\n // arrange\n", "problem_statement": "UI Modernization Posts: Remove compact layout filter\n\r\n```[tasklist]\n### Tasks\n- [x] Remove layouts files\n- [x] Remove string resources\n- [x] Remove from toolbar menu\n- [x] Remove logic associated with changing the layout filter\n```\r\n\n", "hints_text": "", "created_at": "2023-10-22T18:18:15Z", "version": "23.51", "FAIL_TO_PASS": [ "gradle_test_execution" ], "PASS_TO_PASS": [], "ERROR_TO_PASS": [], "environment_setup_commit": "72fdb734f5061bd1020532c544c2d040b30f5678" }, { "repo": "wordpress-mobile/WordPress-Android", "pull_number": 19537, "instance_id": "wordpress-mobile__WordPress-Android-19537", "issue_numbers": [ "19536" ], "base_commit": "ba8338bd1e5e20502e184457c0809fc67e53ef76", "patch": "diff --git a/WordPress/src/main/java/org/wordpress/android/ui/mysite/personalization/DashboardCardPersonalizationViewModelSlice.kt b/WordPress/src/main/java/org/wordpress/android/ui/mysite/personalization/DashboardCardPersonalizationViewModelSlice.kt\nindex 8d25b5d32a73..29f95762e5ca 100644\n--- a/WordPress/src/main/java/org/wordpress/android/ui/mysite/personalization/DashboardCardPersonalizationViewModelSlice.kt\n+++ b/WordPress/src/main/java/org/wordpress/android/ui/mysite/personalization/DashboardCardPersonalizationViewModelSlice.kt\n@@ -61,7 +61,7 @@ class DashboardCardPersonalizationViewModelSlice @Inject constructor(\n }\n \n private suspend fun getBloggingPromptCardState(): DashboardCardState? {\n- return if (bloggingPromptsSettingsHelper.shouldShowPromptsFeature()) {\n+ return if (bloggingPromptsSettingsHelper.shouldShowPromptsSetting()) {\n DashboardCardState(\n title = R.string.personalization_screen_blogging_prompts_card_title,\n description = R.string.personalization_screen_blogging_prompts_card_description,\n@@ -179,9 +179,12 @@ class DashboardCardPersonalizationViewModelSlice @Inject constructor(\n \n private fun updateCardState(cardType: CardType, enabled: Boolean) {\n val currentCards: MutableList = _uiState.value!!.toMutableList()\n- val updated = currentCards.find { it.cardType == cardType }!!.copy(enabled = enabled)\n- currentCards[cardType.order] = updated\n- _uiState.postValue(currentCards)\n+ val cardIndex = currentCards.indexOfFirst { it.cardType == cardType }\n+ if (cardIndex != -1) {\n+ val updated = currentCards[cardIndex].copy(enabled = enabled)\n+ currentCards[cardIndex] = updated\n+ _uiState.postValue(currentCards)\n+ }\n }\n \n private fun isStatsCardShown(siteId: Long) = !appPrefsWrapper.getShouldHideTodaysStatsDashboardCard(siteId)\n", "test_patch": "diff --git a/WordPress/src/test/java/org/wordpress/android/ui/mysite/personalization/DashboardCardPersonalizationViewModelSliceTest.kt b/WordPress/src/test/java/org/wordpress/android/ui/mysite/personalization/DashboardCardPersonalizationViewModelSliceTest.kt\nindex 6e2530ccf16c..55990e5fb458 100644\n--- a/WordPress/src/test/java/org/wordpress/android/ui/mysite/personalization/DashboardCardPersonalizationViewModelSliceTest.kt\n+++ b/WordPress/src/test/java/org/wordpress/android/ui/mysite/personalization/DashboardCardPersonalizationViewModelSliceTest.kt\n@@ -9,6 +9,7 @@ import org.junit.Test\n import org.junit.runner.RunWith\n import org.mockito.Mock\n import org.mockito.junit.MockitoJUnitRunner\n+import org.mockito.kotlin.anyOrNull\n import org.mockito.kotlin.verify\n import org.mockito.kotlin.whenever\n import org.wordpress.android.BaseUnitTest\n@@ -22,6 +23,7 @@ import org.wordpress.android.ui.mysite.SelectedSiteRepository\n import org.wordpress.android.ui.mysite.cards.dashboard.posts.PostCardType\n import org.wordpress.android.ui.prefs.AppPrefsWrapper\n import org.wordpress.android.util.analytics.AnalyticsTrackerWrapper\n+import kotlin.test.assertNull\n \n @ExperimentalCoroutinesApi\n @RunWith(MockitoJUnitRunner::class)\n@@ -64,7 +66,7 @@ class DashboardCardPersonalizationViewModelSliceTest : BaseUnitTest() {\n \n whenever(blazeFeatureUtils.isSiteBlazeEligible(site)).thenReturn(true)\n test {\n- whenever(bloggingPromptsSettingsHelper.shouldShowPromptsFeature()).thenReturn(true)\n+ whenever(bloggingPromptsSettingsHelper.shouldShowPromptsSetting()).thenReturn(true)\n }\n \n viewModelSlice = DashboardCardPersonalizationViewModelSlice(\n@@ -274,4 +276,14 @@ class DashboardCardPersonalizationViewModelSliceTest : BaseUnitTest() {\n mapOf(CARD_TYPE_TRACK_PARAM to cardType.trackingName)\n )\n }\n+\n+ @Test\n+ fun `given blaze state is not built, when cards are fetched, then blaze is not present and app does not crash`() {\n+ whenever(blazeFeatureUtils.isSiteBlazeEligible(anyOrNull())).thenReturn(false)\n+\n+ viewModelSlice.start(123L)\n+ val cardState = uiStateList.last().find { it.cardType == CardType.BLAZE }\n+\n+ assertNull(cardState)\n+ }\n }\n", "problem_statement": "Personalize Dashboard View Crash\nCrash in JP app when updating the state of the cards within the Personalization View when an expected card state is not built.\r\n\r\n\r\nCC: @AjeshRPai \r\n\r\nCrash Log\r\n
\r\nFATAL EXCEPTION: DefaultDispatcher-worker-1Process: com.jetpack.android.beta, PID: 6784java.lang.IndexOutOfBoundsException: Index 6 out of bounds for length 6\tat jdk.internal.util.Preconditions.outOfBounds(Preconditions.java:64)\tat jdk.internal.util.Preconditions.outOfBoundsCheckIndex(Preconditions.java:70)\tat jdk.internal.util.Preconditions.checkIndex(Preconditions.java:266)\tat java.util.Objects.checkIndex(Objects.java:359)\tat java.util.ArrayList.set(ArrayList.java:448)\tat org.wordpress.android.ui.mysite.personalization.DashboardCardPersonalizationViewModelSlice.updateCardState(DashboardCardPersonalizationViewModelSlice.kt:183)\tat org.wordpress.android.ui.mysite.personalization.DashboardCardPersonalizationViewModelSlice.access$updateCardState(DashboardCardPersonalizationViewModelSlice.kt:24)\tat org.wordpress.android.ui.mysite.personalization.DashboardCardPersonalizationViewModelSlice$onCardToggled$1.invokeSuspend(DashboardCardPersonalizationViewModelSlice.kt:157)\tat kotlin.coroutines.jvm.internal.BaseContinuationImpl.resumeWith(ContinuationImpl.kt:33)\tat kotlinx.coroutines.UndispatchedCoroutine.afterResume(CoroutineContext.kt:270)\tat kotlinx.coroutines.AbstractCoroutine.resumeWith(AbstractCoroutine.kt:102)\tat kotlin.coroutines.jvm.internal.BaseContinuationImpl.resumeWith(ContinuationImpl.kt:46)\tat kotlinx.coroutines.DispatchedTask.run(DispatchedTask.kt:108)\tat kotlinx.coroutines.scheduling.CoroutineScheduler.runSafely(CoroutineScheduler.kt:584)\tat kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.executeTask(CoroutineScheduler.kt:793)\tat kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.runWorker(CoroutineScheduler.kt:697)\tat kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.run(CoroutineScheduler.kt:684)\tSuppressed: kotlinx.coroutines.internal.DiagnosticCoroutineContextException: [StandaloneCoroutine{Cancelling}@e60bd21, Dispatchers.Default]\r\n
\r\n\r\n##### Tested on [device], Android [version], JPAndroid / WPAndroid [version]\r\n\n", "hints_text": "", "created_at": "2023-11-05T17:12:46Z", "version": "23.61", "FAIL_TO_PASS": [ "gradle_test_execution" ], "PASS_TO_PASS": [], "ERROR_TO_PASS": [], "environment_setup_commit": "9fc79ceb9a6bcbdaa7adfd45dd9e6f80636120a6" }, { "repo": "wordpress-mobile/WordPress-Android", "pull_number": 19482, "instance_id": "wordpress-mobile__WordPress-Android-19482", "issue_numbers": [ "19343" ], "base_commit": "7098fa0250fb779b25562afe2f274c89018a5154", "patch": "diff --git a/WordPress/src/main/java/org/wordpress/android/ui/posts/PostActionHandler.kt b/WordPress/src/main/java/org/wordpress/android/ui/posts/PostActionHandler.kt\nindex 15fd59b677d0..79cfcf757fa0 100644\n--- a/WordPress/src/main/java/org/wordpress/android/ui/posts/PostActionHandler.kt\n+++ b/WordPress/src/main/java/org/wordpress/android/ui/posts/PostActionHandler.kt\n@@ -34,6 +34,7 @@ import org.wordpress.android.util.ToastUtils.Duration\n import org.wordpress.android.viewmodel.helpers.ToastMessageHolder\n import org.wordpress.android.widgets.PostListButtonType\n import org.wordpress.android.widgets.PostListButtonType.BUTTON_CANCEL_PENDING_AUTO_UPLOAD\n+import org.wordpress.android.widgets.PostListButtonType.BUTTON_COMMENTS\n import org.wordpress.android.widgets.PostListButtonType.BUTTON_COPY\n import org.wordpress.android.widgets.PostListButtonType.BUTTON_COPY_URL\n import org.wordpress.android.widgets.PostListButtonType.BUTTON_DELETE\n@@ -133,6 +134,7 @@ class PostActionHandler(\n BUTTON_PROMOTE_WITH_BLAZE -> {\n triggerPostListAction.invoke(PostListAction.ShowPromoteWithBlaze(post))\n }\n+ BUTTON_COMMENTS -> {} // todo: implement\n }\n }\n \ndiff --git a/WordPress/src/main/java/org/wordpress/android/ui/posts/PostListActionTracker.kt b/WordPress/src/main/java/org/wordpress/android/ui/posts/PostListActionTracker.kt\nindex d9e2c9c8e32a..1bb98071b6e0 100644\n--- a/WordPress/src/main/java/org/wordpress/android/ui/posts/PostListActionTracker.kt\n+++ b/WordPress/src/main/java/org/wordpress/android/ui/posts/PostListActionTracker.kt\n@@ -6,6 +6,7 @@ import org.wordpress.android.fluxc.model.SiteModel\n import org.wordpress.android.util.analytics.AnalyticsUtils\n import org.wordpress.android.widgets.PostListButtonType\n import org.wordpress.android.widgets.PostListButtonType.BUTTON_CANCEL_PENDING_AUTO_UPLOAD\n+import org.wordpress.android.widgets.PostListButtonType.BUTTON_COMMENTS\n import org.wordpress.android.widgets.PostListButtonType.BUTTON_COPY\n import org.wordpress.android.widgets.PostListButtonType.BUTTON_COPY_URL\n import org.wordpress.android.widgets.PostListButtonType.BUTTON_DELETE\n@@ -53,6 +54,7 @@ fun trackPostListAction(site: SiteModel, buttonType: PostListButtonType, postDat\n BUTTON_SHOW_MOVE_TRASHED_POST_TO_DRAFT_DIALOG -> \"show_move_trashed_post_to_draft_post_dialog\"\n BUTTON_COPY_URL -> \"copy_url\"\n BUTTON_PROMOTE_WITH_BLAZE -> \"promote_with_blaze\"\n+ BUTTON_COMMENTS -> \"comments\"\n }\n \n AnalyticsUtils.trackWithSiteDetails(statsEvent, site, properties)\ndiff --git a/WordPress/src/main/java/org/wordpress/android/ui/posts/PostListItemViewHolder.kt b/WordPress/src/main/java/org/wordpress/android/ui/posts/PostListItemViewHolder.kt\nindex a69565f211ed..5fef04b859e8 100644\n--- a/WordPress/src/main/java/org/wordpress/android/ui/posts/PostListItemViewHolder.kt\n+++ b/WordPress/src/main/java/org/wordpress/android/ui/posts/PostListItemViewHolder.kt\n@@ -1,19 +1,18 @@\n package org.wordpress.android.ui.posts\n \n import android.content.Context\n-import android.graphics.Color\n-import android.graphics.drawable.ColorDrawable\n import android.graphics.drawable.Drawable\n-import android.text.SpannableStringBuilder\n-import android.text.style.ImageSpan\n+import android.text.Spannable\n+import android.text.SpannableString\n+import android.text.style.ForegroundColorSpan\n import android.view.LayoutInflater\n import android.view.Menu\n+import android.view.MenuItem\n import android.view.View\n import android.view.ViewGroup\n import android.view.ViewTreeObserver\n import android.widget.FrameLayout\n import android.widget.ImageView\n-import android.widget.PopupMenu\n import android.widget.ProgressBar\n import android.widget.TextView\n import androidx.annotation.ColorRes\n@@ -21,6 +20,9 @@ import androidx.annotation.LayoutRes\n import androidx.constraintlayout.widget.ConstraintLayout\n import androidx.core.content.ContextCompat\n import androidx.core.graphics.drawable.DrawableCompat\n+import androidx.core.view.GravityCompat\n+import androidx.core.view.MenuCompat\n+import androidx.appcompat.widget.PopupMenu as AppCompatPopupMenu\n import androidx.recyclerview.widget.RecyclerView\n import org.wordpress.android.R\n import org.wordpress.android.WordPress\n@@ -38,8 +40,8 @@ import org.wordpress.android.viewmodel.posts.PostListItemUiStateData\n import org.wordpress.android.viewmodel.uistate.ProgressBarUiState\n import java.util.concurrent.atomic.AtomicBoolean\n import android.R as AndroidR\n+import com.google.android.material.R as MaterialR\n \n-const val POST_LIST_ICON_PADDING = 8\n const val MAX_TITLE_EXCERPT_LINES = 2\n \n sealed class PostListItemViewHolder(\n@@ -157,23 +159,68 @@ sealed class PostListItemViewHolder(\n uiHelpers.setTextOrHide(view, concatenatedText)\n }\n \n- protected fun onMoreClicked(actions: List, v: View) {\n- val menu = PopupMenu(v.context, v)\n+ private fun onMoreClicked(actions: List, v: View) {\n+ val emptyDrawable = ContextCompat.getDrawable(v.context, R.drawable.ic_placeholder_24dp)\n+ val menu = AppCompatPopupMenu(v.context, v, GravityCompat.END)\n+ MenuCompat.setGroupDividerEnabled(menu.menu, true)\n+ menu.setForceShowIcon(true)\n actions.forEach { singleItemAction ->\n val menuItem = menu.menu.add(\n- Menu.NONE,\n+ singleItemAction.buttonType.groupId,\n singleItemAction.buttonType.value,\n Menu.NONE,\n- getMenuItemTitleWithIcon(v.context, singleItemAction)\n+ singleItemAction.buttonType.textResId\n )\n menuItem.setOnMenuItemClickListener {\n singleItemAction.onButtonClicked.invoke(singleItemAction.buttonType)\n true\n }\n+\n+ setIconAndIconColorIfNeeded(v.context, menuItem, singleItemAction, emptyDrawable)\n+ setTextColorIfNeeded(v.context, menuItem, singleItemAction)\n }\n menu.show()\n }\n \n+ private fun setIconAndIconColorIfNeeded(\n+ context: Context,\n+ menuItem: MenuItem,\n+ singleItemAction: PostListItemAction,\n+ emptyDrawable: Drawable?\n+ ) {\n+ if (singleItemAction.buttonType.iconResId > 0) {\n+ val icon: Drawable = setTint(\n+ context,\n+ ContextCompat.getDrawable(context, singleItemAction.buttonType.iconResId)!!,\n+ singleItemAction.buttonType.colorAttrId\n+ )\n+ menuItem.icon = icon\n+ } else {\n+ // Leave space for the icon so the text lines up\n+ menuItem.icon = emptyDrawable\n+ }\n+ }\n+\n+ private fun setTextColorIfNeeded(context: Context,\n+ menuItem: MenuItem,\n+ singleItemAction: PostListItemAction) {\n+ if (singleItemAction.buttonType.colorAttrId > 0 &&\n+ singleItemAction.buttonType.colorAttrId != MaterialR.attr.colorOnSurface) {\n+ val menuTitle = context.getText(singleItemAction.buttonType.textResId)\n+ val spannableString = SpannableString(menuTitle)\n+ val textColor = context.getColorFromAttribute(singleItemAction.buttonType.colorAttrId)\n+\n+ spannableString.setSpan(\n+ ForegroundColorSpan(textColor),\n+ 0,\n+ spannableString.length,\n+ Spannable.SPAN_INCLUSIVE_INCLUSIVE\n+ )\n+\n+ menuItem.title = spannableString\n+ }\n+ }\n+\n private fun updateProgressBarState(progressBarUiState: ProgressBarUiState) {\n uiHelpers.updateVisibility(uploadProgressBar, progressBarUiState.visibility)\n when (progressBarUiState) {\n@@ -235,27 +282,4 @@ sealed class PostListItemViewHolder(\n }\n return wrappedDrawable\n }\n-\n- @Suppress(\"ComplexMethod\")\n- private fun getMenuItemTitleWithIcon(context: Context, item: PostListItemAction): SpannableStringBuilder {\n- var icon: Drawable? = setTint(\n- context,\n- ContextCompat.getDrawable(context, item.buttonType.iconResId)!!, item.buttonType.colorAttrId\n- )\n- // If there's no icon, we insert a transparent one to keep the title aligned with the items which have icons.\n- if (icon == null) icon = ColorDrawable(Color.TRANSPARENT)\n- val iconSize: Int = context.resources.getDimensionPixelSize(R.dimen.menu_item_icon_size)\n- icon.setBounds(0, 0, iconSize, iconSize)\n- val imageSpan = ImageSpan(icon)\n-\n- // Add a space placeholder for the icon, before the title.\n- val menuTitle = context.getText(item.buttonType.textResId)\n- val ssb = SpannableStringBuilder(\n- menuTitle.padStart(menuTitle.length + POST_LIST_ICON_PADDING)\n- )\n-\n- // Replace the space placeholder with the icon.\n- ssb.setSpan(imageSpan, 1, 2, 0)\n- return ssb\n- }\n }\ndiff --git a/WordPress/src/main/java/org/wordpress/android/viewmodel/posts/PostListItemUiStateHelper.kt b/WordPress/src/main/java/org/wordpress/android/viewmodel/posts/PostListItemUiStateHelper.kt\nindex 5e3eed9be283..915d884477ab 100644\n--- a/WordPress/src/main/java/org/wordpress/android/viewmodel/posts/PostListItemUiStateHelper.kt\n+++ b/WordPress/src/main/java/org/wordpress/android/viewmodel/posts/PostListItemUiStateHelper.kt\n@@ -420,10 +420,6 @@ class PostListItemUiStateHelper @Inject constructor(\n val canShowPublishButton = canRetryUpload || canPublishPost\n val buttonTypes = ArrayList()\n \n- if (postStatus != TRASHED) {\n- buttonTypes.add(BUTTON_EDIT)\n- }\n-\n if (canCancelPendingAutoUpload) {\n buttonTypes.add(BUTTON_CANCEL_PENDING_AUTO_UPLOAD)\n }\n@@ -463,7 +459,14 @@ class PostListItemUiStateHelper @Inject constructor(\n \n buttonTypes.addDeletingOrTrashAction(isLocalDraft, postStatus)\n \n- return buttonTypes\n+ return sortPostListButtons(buttonTypes)\n+ }\n+\n+ private fun sortPostListButtons(list: List): List {\n+ return list.sortedWith(compareBy(\n+ { it.groupId },\n+ { it.positionInGroup }\n+ ))\n }\n \n private fun MutableList.addViewOrPreviewAction(shouldShowPreview: Boolean) {\ndiff --git a/WordPress/src/main/java/org/wordpress/android/widgets/PostListButtonType.kt b/WordPress/src/main/java/org/wordpress/android/widgets/PostListButtonType.kt\nindex ac90a59a7bd8..11ae4803c505 100644\n--- a/WordPress/src/main/java/org/wordpress/android/widgets/PostListButtonType.kt\n+++ b/WordPress/src/main/java/org/wordpress/android/widgets/PostListButtonType.kt\n@@ -6,120 +6,173 @@ import androidx.annotation.StringRes\n import org.wordpress.android.R\n import com.google.android.material.R as MaterialR\n \n+private const val VIEW_GROUP_ID = 1\n+private const val TAKE_AN_ACTION_GROUP_ID = 2\n+private const val SHARE_AND_PROMOTE_GROUP_ID = 3\n+private const val NAVIGATE_GROUP_ID = 4\n+private const val TRASH_GROUP_ID = 5\n+private const val OTHER_GROUP_ID = 6\n+\n // PostListButton.java types - from attrs.xml\n enum class PostListButtonType constructor(\n val value: Int,\n @StringRes val textResId: Int,\n @DrawableRes val iconResId: Int,\n- @AttrRes val colorAttrId: Int\n+ @AttrRes val colorAttrId: Int,\n+ val groupId: Int,\n+ val positionInGroup: Int\n ) {\n BUTTON_EDIT(\n 1,\n R.string.button_edit,\n R.drawable.gb_ic_pencil,\n- MaterialR.attr.colorOnSurface\n+ MaterialR.attr.colorOnSurface,\n+ VIEW_GROUP_ID,\n+ 1\n ),\n BUTTON_VIEW(\n 2,\n R.string.button_view,\n R.drawable.gb_ic_external,\n- MaterialR.attr.colorOnSurface\n+ MaterialR.attr.colorOnSurface,\n+ VIEW_GROUP_ID,\n+ 1\n ),\n BUTTON_PREVIEW(\n 3,\n R.string.button_preview,\n R.drawable.gb_ic_globe,\n- MaterialR.attr.colorOnSurface\n+ MaterialR.attr.colorOnSurface,\n+ VIEW_GROUP_ID,\n+ 2\n ),\n BUTTON_STATS(\n 4,\n R.string.button_stats,\n R.drawable.gb_ic_chart_bar,\n- MaterialR.attr.colorOnSurface\n+ MaterialR.attr.colorOnSurface,\n+ NAVIGATE_GROUP_ID,\n+ 1\n ),\n BUTTON_TRASH(\n 5,\n R.string.button_trash,\n R.drawable.gb_ic_trash,\n- MaterialR.attr.colorOnSurface\n+ R.attr.wpColorError,\n+ TRASH_GROUP_ID,\n+ 3\n ),\n BUTTON_DELETE(\n 6,\n R.string.button_delete,\n R.drawable.gb_ic_trash,\n- MaterialR.attr.colorOnSurface\n+ R.attr.wpColorError,\n+ TRASH_GROUP_ID,\n+ 1\n ),\n BUTTON_PUBLISH(\n 7,\n R.string.button_publish,\n R.drawable.gb_ic_globe,\n- MaterialR.attr.colorOnSurface\n+ MaterialR.attr.colorOnSurface,\n+ TAKE_AN_ACTION_GROUP_ID,\n+ 2\n ),\n BUTTON_SYNC(\n 8,\n R.string.button_sync,\n R.drawable.gb_ic_update,\n- MaterialR.attr.colorOnSurface\n+ MaterialR.attr.colorOnSurface,\n+ TAKE_AN_ACTION_GROUP_ID,\n+ 4\n ),\n BUTTON_MORE(\n 9,\n R.string.button_more,\n R.drawable.gb_ic_more_horizontal,\n- MaterialR.attr.colorOnSurface\n+ MaterialR.attr.colorOnSurface,\n+ OTHER_GROUP_ID,\n+ 1\n ),\n BUTTON_SUBMIT(\n 10,\n R.string.submit_for_review,\n R.drawable.gb_ic_post_author,\n- MaterialR.attr.colorOnSurface\n+ MaterialR.attr.colorOnSurface,\n+ TAKE_AN_ACTION_GROUP_ID,\n+ 5\n ),\n BUTTON_RETRY(\n 11,\n R.string.button_retry,\n R.drawable.gb_ic_redo,\n- MaterialR.attr.colorError\n+ R.attr.wpColorError,\n+ TAKE_AN_ACTION_GROUP_ID,\n+ 3\n ),\n BUTTON_MOVE_TO_DRAFT(\n 12,\n R.string.button_move_to_draft,\n R.drawable.gb_ic_move_to,\n- MaterialR.attr.colorOnSurface\n+ MaterialR.attr.colorOnSurface,\n+ TAKE_AN_ACTION_GROUP_ID,\n+ 6\n ),\n BUTTON_DELETE_PERMANENTLY(\n 13,\n R.string.button_delete_permanently,\n R.drawable.gb_ic_trash,\n- MaterialR.attr.colorOnSurface\n+ R.attr.wpColorError,\n+ TRASH_GROUP_ID,\n+ 3\n ),\n BUTTON_CANCEL_PENDING_AUTO_UPLOAD(\n 14,\n R.string.pages_and_posts_cancel_auto_upload,\n R.drawable.gb_ic_undo,\n- R.attr.wpColorWarningDark\n+ R.attr.wpColorWarningDark,\n+ TAKE_AN_ACTION_GROUP_ID,\n+ 1\n ),\n BUTTON_SHOW_MOVE_TRASHED_POST_TO_DRAFT_DIALOG(\n 15,\n 0,\n 0,\n- 0\n+ 0,\n+ TRASH_GROUP_ID,\n+ 4\n ),\n BUTTON_COPY(\n 16,\n R.string.button_copy,\n R.drawable.gb_ic_copy,\n- MaterialR.attr.colorOnSurface\n+ MaterialR.attr.colorOnSurface,\n+ TAKE_AN_ACTION_GROUP_ID,\n+ 7\n ),\n BUTTON_COPY_URL(\n 17,\n- R.string.button_copy_link,\n- R.drawable.gb_ic_link,\n- MaterialR.attr.colorOnSurface\n+ R.string.button_share,\n+ R.drawable.gb_ic_share,\n+ MaterialR.attr.colorOnSurface,\n+ SHARE_AND_PROMOTE_GROUP_ID,\n+ 1\n ),\n BUTTON_PROMOTE_WITH_BLAZE(\n 18,\n R.string.button_promote_with_blaze,\n- R.drawable.ic_promote_with_blaze,\n- 0\n+ R.drawable.ic_blaze_flame_24dp,\n+ 0,\n+ SHARE_AND_PROMOTE_GROUP_ID,\n+ 2\n+ ),\n+ BUTTON_COMMENTS(\n+ 19,\n+ R.string.button_comments,\n+ R.drawable.gb_ic_comment,\n+ MaterialR.attr.colorOnSurface,\n+ NAVIGATE_GROUP_ID,\n+ 2\n );\n \n companion object {\ndiff --git a/WordPress/src/main/res/drawable/gb_ic_link.xml b/WordPress/src/main/res/drawable/gb_ic_link.xml\ndeleted file mode 100644\nindex 2b59e2b71bba..000000000000\n--- a/WordPress/src/main/res/drawable/gb_ic_link.xml\n+++ /dev/null\n@@ -1,10 +0,0 @@\n-\n- \n-\ndiff --git a/WordPress/src/main/res/drawable/ic_blaze_flame_24dp.xml b/WordPress/src/main/res/drawable/ic_blaze_flame_24dp.xml\nnew file mode 100644\nindex 000000000000..cb0c5a85330f\n--- /dev/null\n+++ b/WordPress/src/main/res/drawable/ic_blaze_flame_24dp.xml\n@@ -0,0 +1,5 @@\n+\n+ \n+\ndiff --git a/WordPress/src/main/res/drawable/ic_gridicons_link_white_24dp.xml b/WordPress/src/main/res/drawable/ic_gridicons_link_white_24dp.xml\nnew file mode 100644\nindex 000000000000..f71d1dfc1e80\n--- /dev/null\n+++ b/WordPress/src/main/res/drawable/ic_gridicons_link_white_24dp.xml\n@@ -0,0 +1,9 @@\n+\n+ \n+\ndiff --git a/WordPress/src/main/res/drawable/ic_placeholder_24dp.xml b/WordPress/src/main/res/drawable/ic_placeholder_24dp.xml\nnew file mode 100644\nindex 000000000000..c47844125ac7\n--- /dev/null\n+++ b/WordPress/src/main/res/drawable/ic_placeholder_24dp.xml\n@@ -0,0 +1,9 @@\n+\n+ \n+\ndiff --git a/WordPress/src/main/res/values/strings.xml b/WordPress/src/main/res/values/strings.xml\nindex ddd1971d2edf..e3270b13516c 100644\n--- a/WordPress/src/main/res/values/strings.xml\n+++ b/WordPress/src/main/res/values/strings.xml\n@@ -309,6 +309,8 @@\n Duplicate\n Copy link\n Promote with Blaze\n+ @string/comments\n+ @string/share_desc\n \n \n Upload failed for \\\"%s\\\"\n", "test_patch": "diff --git a/WordPress/src/test/java/org/wordpress/android/viewmodel/posts/PostListItemUiStateHelperTest.kt b/WordPress/src/test/java/org/wordpress/android/viewmodel/posts/PostListItemUiStateHelperTest.kt\nindex 0937eb3a4a8f..d8f6bd64dfbb 100644\n--- a/WordPress/src/test/java/org/wordpress/android/viewmodel/posts/PostListItemUiStateHelperTest.kt\n+++ b/WordPress/src/test/java/org/wordpress/android/viewmodel/posts/PostListItemUiStateHelperTest.kt\n@@ -92,15 +92,12 @@ class PostListItemUiStateHelperTest {\n val state = createPostListItemUiState(\n post = createPostModel(status = POST_STATE_DRAFT)\n )\n-\n-\n- assertThat(state.moreActions.actions[0].buttonType).isEqualTo(PostListButtonType.BUTTON_EDIT)\n+ assertThat(state.moreActions.actions[0].buttonType).isEqualTo(PostListButtonType.BUTTON_VIEW)\n assertThat(state.moreActions.actions[1].buttonType).isEqualTo(PostListButtonType.BUTTON_PUBLISH)\n- assertThat(state.moreActions.actions[2].buttonType).isEqualTo(PostListButtonType.BUTTON_VIEW)\n- assertThat(state.moreActions.actions[3].buttonType).isEqualTo(PostListButtonType.BUTTON_COPY)\n- assertThat(state.moreActions.actions[4].buttonType).isEqualTo(PostListButtonType.BUTTON_COPY_URL)\n- assertThat(state.moreActions.actions[5].buttonType).isEqualTo(PostListButtonType.BUTTON_TRASH)\n- assertThat(state.moreActions.actions).hasSize(6)\n+ assertThat(state.moreActions.actions[2].buttonType).isEqualTo(PostListButtonType.BUTTON_COPY)\n+ assertThat(state.moreActions.actions[3].buttonType).isEqualTo(PostListButtonType.BUTTON_COPY_URL)\n+ assertThat(state.moreActions.actions[4].buttonType).isEqualTo(PostListButtonType.BUTTON_TRASH)\n+ assertThat(state.moreActions.actions).hasSize(5)\n }\n \n @Test\n@@ -109,12 +106,11 @@ class PostListItemUiStateHelperTest {\n post = createPostModel(status = POST_STATE_DRAFT, isLocalDraft = true)\n )\n \n- assertThat(state.moreActions.actions[0].buttonType).isEqualTo(PostListButtonType.BUTTON_EDIT)\n+ assertThat(state.moreActions.actions[0].buttonType).isEqualTo(PostListButtonType.BUTTON_PREVIEW)\n assertThat(state.moreActions.actions[1].buttonType).isEqualTo(PostListButtonType.BUTTON_PUBLISH)\n- assertThat(state.moreActions.actions[2].buttonType).isEqualTo(PostListButtonType.BUTTON_PREVIEW)\n- assertThat(state.moreActions.actions[3].buttonType).isEqualTo(PostListButtonType.BUTTON_COPY)\n- assertThat(state.moreActions.actions[4].buttonType).isEqualTo(PostListButtonType.BUTTON_DELETE)\n- assertThat(state.moreActions.actions).hasSize(5)\n+ assertThat(state.moreActions.actions[2].buttonType).isEqualTo(PostListButtonType.BUTTON_COPY)\n+ assertThat(state.moreActions.actions[3].buttonType).isEqualTo(PostListButtonType.BUTTON_DELETE)\n+ assertThat(state.moreActions.actions).hasSize(4)\n }\n \n @Test\n@@ -125,13 +121,12 @@ class PostListItemUiStateHelperTest {\n )\n \n val moreActions = state.moreActions.actions\n- assertThat(moreActions[0].buttonType).isEqualTo(PostListButtonType.BUTTON_EDIT)\n+ assertThat(moreActions[0].buttonType).isEqualTo(PostListButtonType.BUTTON_VIEW)\n assertThat(moreActions[1].buttonType).isEqualTo(PostListButtonType.BUTTON_SUBMIT)\n- assertThat(moreActions[2].buttonType).isEqualTo(PostListButtonType.BUTTON_VIEW)\n- assertThat(moreActions[3].buttonType).isEqualTo(PostListButtonType.BUTTON_COPY)\n- assertThat(moreActions[4].buttonType).isEqualTo(PostListButtonType.BUTTON_COPY_URL)\n- assertThat(moreActions[5].buttonType).isEqualTo(PostListButtonType.BUTTON_TRASH)\n- assertThat(moreActions).hasSize(6)\n+ assertThat(moreActions[2].buttonType).isEqualTo(PostListButtonType.BUTTON_COPY)\n+ assertThat(moreActions[3].buttonType).isEqualTo(PostListButtonType.BUTTON_COPY_URL)\n+ assertThat(moreActions[4].buttonType).isEqualTo(PostListButtonType.BUTTON_TRASH)\n+ assertThat(moreActions).hasSize(5)\n }\n \n @Test\n@@ -142,12 +137,11 @@ class PostListItemUiStateHelperTest {\n )\n \n val moreActions = state.moreActions.actions\n- assertThat(moreActions[0].buttonType).isEqualTo(PostListButtonType.BUTTON_EDIT)\n+ assertThat(moreActions[0].buttonType).isEqualTo(PostListButtonType.BUTTON_PREVIEW)\n assertThat(moreActions[1].buttonType).isEqualTo(PostListButtonType.BUTTON_SUBMIT)\n- assertThat(moreActions[2].buttonType).isEqualTo(PostListButtonType.BUTTON_PREVIEW)\n- assertThat(moreActions[3].buttonType).isEqualTo(PostListButtonType.BUTTON_COPY)\n- assertThat(moreActions[4].buttonType).isEqualTo(PostListButtonType.BUTTON_DELETE)\n- assertThat(moreActions).hasSize(5)\n+ assertThat(moreActions[2].buttonType).isEqualTo(PostListButtonType.BUTTON_COPY)\n+ assertThat(moreActions[3].buttonType).isEqualTo(PostListButtonType.BUTTON_DELETE)\n+ assertThat(moreActions).hasSize(4)\n }\n \n @Test\n@@ -160,12 +154,11 @@ class PostListItemUiStateHelperTest {\n )\n \n val moreActions = state.moreActions.actions\n- assertThat(moreActions[0].buttonType).isEqualTo(PostListButtonType.BUTTON_EDIT)\n- assertThat(moreActions[1].buttonType).isEqualTo(PostListButtonType.BUTTON_RETRY)\n- assertThat(moreActions[2].buttonType).isEqualTo(PostListButtonType.BUTTON_COPY)\n- assertThat(moreActions[3].buttonType).isEqualTo(PostListButtonType.BUTTON_COPY_URL)\n- assertThat(moreActions[4].buttonType).isEqualTo(PostListButtonType.BUTTON_TRASH)\n- assertThat(moreActions).hasSize(5)\n+ assertThat(moreActions[0].buttonType).isEqualTo(PostListButtonType.BUTTON_RETRY)\n+ assertThat(moreActions[1].buttonType).isEqualTo(PostListButtonType.BUTTON_COPY)\n+ assertThat(moreActions[2].buttonType).isEqualTo(PostListButtonType.BUTTON_COPY_URL)\n+ assertThat(moreActions[3].buttonType).isEqualTo(PostListButtonType.BUTTON_TRASH)\n+ assertThat(moreActions).hasSize(4)\n }\n \n @Test\n@@ -178,11 +171,10 @@ class PostListItemUiStateHelperTest {\n )\n \n val moreActions = state.moreActions.actions\n- assertThat(moreActions[0].buttonType).isEqualTo(PostListButtonType.BUTTON_EDIT)\n- assertThat(moreActions[1].buttonType).isEqualTo(PostListButtonType.BUTTON_RETRY)\n- assertThat(moreActions[2].buttonType).isEqualTo(PostListButtonType.BUTTON_COPY)\n- assertThat(moreActions[3].buttonType).isEqualTo(PostListButtonType.BUTTON_DELETE)\n- assertThat(moreActions).hasSize(4)\n+ assertThat(moreActions[0].buttonType).isEqualTo(PostListButtonType.BUTTON_RETRY)\n+ assertThat(moreActions[1].buttonType).isEqualTo(PostListButtonType.BUTTON_COPY)\n+ assertThat(moreActions[2].buttonType).isEqualTo(PostListButtonType.BUTTON_DELETE)\n+ assertThat(moreActions).hasSize(3)\n }\n \n @Test\n@@ -195,12 +187,11 @@ class PostListItemUiStateHelperTest {\n capabilitiesToPublish = false\n )\n \n- assertThat(state.moreActions.actions[0].buttonType).isEqualTo(PostListButtonType.BUTTON_EDIT)\n- assertThat(state.moreActions.actions[1].buttonType).isEqualTo(PostListButtonType.BUTTON_RETRY)\n- assertThat(state.moreActions.actions[2].buttonType).isEqualTo(PostListButtonType.BUTTON_COPY)\n- assertThat(state.moreActions.actions[3].buttonType).isEqualTo(PostListButtonType.BUTTON_COPY_URL)\n- assertThat(state.moreActions.actions[4].buttonType).isEqualTo(PostListButtonType.BUTTON_TRASH)\n- assertThat(state.moreActions.actions).hasSize(5)\n+ assertThat(state.moreActions.actions[0].buttonType).isEqualTo(PostListButtonType.BUTTON_RETRY)\n+ assertThat(state.moreActions.actions[1].buttonType).isEqualTo(PostListButtonType.BUTTON_COPY)\n+ assertThat(state.moreActions.actions[2].buttonType).isEqualTo(PostListButtonType.BUTTON_COPY_URL)\n+ assertThat(state.moreActions.actions[3].buttonType).isEqualTo(PostListButtonType.BUTTON_TRASH)\n+ assertThat(state.moreActions.actions).hasSize(4)\n }\n \n @Test\n@@ -214,11 +205,10 @@ class PostListItemUiStateHelperTest {\n capabilitiesToPublish = false\n )\n \n- assertThat(state.moreActions.actions[0].buttonType).isEqualTo(PostListButtonType.BUTTON_EDIT)\n- assertThat(state.moreActions.actions[1].buttonType).isEqualTo(PostListButtonType.BUTTON_RETRY)\n- assertThat(state.moreActions.actions[2].buttonType).isEqualTo(PostListButtonType.BUTTON_COPY)\n- assertThat(state.moreActions.actions[3].buttonType).isEqualTo(PostListButtonType.BUTTON_DELETE)\n- assertThat(state.moreActions.actions).hasSize(4)\n+ assertThat(state.moreActions.actions[0].buttonType).isEqualTo(PostListButtonType.BUTTON_RETRY)\n+ assertThat(state.moreActions.actions[1].buttonType).isEqualTo(PostListButtonType.BUTTON_COPY)\n+ assertThat(state.moreActions.actions[2].buttonType).isEqualTo(PostListButtonType.BUTTON_DELETE)\n+ assertThat(state.moreActions.actions).hasSize(3)\n }\n \n @Test\n@@ -227,15 +217,15 @@ class PostListItemUiStateHelperTest {\n val state = createPostListItemUiState(\n post = createPostModel(status = POST_STATE_PUBLISH)\n )\n+\n val moreActions = state.moreActions.actions\n- assertThat(moreActions[0].buttonType).isEqualTo(PostListButtonType.BUTTON_EDIT)\n- assertThat(moreActions[1].buttonType).isEqualTo(PostListButtonType.BUTTON_VIEW)\n- assertThat(moreActions[2].buttonType).isEqualTo(PostListButtonType.BUTTON_STATS)\n- assertThat(moreActions[3].buttonType).isEqualTo(PostListButtonType.BUTTON_COPY)\n- assertThat(moreActions[4].buttonType).isEqualTo(PostListButtonType.BUTTON_MOVE_TO_DRAFT)\n- assertThat(moreActions[5].buttonType).isEqualTo(PostListButtonType.BUTTON_COPY_URL)\n- assertThat(moreActions[6].buttonType).isEqualTo(PostListButtonType.BUTTON_TRASH)\n- assertThat(moreActions).hasSize(7)\n+ assertThat(moreActions[0].buttonType).isEqualTo(PostListButtonType.BUTTON_VIEW)\n+ assertThat(moreActions[1].buttonType).isEqualTo(PostListButtonType.BUTTON_MOVE_TO_DRAFT)\n+ assertThat(moreActions[2].buttonType).isEqualTo(PostListButtonType.BUTTON_COPY)\n+ assertThat(moreActions[3].buttonType).isEqualTo(PostListButtonType.BUTTON_COPY_URL)\n+ assertThat(moreActions[4].buttonType).isEqualTo(PostListButtonType.BUTTON_STATS)\n+ assertThat(moreActions[5].buttonType).isEqualTo(PostListButtonType.BUTTON_TRASH)\n+ assertThat(moreActions).hasSize(6)\n }\n \n @Test\n@@ -246,13 +236,12 @@ class PostListItemUiStateHelperTest {\n )\n \n val moreActions = state.moreActions.actions\n- assertThat(moreActions[0].buttonType).isEqualTo(PostListButtonType.BUTTON_EDIT)\n- assertThat(moreActions[1].buttonType).isEqualTo(PostListButtonType.BUTTON_VIEW)\n+ assertThat(moreActions[0].buttonType).isEqualTo(PostListButtonType.BUTTON_VIEW)\n+ assertThat(moreActions[1].buttonType).isEqualTo(PostListButtonType.BUTTON_MOVE_TO_DRAFT)\n assertThat(moreActions[2].buttonType).isEqualTo(PostListButtonType.BUTTON_COPY)\n- assertThat(moreActions[3].buttonType).isEqualTo(PostListButtonType.BUTTON_MOVE_TO_DRAFT)\n- assertThat(moreActions[4].buttonType).isEqualTo(PostListButtonType.BUTTON_COPY_URL)\n- assertThat(moreActions[5].buttonType).isEqualTo(PostListButtonType.BUTTON_TRASH)\n- assertThat(moreActions).hasSize(6)\n+ assertThat(moreActions[3].buttonType).isEqualTo(PostListButtonType.BUTTON_COPY_URL)\n+ assertThat(moreActions[4].buttonType).isEqualTo(PostListButtonType.BUTTON_TRASH)\n+ assertThat(moreActions).hasSize(5)\n }\n \n @Test\n@@ -263,14 +252,13 @@ class PostListItemUiStateHelperTest {\n )\n \n val moreActions = state.moreActions.actions\n- assertThat(moreActions[0].buttonType).isEqualTo(PostListButtonType.BUTTON_EDIT)\n- assertThat(moreActions[1].buttonType).isEqualTo(PostListButtonType.BUTTON_VIEW)\n- assertThat(moreActions[2].buttonType).isEqualTo(PostListButtonType.BUTTON_STATS)\n- assertThat(moreActions[3].buttonType).isEqualTo(PostListButtonType.BUTTON_COPY)\n- assertThat(moreActions[4].buttonType).isEqualTo(PostListButtonType.BUTTON_MOVE_TO_DRAFT)\n- assertThat(moreActions[5].buttonType).isEqualTo(PostListButtonType.BUTTON_COPY_URL)\n- assertThat(moreActions[6].buttonType).isEqualTo(PostListButtonType.BUTTON_TRASH)\n- assertThat(moreActions).hasSize(7)\n+ assertThat(moreActions[0].buttonType).isEqualTo(PostListButtonType.BUTTON_VIEW)\n+ assertThat(moreActions[1].buttonType).isEqualTo(PostListButtonType.BUTTON_MOVE_TO_DRAFT)\n+ assertThat(moreActions[2].buttonType).isEqualTo(PostListButtonType.BUTTON_COPY)\n+ assertThat(moreActions[3].buttonType).isEqualTo(PostListButtonType.BUTTON_COPY_URL)\n+ assertThat(moreActions[4].buttonType).isEqualTo(PostListButtonType.BUTTON_STATS)\n+ assertThat(moreActions[5].buttonType).isEqualTo(PostListButtonType.BUTTON_TRASH)\n+ assertThat(moreActions).hasSize(6)\n }\n \n @Test\n@@ -281,13 +269,12 @@ class PostListItemUiStateHelperTest {\n )\n \n val moreActions = state.moreActions.actions\n- assertThat(moreActions[0].buttonType).isEqualTo(PostListButtonType.BUTTON_EDIT)\n- assertThat(moreActions[1].buttonType).isEqualTo(PostListButtonType.BUTTON_VIEW)\n+ assertThat(moreActions[0].buttonType).isEqualTo(PostListButtonType.BUTTON_VIEW)\n+ assertThat(moreActions[1].buttonType).isEqualTo(PostListButtonType.BUTTON_MOVE_TO_DRAFT)\n assertThat(moreActions[2].buttonType).isEqualTo(PostListButtonType.BUTTON_COPY)\n- assertThat(moreActions[3].buttonType).isEqualTo(PostListButtonType.BUTTON_MOVE_TO_DRAFT)\n- assertThat(moreActions[4].buttonType).isEqualTo(PostListButtonType.BUTTON_COPY_URL)\n- assertThat(moreActions[5].buttonType).isEqualTo(PostListButtonType.BUTTON_TRASH)\n- assertThat(moreActions).hasSize(6)\n+ assertThat(moreActions[3].buttonType).isEqualTo(PostListButtonType.BUTTON_COPY_URL)\n+ assertThat(moreActions[4].buttonType).isEqualTo(PostListButtonType.BUTTON_TRASH)\n+ assertThat(moreActions).hasSize(5)\n }\n \n @Test\n@@ -297,14 +284,13 @@ class PostListItemUiStateHelperTest {\n )\n \n val moreActions = state.moreActions.actions\n- assertThat(moreActions[0].buttonType).isEqualTo(PostListButtonType.BUTTON_EDIT)\n+ assertThat(moreActions[0].buttonType).isEqualTo(PostListButtonType.BUTTON_PREVIEW)\n assertThat(moreActions[1].buttonType).isEqualTo(PostListButtonType.BUTTON_PUBLISH)\n- assertThat(moreActions[2].buttonType).isEqualTo(PostListButtonType.BUTTON_PREVIEW)\n+ assertThat(moreActions[2].buttonType).isEqualTo(PostListButtonType.BUTTON_MOVE_TO_DRAFT)\n assertThat(moreActions[3].buttonType).isEqualTo(PostListButtonType.BUTTON_COPY)\n- assertThat(moreActions[4].buttonType).isEqualTo(PostListButtonType.BUTTON_MOVE_TO_DRAFT)\n- assertThat(moreActions[5].buttonType).isEqualTo(PostListButtonType.BUTTON_COPY_URL)\n- assertThat(moreActions[6].buttonType).isEqualTo(PostListButtonType.BUTTON_TRASH)\n- assertThat(moreActions).hasSize(7)\n+ assertThat(moreActions[4].buttonType).isEqualTo(PostListButtonType.BUTTON_COPY_URL)\n+ assertThat(moreActions[5].buttonType).isEqualTo(PostListButtonType.BUTTON_TRASH)\n+ assertThat(moreActions).hasSize(6)\n }\n \n @Test\n@@ -317,13 +303,12 @@ class PostListItemUiStateHelperTest {\n )\n \n val moreActions = state.moreActions.actions\n- assertThat(moreActions[0].buttonType).isEqualTo(PostListButtonType.BUTTON_EDIT)\n- assertThat(moreActions[1].buttonType).isEqualTo(PostListButtonType.BUTTON_RETRY)\n+ assertThat(moreActions[0].buttonType).isEqualTo(PostListButtonType.BUTTON_RETRY)\n+ assertThat(moreActions[1].buttonType).isEqualTo(PostListButtonType.BUTTON_MOVE_TO_DRAFT)\n assertThat(moreActions[2].buttonType).isEqualTo(PostListButtonType.BUTTON_COPY)\n- assertThat(moreActions[3].buttonType).isEqualTo(PostListButtonType.BUTTON_MOVE_TO_DRAFT)\n- assertThat(moreActions[4].buttonType).isEqualTo(PostListButtonType.BUTTON_COPY_URL)\n- assertThat(moreActions[5].buttonType).isEqualTo(PostListButtonType.BUTTON_TRASH)\n- assertThat(moreActions).hasSize(6)\n+ assertThat(moreActions[3].buttonType).isEqualTo(PostListButtonType.BUTTON_COPY_URL)\n+ assertThat(moreActions[4].buttonType).isEqualTo(PostListButtonType.BUTTON_TRASH)\n+ assertThat(moreActions).hasSize(5)\n }\n \n @Test\n@@ -344,11 +329,10 @@ class PostListItemUiStateHelperTest {\n )\n \n val moreActions = state.moreActions.actions\n- assertThat(moreActions[0].buttonType).isEqualTo(PostListButtonType.BUTTON_EDIT)\n- assertThat(moreActions[1].buttonType).isEqualTo(PostListButtonType.BUTTON_VIEW)\n- assertThat(moreActions[2].buttonType).isEqualTo(PostListButtonType.BUTTON_COPY_URL)\n- assertThat(moreActions[3].buttonType).isEqualTo(PostListButtonType.BUTTON_TRASH)\n- assertThat(moreActions).hasSize(4)\n+ assertThat(moreActions[0].buttonType).isEqualTo(PostListButtonType.BUTTON_VIEW)\n+ assertThat(moreActions[1].buttonType).isEqualTo(PostListButtonType.BUTTON_COPY_URL)\n+ assertThat(moreActions[2].buttonType).isEqualTo(PostListButtonType.BUTTON_TRASH)\n+ assertThat(moreActions).hasSize(3)\n }\n \n @Test\n@@ -358,12 +342,11 @@ class PostListItemUiStateHelperTest {\n )\n \n val moreActions = state.moreActions.actions\n- assertThat(moreActions[0].buttonType).isEqualTo(PostListButtonType.BUTTON_EDIT)\n+ assertThat(moreActions[0].buttonType).isEqualTo(PostListButtonType.BUTTON_PREVIEW)\n assertThat(moreActions[1].buttonType).isEqualTo(PostListButtonType.BUTTON_SYNC)\n- assertThat(moreActions[2].buttonType).isEqualTo(PostListButtonType.BUTTON_PREVIEW)\n- assertThat(moreActions[3].buttonType).isEqualTo(PostListButtonType.BUTTON_COPY_URL)\n- assertThat(moreActions[4].buttonType).isEqualTo(PostListButtonType.BUTTON_TRASH)\n- assertThat(moreActions).hasSize(5)\n+ assertThat(moreActions[2].buttonType).isEqualTo(PostListButtonType.BUTTON_COPY_URL)\n+ assertThat(moreActions[3].buttonType).isEqualTo(PostListButtonType.BUTTON_TRASH)\n+ assertThat(moreActions).hasSize(4)\n }\n \n @Test\n@@ -376,11 +359,10 @@ class PostListItemUiStateHelperTest {\n )\n \n val moreActions = state.moreActions.actions\n- assertThat(moreActions[0].buttonType).isEqualTo(PostListButtonType.BUTTON_EDIT)\n- assertThat(moreActions[1].buttonType).isEqualTo(PostListButtonType.BUTTON_RETRY)\n- assertThat(moreActions[2].buttonType).isEqualTo(PostListButtonType.BUTTON_COPY_URL)\n- assertThat(moreActions[3].buttonType).isEqualTo(PostListButtonType.BUTTON_TRASH)\n- assertThat(moreActions).hasSize(4)\n+ assertThat(moreActions[0].buttonType).isEqualTo(PostListButtonType.BUTTON_RETRY)\n+ assertThat(moreActions[1].buttonType).isEqualTo(PostListButtonType.BUTTON_COPY_URL)\n+ assertThat(moreActions[2].buttonType).isEqualTo(PostListButtonType.BUTTON_TRASH)\n+ assertThat(moreActions).hasSize(3)\n }\n \n @Test\n@@ -389,12 +371,11 @@ class PostListItemUiStateHelperTest {\n post = createPostModel(status = POST_STATE_PENDING)\n )\n \n- assertThat(state.moreActions.actions[0].buttonType).isEqualTo(PostListButtonType.BUTTON_EDIT)\n+ assertThat(state.moreActions.actions[0].buttonType).isEqualTo(PostListButtonType.BUTTON_VIEW)\n assertThat(state.moreActions.actions[1].buttonType).isEqualTo(PostListButtonType.BUTTON_PUBLISH)\n- assertThat(state.moreActions.actions[2].buttonType).isEqualTo(PostListButtonType.BUTTON_VIEW)\n- assertThat(state.moreActions.actions[3].buttonType).isEqualTo(PostListButtonType.BUTTON_COPY_URL)\n- assertThat(state.moreActions.actions[4].buttonType).isEqualTo(PostListButtonType.BUTTON_TRASH)\n- assertThat(state.moreActions.actions).hasSize(5)\n+ assertThat(state.moreActions.actions[2].buttonType).isEqualTo(PostListButtonType.BUTTON_COPY_URL)\n+ assertThat(state.moreActions.actions[3].buttonType).isEqualTo(PostListButtonType.BUTTON_TRASH)\n+ assertThat(state.moreActions.actions).hasSize(4)\n }\n \n @Test\n@@ -405,11 +386,10 @@ class PostListItemUiStateHelperTest {\n )\n \n val moreActions = state.moreActions.actions\n- assertThat(moreActions[0].buttonType).isEqualTo(PostListButtonType.BUTTON_EDIT)\n- assertThat(moreActions[1].buttonType).isEqualTo(PostListButtonType.BUTTON_VIEW)\n- assertThat(moreActions[2].buttonType).isEqualTo(PostListButtonType.BUTTON_COPY_URL)\n- assertThat(moreActions[3].buttonType).isEqualTo(PostListButtonType.BUTTON_TRASH)\n- assertThat(moreActions).hasSize(4)\n+ assertThat(moreActions[0].buttonType).isEqualTo(PostListButtonType.BUTTON_VIEW)\n+ assertThat(moreActions[1].buttonType).isEqualTo(PostListButtonType.BUTTON_COPY_URL)\n+ assertThat(moreActions[2].buttonType).isEqualTo(PostListButtonType.BUTTON_TRASH)\n+ assertThat(moreActions).hasSize(3)\n }\n \n @Test\n@@ -422,15 +402,14 @@ class PostListItemUiStateHelperTest {\n )\n \n val moreActions = state.moreActions.actions\n- assertThat(moreActions[0].buttonType).isEqualTo(PostListButtonType.BUTTON_EDIT)\n+ assertThat(moreActions[0].buttonType).isEqualTo(PostListButtonType.BUTTON_PREVIEW)\n assertThat(moreActions[1].buttonType).isEqualTo(PostListButtonType.BUTTON_CANCEL_PENDING_AUTO_UPLOAD)\n- assertThat(moreActions[2].buttonType).isEqualTo(PostListButtonType.BUTTON_PREVIEW)\n+ assertThat(moreActions[2].buttonType).isEqualTo(PostListButtonType.BUTTON_MOVE_TO_DRAFT)\n assertThat(moreActions[3].buttonType).isEqualTo(PostListButtonType.BUTTON_COPY)\n- assertThat(moreActions[4].buttonType).isEqualTo(PostListButtonType.BUTTON_MOVE_TO_DRAFT)\n- assertThat(moreActions[5].buttonType).isEqualTo(PostListButtonType.BUTTON_COPY_URL)\n- assertThat(moreActions[6].buttonType).isEqualTo(PostListButtonType.BUTTON_TRASH)\n- assertThat(moreActions).hasSize(7)\n- }\n+ assertThat(moreActions[4].buttonType).isEqualTo(PostListButtonType.BUTTON_COPY_URL)\n+ assertThat(moreActions[5].buttonType).isEqualTo(PostListButtonType.BUTTON_TRASH)\n+ assertThat(moreActions).hasSize(6)\n+ }\n \n @Test\n fun `verify scheduled post with local changes eligible for auto upload`() {\n@@ -442,12 +421,11 @@ class PostListItemUiStateHelperTest {\n )\n \n val moreActions = state.moreActions.actions\n- assertThat(moreActions[0].buttonType).isEqualTo(PostListButtonType.BUTTON_EDIT)\n+ assertThat(moreActions[0].buttonType).isEqualTo(PostListButtonType.BUTTON_PREVIEW)\n assertThat(moreActions[1].buttonType).isEqualTo(PostListButtonType.BUTTON_CANCEL_PENDING_AUTO_UPLOAD)\n- assertThat(moreActions[2].buttonType).isEqualTo(PostListButtonType.BUTTON_PREVIEW)\n- assertThat(moreActions[3].buttonType).isEqualTo(PostListButtonType.BUTTON_COPY_URL)\n- assertThat(moreActions[4].buttonType).isEqualTo(PostListButtonType.BUTTON_TRASH)\n- assertThat(moreActions).hasSize(5)\n+ assertThat(moreActions[2].buttonType).isEqualTo(PostListButtonType.BUTTON_COPY_URL)\n+ assertThat(moreActions[3].buttonType).isEqualTo(PostListButtonType.BUTTON_TRASH)\n+ assertThat(moreActions).hasSize(4)\n }\n \n @Test\n@@ -458,13 +436,13 @@ class PostListItemUiStateHelperTest {\n val state = createPostListItemUiState(\n post = createPostModel(status = POST_STATE_PRIVATE, isLocallyChanged = true)\n )\n+\n val moreActions = state.moreActions.actions\n- assertThat(moreActions[0].buttonType).isEqualTo(PostListButtonType.BUTTON_EDIT)\n+ assertThat(moreActions[0].buttonType).isEqualTo(PostListButtonType.BUTTON_PREVIEW)\n assertThat(moreActions[1].buttonType).isEqualTo(PostListButtonType.BUTTON_CANCEL_PENDING_AUTO_UPLOAD)\n- assertThat(moreActions[2].buttonType).isEqualTo(PostListButtonType.BUTTON_PREVIEW)\n- assertThat(moreActions[3].buttonType).isEqualTo(PostListButtonType.BUTTON_COPY_URL)\n- assertThat(moreActions[4].buttonType).isEqualTo(PostListButtonType.BUTTON_TRASH)\n- assertThat(moreActions).hasSize(5)\n+ assertThat(moreActions[2].buttonType).isEqualTo(PostListButtonType.BUTTON_COPY_URL)\n+ assertThat(moreActions[3].buttonType).isEqualTo(PostListButtonType.BUTTON_TRASH)\n+ assertThat(moreActions).hasSize(4)\n }\n \n @Test\n@@ -476,14 +454,13 @@ class PostListItemUiStateHelperTest {\n post = createPostModel(status = POST_STATE_DRAFT, isLocallyChanged = true)\n )\n \n- assertThat(state.moreActions.actions[0].buttonType).isEqualTo(PostListButtonType.BUTTON_EDIT)\n+ assertThat(state.moreActions.actions[0].buttonType).isEqualTo(PostListButtonType.BUTTON_PREVIEW)\n assertThat(state.moreActions.actions[1].buttonType)\n .isEqualTo(PostListButtonType.BUTTON_CANCEL_PENDING_AUTO_UPLOAD)\n- assertThat(state.moreActions.actions[2].buttonType).isEqualTo(PostListButtonType.BUTTON_PREVIEW)\n- assertThat(state.moreActions.actions[3].buttonType).isEqualTo(PostListButtonType.BUTTON_COPY)\n- assertThat(state.moreActions.actions[4].buttonType).isEqualTo(PostListButtonType.BUTTON_COPY_URL)\n- assertThat(state.moreActions.actions[5].buttonType).isEqualTo(PostListButtonType.BUTTON_TRASH)\n- assertThat(state.moreActions.actions).hasSize(6)\n+ assertThat(state.moreActions.actions[2].buttonType).isEqualTo(PostListButtonType.BUTTON_COPY)\n+ assertThat(state.moreActions.actions[3].buttonType).isEqualTo(PostListButtonType.BUTTON_COPY_URL)\n+ assertThat(state.moreActions.actions[4].buttonType).isEqualTo(PostListButtonType.BUTTON_TRASH)\n+ assertThat(state.moreActions.actions).hasSize(5)\n }\n \n @Test\n@@ -505,14 +482,13 @@ class PostListItemUiStateHelperTest {\n )\n \n val moreActions = state.moreActions.actions\n- assertThat(moreActions[0].buttonType).isEqualTo(PostListButtonType.BUTTON_EDIT)\n- assertThat(moreActions[1].buttonType).isEqualTo(PostListButtonType.BUTTON_CANCEL_PENDING_AUTO_UPLOAD)\n- assertThat(moreActions[2].buttonType).isEqualTo(PostListButtonType.BUTTON_RETRY)\n+ assertThat(moreActions[0].buttonType).isEqualTo(PostListButtonType.BUTTON_CANCEL_PENDING_AUTO_UPLOAD)\n+ assertThat(moreActions[1].buttonType).isEqualTo(PostListButtonType.BUTTON_RETRY)\n+ assertThat(moreActions[2].buttonType).isEqualTo(PostListButtonType.BUTTON_MOVE_TO_DRAFT)\n assertThat(moreActions[3].buttonType).isEqualTo(PostListButtonType.BUTTON_COPY)\n- assertThat(moreActions[4].buttonType).isEqualTo(PostListButtonType.BUTTON_MOVE_TO_DRAFT)\n- assertThat(moreActions[5].buttonType).isEqualTo(PostListButtonType.BUTTON_COPY_URL)\n- assertThat(moreActions[6].buttonType).isEqualTo(PostListButtonType.BUTTON_TRASH)\n- assertThat(moreActions).hasSize(7)\n+ assertThat(moreActions[4].buttonType).isEqualTo(PostListButtonType.BUTTON_COPY_URL)\n+ assertThat(moreActions[5].buttonType).isEqualTo(PostListButtonType.BUTTON_TRASH)\n+ assertThat(moreActions).hasSize(6)\n }\n \n @Test\n@@ -845,12 +821,11 @@ class PostListItemUiStateHelperTest {\n )\n \n val moreActions = state.moreActions.actions\n- assertThat(moreActions[0].buttonType).isEqualTo(PostListButtonType.BUTTON_EDIT)\n- assertThat(moreActions[1].buttonType).isEqualTo(PostListButtonType.BUTTON_RETRY)\n+ assertThat(moreActions[0].buttonType).isEqualTo(PostListButtonType.BUTTON_RETRY)\n+ assertThat(moreActions[1].buttonType).isEqualTo(PostListButtonType.BUTTON_MOVE_TO_DRAFT)\n assertThat(moreActions[2].buttonType).isEqualTo(PostListButtonType.BUTTON_COPY)\n- assertThat(moreActions[3].buttonType).isEqualTo(PostListButtonType.BUTTON_MOVE_TO_DRAFT)\n- assertThat(moreActions[4].buttonType).isEqualTo(PostListButtonType.BUTTON_DELETE)\n- assertThat(moreActions).hasSize(5)\n+ assertThat(moreActions[3].buttonType).isEqualTo(PostListButtonType.BUTTON_DELETE)\n+ assertThat(moreActions).hasSize(4)\n }\n \n @Test\n", "problem_statement": "UI Modernization Posts: Update context menus\nFigma Design eYeHXEMDbnFptE40xUqZ2T-fi-836_5909\r\n```[tasklist]\n### Tasks\n- [x] Apply new grouping and ordering for the context menu on each tab\n- [x] Adjust copy and icons\n- [x] Apply existing visibility rules\n- [x] Move offline actions to the context menu\n- [x] Add GB icons to the project\n```\r\n\n", "hints_text": "", "created_at": "2023-10-30T21:16:03Z", "version": "23.5", "FAIL_TO_PASS": [ "gradle_test_execution" ], "PASS_TO_PASS": [], "ERROR_TO_PASS": [], "environment_setup_commit": "843bb9325e868c5a18177ff203ed9a3f08cd8daa" }, { "repo": "wordpress-mobile/WordPress-Android", "pull_number": 20940, "instance_id": "wordpress-mobile__WordPress-Android-20940", "issue_numbers": [ "20033" ], "base_commit": "a24e5d1d040b312f72243ec291ae56f2b44f8cce", "patch": "diff --git a/WordPress/src/main/java/org/wordpress/android/ui/reader/utils/ReaderTopBarMenuHelper.kt b/WordPress/src/main/java/org/wordpress/android/ui/reader/utils/ReaderTopBarMenuHelper.kt\nindex ba94c014f5c5..e5b979bd9bc3 100644\n--- a/WordPress/src/main/java/org/wordpress/android/ui/reader/utils/ReaderTopBarMenuHelper.kt\n+++ b/WordPress/src/main/java/org/wordpress/android/ui/reader/utils/ReaderTopBarMenuHelper.kt\n@@ -55,11 +55,30 @@ class ReaderTopBarMenuHelper @Inject constructor(\n .takeIf { it.isNotEmpty() }\n ?.let { customListsArray ->\n add(MenuElementData.Divider)\n- add(createCustomListsItem(customListsArray))\n+ createCustomListsItems(customListsArray)\n }\n }\n }\n \n+ private fun MutableList.createCustomListsItems(\n+ customListsArray: SparseArrayCompat\n+ ) {\n+ if (customListsArray.size() > 2) {\n+ // If custom lists has more than 2 items, we add a submenu called \"Lists\"\n+ add(createCustomListsItem(customListsArray))\n+ } else {\n+ // If the custom lists has 2 or less items, we add the items directly without submenu\n+ customListsArray.forEach { index, readerTag ->\n+ add(\n+ MenuElementData.Item.Single(\n+ id = getMenuItemIdFromReaderTagIndex(index),\n+ text = UiString.UiStringText(readerTag.tagTitle),\n+ )\n+ )\n+ }\n+ }\n+ }\n+\n private fun createDiscoverItem(id: String): MenuElementData.Item.Single {\n return MenuElementData.Item.Single(\n id = id,\n", "test_patch": "diff --git a/WordPress/src/test/java/org/wordpress/android/ui/reader/utils/ReaderTopBarMenuHelperTest.kt b/WordPress/src/test/java/org/wordpress/android/ui/reader/utils/ReaderTopBarMenuHelperTest.kt\nindex 03e57616424e..e9850dab73b1 100644\n--- a/WordPress/src/test/java/org/wordpress/android/ui/reader/utils/ReaderTopBarMenuHelperTest.kt\n+++ b/WordPress/src/test/java/org/wordpress/android/ui/reader/utils/ReaderTopBarMenuHelperTest.kt\n@@ -72,6 +72,27 @@ class ReaderTopBarMenuHelperTest {\n assertThat(customList3Item.text).isEqualTo(UiStringText(\"custom-list-3\"))\n }\n \n+ @Test\n+ fun `GIVEN custom lists has 2 items or less WHEN createMenu THEN custom lists items are shown outside a submenu`() {\n+ val tags = ReaderTagList().apply {\n+ add(mockFollowingTag()) // item 0\n+ add(mockDiscoverTag()) // item 1\n+ add(mockSavedTag()) // item 2\n+ add(mockLikedTag()) // item 3\n+ add(mockA8CTag()) // item 4\n+ add(mockFollowedP2sTag()) // item 5\n+ add(createCustomListTag(\"custom-list-1\")) // item 6\n+ add(createCustomListTag(\"custom-list-2\")) // item 7\n+ }\n+ val menu = helper.createMenu(tags)\n+\n+ val customListItem1 = menu.findSingleItem { it.id == \"6\" }!!\n+ assertThat(customListItem1.text).isEqualTo(UiStringText(\"custom-list-1\"))\n+\n+ val customListItem2 = menu.findSingleItem { it.id == \"7\" }!!\n+ assertThat(customListItem2.text).isEqualTo(UiStringText(\"custom-list-2\"))\n+ }\n+\n @Test\n fun `GIVEN all tags are available and tags FF enabled WHEN createMenu THEN all items are created correctly`() {\n whenever(readerTagsFeedFeatureConfig.isEnabled()).thenReturn(true)\n", "problem_statement": "[Reader IA] Show lists directly on dropdown menu if there are 2 or fewer\nWe are currently grouping the Lists in a \"Lists\" submenu independent of the number of lists the user has, but we should only show that submenu when the user has over 2 lists.\r\n\r\nSo if the user has 2 or fewer, they should be displayed directly in the menu root.\r\n\r\n![image](https://github.com/wordpress-mobile/WordPress-Android/assets/5091503/57e663d9-218f-4a58-a447-05a86406ea86)\r\n\r\nInternal ref: pcdRpT-4tr-p2#comment-7237\n", "hints_text": "", "created_at": "2024-06-05T18:19:01Z", "version": "25.01", "FAIL_TO_PASS": [ "gradle_test_execution" ], "PASS_TO_PASS": [], "ERROR_TO_PASS": [], "environment_setup_commit": "a24e5d1d040b312f72243ec291ae56f2b44f8cce" }, { "repo": "wordpress-mobile/WordPress-Android", "pull_number": 19656, "instance_id": "wordpress-mobile__WordPress-Android-19656", "issue_numbers": [ "19557" ], "base_commit": "65f9f87a953f0f0d0f4bac8bd04ee02f9fcb2152", "patch": "diff --git a/WordPress/src/main/java/org/wordpress/android/ui/posts/prepublishing/home/PrepublishingHomeViewModel.kt b/WordPress/src/main/java/org/wordpress/android/ui/posts/prepublishing/home/PrepublishingHomeViewModel.kt\nindex 0004f8b6fae7..4d385373241d 100644\n--- a/WordPress/src/main/java/org/wordpress/android/ui/posts/prepublishing/home/PrepublishingHomeViewModel.kt\n+++ b/WordPress/src/main/java/org/wordpress/android/ui/posts/prepublishing/home/PrepublishingHomeViewModel.kt\n@@ -123,16 +123,18 @@ class PrepublishingHomeViewModel @Inject constructor(\n site\n )\n \n- add(HomeUiState(\n- navigationAction = PrepublishingScreenNavigation.Categories,\n- actionResult = if (categoriesString.isNotEmpty()) {\n- UiStringText(categoriesString)\n- } else {\n- run { UiStringRes(R.string.prepublishing_nudges_home_categories_not_set) }\n- },\n- actionClickable = true,\n- onNavigationActionClicked = ::onActionClicked\n- ))\n+ if (!editPostRepository.isPage) {\n+ add(HomeUiState(\n+ navigationAction = PrepublishingScreenNavigation.Categories,\n+ actionResult = if (categoriesString.isNotEmpty()) {\n+ UiStringText(categoriesString)\n+ } else {\n+ run { UiStringRes(R.string.prepublishing_nudges_home_categories_not_set) }\n+ },\n+ actionClickable = true,\n+ onNavigationActionClicked = ::onActionClicked\n+ ))\n+ }\n \n add(SocialUiState.Hidden)\n \n", "test_patch": "diff --git a/WordPress/src/test/java/org/wordpress/android/ui/posts/PrepublishingHomeViewModelTest.kt b/WordPress/src/test/java/org/wordpress/android/ui/posts/PrepublishingHomeViewModelTest.kt\nindex 9ce9e6795e6b..9d861816c5bf 100644\n--- a/WordPress/src/test/java/org/wordpress/android/ui/posts/PrepublishingHomeViewModelTest.kt\n+++ b/WordPress/src/test/java/org/wordpress/android/ui/posts/PrepublishingHomeViewModelTest.kt\n@@ -112,7 +112,7 @@ class PrepublishingHomeViewModelTest : BaseUnitTest() {\n @Test\n fun `verify that page home actions are propagated to prepublishingHomeUiState once the viewModel is started`() {\n // arrange\n- val expectedActionsAmount = 2\n+ val expectedActionsAmount = 1\n whenever(editPostRepository.isPage).thenReturn(true)\n \n // act\n@@ -148,6 +148,30 @@ class PrepublishingHomeViewModelTest : BaseUnitTest() {\n assertThat(getHomeUiState(PrepublishingScreenNavigation.Tags)).isNull()\n }\n \n+ @Test\n+ fun `verify that categories actions is propagated to prepublishingHomeUiState once post is not a page`() {\n+ // arrange\n+ whenever(editPostRepository.isPage).thenReturn(false)\n+\n+ // act\n+ viewModel.start(editPostRepository, site, false)\n+\n+ // assert\n+ assertThat(getHomeUiState(PrepublishingScreenNavigation.Categories)).isNotNull()\n+ }\n+\n+ @Test\n+ fun `verify that categories actions is not propagated to prepublishingHomeUiState once post is a page`() {\n+ // arrange\n+ whenever(editPostRepository.isPage).thenReturn(true)\n+\n+ // act\n+ viewModel.start(editPostRepository, site, false)\n+\n+ // assert\n+ assertThat(getHomeUiState(PrepublishingScreenNavigation.Categories)).isNull()\n+ }\n+\n @Test\n fun `verify that header ui state is propagated to prepublishingHomeUiState once the viewModel is started`() {\n // arrange\n", "problem_statement": "Pages: When publishing pages you see the prepublish modal that tells you select catergoris\n### Expected behaviour\r\nYou should not see the prepublish modal and you should not be able to choose categories. \r\n\r\n### Actual behaviour\r\nYou see this. After you publish a page.\r\n\r\n\r\n### Steps to reproduce the behavior\r\nCreate a new page. Publish it. \r\n\r\n##### Tested on Pixel 3, Android 12, JPAndroid / WPAndroid 23.6-RC-1\r\n\n", "hints_text": "", "created_at": "2023-11-23T13:54:23Z", "version": "23.71", "FAIL_TO_PASS": [ "gradle_test_execution" ], "PASS_TO_PASS": [], "ERROR_TO_PASS": [], "environment_setup_commit": "e1480e73628fd4d4e716b015b0b2c25009adaff2" }, { "repo": "wordpress-mobile/WordPress-Android", "pull_number": 20564, "instance_id": "wordpress-mobile__WordPress-Android-20564", "issue_numbers": [ "17314" ], "base_commit": "c188122e6ee1d4b1fe844dc127ef1bfd780a3801", "patch": "diff --git a/RELEASE-NOTES.txt b/RELEASE-NOTES.txt\nindex 47aded33e692..7cb01b15dcad 100644\n--- a/RELEASE-NOTES.txt\n+++ b/RELEASE-NOTES.txt\n@@ -4,6 +4,7 @@\n -----\n * [**] Block editor: Highlight text fixes [https://github.com/WordPress/gutenberg/pull/57650]\n * [*] Block editor: Fixes an Aztec editor crash occurring on some occasions when the keyboard suggestions are used [https://github.com/wordpress-mobile/WordPress-Android/pull/20518]\n+* [*] [Jetpack-only] Change \"\u221e\" symbol with \"100%\" on stats [https://github.com/wordpress-mobile/WordPress-Android/pull/20564]\n \n 24.5\n -----\ndiff --git a/WordPress/src/main/java/org/wordpress/android/ui/stats/refresh/utils/StatsUtils.kt b/WordPress/src/main/java/org/wordpress/android/ui/stats/refresh/utils/StatsUtils.kt\nindex 3f14f0dc1b86..5b66e38a6be7 100644\n--- a/WordPress/src/main/java/org/wordpress/android/ui/stats/refresh/utils/StatsUtils.kt\n+++ b/WordPress/src/main/java/org/wordpress/android/ui/stats/refresh/utils/StatsUtils.kt\n@@ -226,7 +226,7 @@ class StatsUtils @Inject constructor(\n val difference = value - previousValue\n val percentage = when (previousValue) {\n value -> \"0\"\n- 0L -> \"\u221e\"\n+ 0L -> percentFormatter.format(value = 100)\n else -> {\n val percentageValue = difference.toFloat() / previousValue\n percentFormatter.format(value = percentageValue, rounding = HALF_UP)\n", "test_patch": "diff --git a/WordPress/src/test/java/org/wordpress/android/ui/stats/refresh/utils/StatsUtilsTest.kt b/WordPress/src/test/java/org/wordpress/android/ui/stats/refresh/utils/StatsUtilsTest.kt\nindex 4367ff9d59ea..c875d6565ecc 100644\n--- a/WordPress/src/test/java/org/wordpress/android/ui/stats/refresh/utils/StatsUtilsTest.kt\n+++ b/WordPress/src/test/java/org/wordpress/android/ui/stats/refresh/utils/StatsUtilsTest.kt\n@@ -278,12 +278,12 @@ class StatsUtilsTest {\n \n @Test\n fun `build change with infinite positive difference`() {\n- whenever(percentFormatter.format(value = 3.0F, rounding = HALF_UP)).thenReturn(\"\u221e\")\n+ whenever(percentFormatter.format(100)).thenReturn(\"100\")\n val previousValue = 0L\n val value = 20L\n val positive = true\n- val expectedChange = \"+20 (\u221e%)\"\n- whenever(resourceProvider.getString(eq(R.string.stats_traffic_increase), eq(\"20\"), eq(\"\u221e\")))\n+ val expectedChange = \"+20 (100%)\"\n+ whenever(resourceProvider.getString(eq(R.string.stats_traffic_increase), eq(\"20\"), eq(\"100\")))\n .thenReturn(expectedChange)\n \n val change = statsUtils.buildChange(previousValue, value, positive, isFormattedNumber = true)\n", "problem_statement": "\"(\u221e)\" shouldn't be used for infinite percentages in stats screens\n### Expected behavior\r\nWhen the percentage is `\u221e` for data in stats screens, we should only show the increase.\r\n\"expected\"\r\n\r\n### Actual behavior\r\nWhen the percentage is `\u221e` for data in stats screens, it shows `(\u221e)`.\r\n\"actual\"\r\n\r\n### Steps to reproduce the behavior\r\n1. Launch the Jetpack app. (WordPress app has the same issue too, but Jetpack has more places showing `(\u221e)`.)\r\n2. Open Stats from \"My Site \u2192 HOME \u2192 Stats\" it \"My Site \u2192 MENU \u2192 Stats\".\r\n3. If the Views & Visitors card is not added to the screen, add it by using \u2699\ufe0f button at the top end of the screen.\r\n4. Find a case which \"Previous Week\" had 0 views, and \"This week\" has more than 0 views.\r\n5. Notice `(\u221e)` is being shown as the percentage.\r\n\r\nThe problem is also on Total Likes card, Total Comments card, and the bar chart on DAYS, WEEKS, MONTHS, YEARS tabs.\r\n\r\n##### Tested on Pixel 4 emulator, Android 11.0, WPAndroid 20.9-rc-2\r\n\n", "hints_text": "", "created_at": "2024-03-31T23:21:56Z", "version": "24.5", "FAIL_TO_PASS": [ "gradle_test_execution" ], "PASS_TO_PASS": [], "ERROR_TO_PASS": [], "environment_setup_commit": "bbe122d406455ce714965776f3dffc6232d39dc5" }, { "repo": "wordpress-mobile/WordPress-Android", "pull_number": 19848, "instance_id": "wordpress-mobile__WordPress-Android-19848", "issue_numbers": [ "19641" ], "base_commit": "70eb2d9f62b6bf2f19a0ced8bcb836c524e6d072", "patch": "diff --git a/WordPress/src/main/java/org/wordpress/android/usecase/social/GetJetpackSocialShareLimitStatusUseCase.kt b/WordPress/src/main/java/org/wordpress/android/usecase/social/GetJetpackSocialShareLimitStatusUseCase.kt\nindex 0aa625beb456..08d0614f7173 100644\n--- a/WordPress/src/main/java/org/wordpress/android/usecase/social/GetJetpackSocialShareLimitStatusUseCase.kt\n+++ b/WordPress/src/main/java/org/wordpress/android/usecase/social/GetJetpackSocialShareLimitStatusUseCase.kt\n@@ -10,9 +10,9 @@ class GetJetpackSocialShareLimitStatusUseCase @Inject constructor(\n private val siteStore: SiteStore,\n ) {\n suspend fun execute(siteModel: SiteModel): ShareLimit {\n- val isShareLimitEnabled =\n- !siteModel.isHostedAtWPCom\n- && (siteModel.planActiveFeatures?.split(\",\")?.doesNotContain(FEATURE_SOCIAL_SHARES_1000) != false)\n+ val isWPComSite = siteModel.isWPCom || siteModel.isWPComAtomic\n+ val isShareLimitEnabled = !isWPComSite &&\n+ (siteModel.planActiveFeatures?.split(\",\")?.doesNotContain(FEATURE_SOCIAL_SHARES_1000) != false)\n val result = siteStore.fetchJetpackSocial(siteModel)\n return if (isShareLimitEnabled && result is FetchedJetpackSocialResult.Success) {\n with(result.jetpackSocial) {\n", "test_patch": "diff --git a/WordPress/src/test/java/org/wordpress/android/usecase/social/GetJetpackSocialShareLimitStatusUseCaseTest.kt b/WordPress/src/test/java/org/wordpress/android/usecase/social/GetJetpackSocialShareLimitStatusUseCaseTest.kt\nindex 82ebe6f684c9..90ac54c08551 100644\n--- a/WordPress/src/test/java/org/wordpress/android/usecase/social/GetJetpackSocialShareLimitStatusUseCaseTest.kt\n+++ b/WordPress/src/test/java/org/wordpress/android/usecase/social/GetJetpackSocialShareLimitStatusUseCaseTest.kt\n@@ -19,10 +19,11 @@ class GetJetpackSocialShareLimitStatusUseCaseTest : BaseUnitTest() {\n )\n \n @Test\n- fun `Should return Disabled if site is not self hosted`() = test {\n+ fun `Should return Disabled if site is hosted at WPCom`() = test {\n val siteModel = SiteModel().apply {\n siteId = 1L\n- setIsJetpackInstalled(false)\n+ setIsWPCom(true)\n+ setIsWPComAtomic(false)\n }\n val expected = ShareLimit.Disabled\n val actual = classToTest.execute(siteModel)\n@@ -30,10 +31,23 @@ class GetJetpackSocialShareLimitStatusUseCaseTest : BaseUnitTest() {\n }\n \n @Test\n- fun `Should return Disabled if site has social-shares-1000 feature active`() = test {\n+ fun `Should return Disabled if site is Atomic`() = test {\n val siteModel = SiteModel().apply {\n siteId = 1L\n- setIsJetpackInstalled(true)\n+ setIsWPCom(false)\n+ setIsWPComAtomic(true)\n+ }\n+ val expected = ShareLimit.Disabled\n+ val actual = classToTest.execute(siteModel)\n+ assertEquals(expected, actual)\n+ }\n+\n+ @Test\n+ fun `Should return Disabled if site is self-hosted AND has social-shares-1000 feature active`() = test {\n+ val siteModel = SiteModel().apply {\n+ siteId = 1L\n+ setIsWPCom(false)\n+ setIsWPComAtomic(false)\n planActiveFeatures = \"social-shares-1000\"\n }\n val expected = ShareLimit.Disabled\n@@ -42,7 +56,7 @@ class GetJetpackSocialShareLimitStatusUseCaseTest : BaseUnitTest() {\n }\n \n @Test\n- fun `Should return Enabled if active features list is null AND is self hosted`() = test {\n+ fun `Should return Enabled if site is self-hosted AND active features list is null`() = test {\n val jetpackSocial = JetpackSocial(\n isShareLimitEnabled = true,\n toBePublicizedCount = 10,\n@@ -55,7 +69,8 @@ class GetJetpackSocialShareLimitStatusUseCaseTest : BaseUnitTest() {\n )\n val siteModel = SiteModel().apply {\n siteId = 1L\n- setIsJetpackInstalled(true)\n+ setIsWPCom(false)\n+ setIsWPComAtomic(false)\n planActiveFeatures = null\n }\n whenever(siteStore.fetchJetpackSocial(siteModel)).thenReturn(FetchedJetpackSocialResult.Success(jetpackSocial))\n@@ -83,7 +98,8 @@ class GetJetpackSocialShareLimitStatusUseCaseTest : BaseUnitTest() {\n )\n val siteModel = SiteModel().apply {\n siteId = 1L\n- setIsJetpackInstalled(true)\n+ setIsWPCom(false)\n+ setIsWPComAtomic(false)\n planActiveFeatures = \"\"\n }\n whenever(siteStore.fetchJetpackSocial(siteModel)).thenReturn(FetchedJetpackSocialResult.Success(jetpackSocial))\n@@ -101,7 +117,8 @@ class GetJetpackSocialShareLimitStatusUseCaseTest : BaseUnitTest() {\n fun `Should return Disabled if fetch site fails`() = test {\n val siteModel = SiteModel().apply {\n siteId = 1L\n- setIsJetpackInstalled(true)\n+ setIsWPCom(false)\n+ setIsWPComAtomic(false)\n planActiveFeatures = \"\"\n }\n whenever(siteStore.fetchJetpackSocial(siteModel)).thenReturn(\n", "problem_statement": "[Jetpack Social] Fix share limits being shown for Atomic sites\nShare limits shouldn't be shown for Atomic sites in the context of Jetpack Social. There are 3 place to double-check using an Atomic site:\r\n\r\n1 - Share limits dashboard card;\r\n2 - Edit post - publish bottom sheet;\r\n3 - Edit post - settings;\r\n\r\nSee p9F6qB-dLk-p2#comment-56603\n", "hints_text": "@RenanLukas Is there a timeline for when this might be fixed that we can share with the user? The ticket is still open and it would be nice if we could give them an update.\n@bobmatyas we're going to have a look this week.", "created_at": "2023-12-22T22:39:35Z", "version": "23.92", "FAIL_TO_PASS": [ "gradle_test_execution" ], "PASS_TO_PASS": [], "ERROR_TO_PASS": [], "environment_setup_commit": "70eb2d9f62b6bf2f19a0ced8bcb836c524e6d072" }, { "repo": "wordpress-mobile/WordPress-Android", "pull_number": 19730, "instance_id": "wordpress-mobile__WordPress-Android-19730", "issue_numbers": [ "19728" ], "base_commit": "afd37fc83bb4a9b7da872e8be4669de73baf858d", "patch": "diff --git a/RELEASE-NOTES.txt b/RELEASE-NOTES.txt\nindex f7ef4c88e694..1d298b006c2f 100644\n--- a/RELEASE-NOTES.txt\n+++ b/RELEASE-NOTES.txt\n@@ -11,6 +11,7 @@\n * [*] Block Editor: In the deeply nested block warning, only display the ungroup option for blocks that support it [https://github.com/WordPress/gutenberg/pull/56445]\n * [**] Enable Optimize Image setting (via Me \u2192 App Settings) by default, and change default compression and resolution values. [https://github.com/wordpress-mobile/WordPress-Android/pull/19581]\n * [*] Fixed an issue that prevented theme installation on atomic sites [https://github.com/wordpress-mobile/WordPress-Android/pull/19668]\n+* [*] Fixed an issue with the pagination of the Blogging Prompts response list [https://github.com/wordpress-mobile/WordPress-Android/pull/19730]\n \n 23.7\n -----\ndiff --git a/WordPress/src/main/java/org/wordpress/android/ui/bloggingprompts/BloggingPromptsPostTagProvider.kt b/WordPress/src/main/java/org/wordpress/android/ui/bloggingprompts/BloggingPromptsPostTagProvider.kt\nindex 0600bbcff449..4aef7e8c43dd 100644\n--- a/WordPress/src/main/java/org/wordpress/android/ui/bloggingprompts/BloggingPromptsPostTagProvider.kt\n+++ b/WordPress/src/main/java/org/wordpress/android/ui/bloggingprompts/BloggingPromptsPostTagProvider.kt\n@@ -2,6 +2,7 @@ package org.wordpress.android.ui.bloggingprompts\n \n import org.wordpress.android.models.ReaderTag\n import org.wordpress.android.models.ReaderTagType\n+import org.wordpress.android.ui.reader.services.post.ReaderPostLogic\n import org.wordpress.android.ui.reader.utils.ReaderUtilsWrapper\n import javax.inject.Inject\n \n@@ -16,10 +17,16 @@ class BloggingPromptsPostTagProvider @Inject constructor(\n \n fun promptIdSearchReaderTag(\n tagUrl: String\n- ): ReaderTag = readerUtilsWrapper.getTagFromTagName(\n- promptIdTag(tagUrl),\n- ReaderTagType.FOLLOWED,\n- )\n+ ): ReaderTag {\n+ val promptIdTag = promptIdTag(tagUrl)\n+ return ReaderTag(\n+ promptIdTag,\n+ promptIdTag,\n+ promptIdTag,\n+ ReaderPostLogic.formatFullEndpointForTag(promptIdTag),\n+ ReaderTagType.FOLLOWED,\n+ )\n+ }\n \n companion object {\n const val BLOGGING_PROMPT_TAG = \"dailyprompt\"\n", "test_patch": "diff --git a/WordPress/src/test/java/org/wordpress/android/ui/bloggingprompts/BloggingPromptsPostTagProviderTest.kt b/WordPress/src/test/java/org/wordpress/android/ui/bloggingprompts/BloggingPromptsPostTagProviderTest.kt\nindex 8c901817c0f7..942681c91225 100644\n--- a/WordPress/src/test/java/org/wordpress/android/ui/bloggingprompts/BloggingPromptsPostTagProviderTest.kt\n+++ b/WordPress/src/test/java/org/wordpress/android/ui/bloggingprompts/BloggingPromptsPostTagProviderTest.kt\n@@ -5,12 +5,12 @@ import org.assertj.core.api.Assertions.assertThat\n import org.junit.Before\n import org.junit.Test\n import org.mockito.Mock\n-import org.mockito.Mockito.mock\n import org.mockito.kotlin.any\n import org.mockito.kotlin.whenever\n import org.wordpress.android.BaseUnitTest\n import org.wordpress.android.models.ReaderTag\n import org.wordpress.android.models.ReaderTagType\n+import org.wordpress.android.ui.reader.services.post.ReaderPostLogic\n import org.wordpress.android.ui.reader.utils.ReaderUtilsWrapper\n import kotlin.test.assertEquals\n \n@@ -23,9 +23,6 @@ class BloggingPromptsPostTagProviderTest : BaseUnitTest() {\n \n @Before\n fun setUp() {\n- whenever(readerUtilsWrapper.getTagFromTagName(BLOGGING_PROMPT_ID_TAG, ReaderTagType.FOLLOWED))\n- .thenReturn(BLOGGING_PROMPT_ID_READER_TAG)\n-\n tagProvider = BloggingPromptsPostTagProvider(readerUtilsWrapper)\n }\n \n@@ -50,14 +47,18 @@ class BloggingPromptsPostTagProviderTest : BaseUnitTest() {\n @Test\n fun `Should return the expected ReaderTag when promptIdSearchReaderTag is called`() {\n whenever(readerUtilsWrapper.getTagFromTagUrl(any())).thenReturn(BLOGGING_PROMPT_ID_TAG)\n-\n+ val expected = ReaderTag(\n+ BLOGGING_PROMPT_ID_TAG,\n+ BLOGGING_PROMPT_ID_TAG,\n+ BLOGGING_PROMPT_ID_TAG,\n+ ReaderPostLogic.formatFullEndpointForTag(BLOGGING_PROMPT_ID_TAG),\n+ ReaderTagType.FOLLOWED,\n+ )\n val actual = tagProvider.promptIdSearchReaderTag(\"valid-url\")\n-\n- assertEquals(BLOGGING_PROMPT_ID_READER_TAG, actual)\n+ assertEquals(expected, actual)\n }\n \n companion object {\n private const val BLOGGING_PROMPT_ID_TAG = \"dailyprompt-1234\"\n- private val BLOGGING_PROMPT_ID_READER_TAG = mock()\n }\n }\n", "problem_statement": "[Prompts] Regression in Prompts responses list pagination\n### Expected behavior\r\nWhen tapping the `View all responses` and scrolling the response list I should be able to get an infinite scroll with proper pagination until I see all responses. New posts are added to the end of the list when loaded. (it was working on version 23.6 and below)\r\n\r\n### Actual behavior\r\nWhen tapping the `View all responses` and scrolling the response list I see the new responses loading once or twice but then no more posts are loaded. Posts shift places when a load happens. (this behavior started on version 23.7)\r\n\r\n### Steps to reproduce the behavior\r\nOn any Jetpack app build of version 23.7 or later do the following:\r\n1. Install and log into the Jetpack app\r\n2. Make sure the `dailyprompt-XXXX` tag for the current day IS NOT FOLLOWED\r\n3. Go to the dashboard\r\n4. Tap `View all responses` on the Prompts card\r\n5. Scroll the prompt tag responses list for a while\r\n6. **Verify** pagination is not working properly (posts are shifting around)\r\n7. **Verify** pagination stops loading new posts at some point\r\n\r\n##### Tested on Emulator, Android 14, JPAndroid 23.7 and later\r\n\n", "hints_text": "", "created_at": "2023-12-04T23:06:37Z", "version": "23.84", "FAIL_TO_PASS": [ "gradle_test_execution" ], "PASS_TO_PASS": [], "ERROR_TO_PASS": [], "environment_setup_commit": "afd37fc83bb4a9b7da872e8be4669de73baf858d" }, { "repo": "wordpress-mobile/WordPress-Android", "pull_number": 21287, "instance_id": "wordpress-mobile__WordPress-Android-21287", "issue_numbers": [ "21283" ], "base_commit": "1281a8b67d76f91ccd54ec23ba30c1fe0951f9b0", "patch": "diff --git a/WordPress/src/main/java/org/wordpress/android/ui/mediapicker/loader/GifMediaDataSource.kt b/WordPress/src/main/java/org/wordpress/android/ui/mediapicker/loader/GifMediaDataSource.kt\nindex f0b31b4027dd..70f76a041e38 100644\n--- a/WordPress/src/main/java/org/wordpress/android/ui/mediapicker/loader/GifMediaDataSource.kt\n+++ b/WordPress/src/main/java/org/wordpress/android/ui/mediapicker/loader/GifMediaDataSource.kt\n@@ -39,8 +39,7 @@ class GifMediaDataSource\n \n if (!networkUtilsWrapper.isNetworkAvailable()) {\n return Failure(\n- UiStringRes(R.string.no_network_title),\n- htmlSubtitle = UiStringRes(R.string.no_network_message),\n+ UiStringRes(R.string.no_network_message),\n image = R.drawable.img_illustration_cloud_off_152dp,\n data = items\n )\ndiff --git a/WordPress/src/main/java/org/wordpress/android/ui/mediapicker/loader/MediaLibraryDataSource.kt b/WordPress/src/main/java/org/wordpress/android/ui/mediapicker/loader/MediaLibraryDataSource.kt\nindex 7009bda1d726..3ce8aa89a617 100644\n--- a/WordPress/src/main/java/org/wordpress/android/ui/mediapicker/loader/MediaLibraryDataSource.kt\n+++ b/WordPress/src/main/java/org/wordpress/android/ui/mediapicker/loader/MediaLibraryDataSource.kt\n@@ -59,8 +59,7 @@ class MediaLibraryDataSource(\n ): MediaLoadingResult {\n if (!networkUtilsWrapper.isNetworkAvailable()) {\n return Failure(\n- UiStringRes(R.string.no_network_title),\n- htmlSubtitle = UiStringRes(R.string.no_network_message),\n+ UiStringRes(R.string.no_network_message),\n image = R.drawable.img_illustration_cloud_off_152dp,\n data = if (loadMore) get(mediaTypes, filter) else listOf()\n )\ndiff --git a/WordPress/src/main/java/org/wordpress/android/ui/mediapicker/loader/StockMediaDataSource.kt b/WordPress/src/main/java/org/wordpress/android/ui/mediapicker/loader/StockMediaDataSource.kt\nindex fae06141a107..da12b4f70c22 100644\n--- a/WordPress/src/main/java/org/wordpress/android/ui/mediapicker/loader/StockMediaDataSource.kt\n+++ b/WordPress/src/main/java/org/wordpress/android/ui/mediapicker/loader/StockMediaDataSource.kt\n@@ -32,8 +32,7 @@ class StockMediaDataSource\n ): MediaLoadingResult {\n if (!networkUtilsWrapper.isNetworkAvailable()) {\n return Failure(\n- UiStringRes(R.string.no_network_title),\n- htmlSubtitle = UiStringRes(R.string.no_network_message),\n+ UiStringRes(R.string.no_network_message),\n image = R.drawable.img_illustration_cloud_off_152dp,\n data = if (loadMore) get() else listOf()\n )\ndiff --git a/WordPress/src/main/java/org/wordpress/android/ui/selfhostedusers/SelfHostedUserComposables.kt b/WordPress/src/main/java/org/wordpress/android/ui/selfhostedusers/SelfHostedUserComposables.kt\nindex 7867ac4059c0..d27ca555ea04 100644\n--- a/WordPress/src/main/java/org/wordpress/android/ui/selfhostedusers/SelfHostedUserComposables.kt\n+++ b/WordPress/src/main/java/org/wordpress/android/ui/selfhostedusers/SelfHostedUserComposables.kt\n@@ -13,9 +13,11 @@ import androidx.compose.foundation.layout.padding\n import androidx.compose.foundation.layout.size\n import androidx.compose.foundation.rememberScrollState\n import androidx.compose.foundation.shape.CircleShape\n+import androidx.compose.foundation.shape.RoundedCornerShape\n import androidx.compose.foundation.verticalScroll\n import androidx.compose.material.icons.Icons\n import androidx.compose.material.icons.filled.Close\n+import androidx.compose.material3.Button\n import androidx.compose.material3.ExperimentalMaterial3Api\n import androidx.compose.material3.Icon\n import androidx.compose.material3.IconButton\n@@ -30,6 +32,7 @@ import androidx.compose.ui.draw.clip\n import androidx.compose.ui.graphics.vector.ImageVector\n import androidx.compose.ui.layout.ContentScale\n import androidx.compose.ui.platform.LocalContext\n+import androidx.compose.ui.res.colorResource\n import androidx.compose.ui.res.stringResource\n import androidx.compose.ui.res.vectorResource\n import androidx.compose.ui.tooling.preview.Preview\n@@ -114,22 +117,26 @@ fun LargeAvatar(avatarUrl: String) {\n * A composable that displays a message when there is no network connection\n */\n @Composable\n-fun OfflineView() {\n+fun OfflineView(\n+ onRetryClick: (() -> Unit)? = null,\n+) {\n MessageView(\n- R.drawable.ic_wifi_off_24px,\n- R.string.no_network_title,\n- R.string.no_network_message,\n+ imageRes = R.drawable.img_illustration_cloud_off_152dp,\n+ messageRes = R.string.no_network_message,\n+ buttonRes = R.string.retry,\n+ onButtonClick = onRetryClick\n )\n }\n \n /**\n- * A composable that displays a title with an icon above it and an optional subtitle below it\n+ * A composable that displays a message with an image above it and an optional button below it\n */\n @Composable\n fun MessageView(\n- @DrawableRes iconRes: Int,\n- @StringRes titleRes: Int,\n- @StringRes subtitleRes: Int? = null,\n+ @DrawableRes imageRes: Int,\n+ @StringRes messageRes: Int,\n+ @StringRes buttonRes: Int? = null,\n+ onButtonClick: (() -> Unit)? = null,\n ) {\n Column(\n modifier = Modifier.fillMaxSize(),\n@@ -137,23 +144,26 @@ fun MessageView(\n horizontalAlignment = Alignment.CenterHorizontally,\n ) {\n Icon(\n- imageVector = ImageVector.vectorResource(iconRes),\n+ imageVector = ImageVector.vectorResource(imageRes),\n+ tint = colorResource(R.color.neutral_30),\n contentDescription = null,\n- tint = MaterialTheme.colorScheme.onSurface,\n- modifier = Modifier\n- .size(85.dp)\n )\n Text(\n- text = stringResource(titleRes),\n+ text = stringResource(messageRes),\n style = MaterialTheme.typography.titleLarge,\n color = MaterialTheme.colorScheme.onSurface,\n+ modifier = Modifier.padding(top = 16.dp),\n )\n- if (subtitleRes != null) {\n- Text(\n- text = stringResource(subtitleRes),\n- style = MaterialTheme.typography.titleSmall,\n- color = MaterialTheme.colorScheme.onSurface,\n- )\n+ if (buttonRes != null && onButtonClick != null) {\n+ Button(\n+ modifier = Modifier.padding(top = 16.dp),\n+ shape = RoundedCornerShape(2.dp),\n+ onClick = onButtonClick,\n+ ) {\n+ Text(\n+ text = stringResource(R.string.retry).uppercase(),\n+ )\n+ }\n }\n }\n }\n@@ -214,12 +224,14 @@ fun ScreenWithTopBar(\n )\n private fun OfflineScreenPreview() {\n val content: @Composable () -> Unit = @Composable {\n- OfflineView()\n+ OfflineView(\n+ onRetryClick = {}\n+ )\n }\n ScreenWithTopBar(\n title = \"Title\",\n content = content,\n onCloseClick = {},\n- isScrollable = false\n+ isScrollable = false,\n )\n }\ndiff --git a/WordPress/src/main/java/org/wordpress/android/ui/selfhostedusers/SelfHostedUsersActivity.kt b/WordPress/src/main/java/org/wordpress/android/ui/selfhostedusers/SelfHostedUsersActivity.kt\nindex 29425a069574..4a625cad5837 100644\n--- a/WordPress/src/main/java/org/wordpress/android/ui/selfhostedusers/SelfHostedUsersActivity.kt\n+++ b/WordPress/src/main/java/org/wordpress/android/ui/selfhostedusers/SelfHostedUsersActivity.kt\n@@ -50,6 +50,9 @@ class SelfHostedUsersActivity : LocaleAwareActivity() {\n },\n onUserAvatarClick = { avatarUrl ->\n viewModel.onUserAvatarClick(avatarUrl)\n+ },\n+ onRetryClick = {\n+ viewModel.onRetryClick()\n }\n )\n }\ndiff --git a/WordPress/src/main/java/org/wordpress/android/ui/selfhostedusers/SelfHostedUsersScreen.kt b/WordPress/src/main/java/org/wordpress/android/ui/selfhostedusers/SelfHostedUsersScreen.kt\nindex 9b252e56865a..14899d75dbc1 100644\n--- a/WordPress/src/main/java/org/wordpress/android/ui/selfhostedusers/SelfHostedUsersScreen.kt\n+++ b/WordPress/src/main/java/org/wordpress/android/ui/selfhostedusers/SelfHostedUsersScreen.kt\n@@ -39,6 +39,7 @@ fun SelfHostedUsersScreen(\n onCloseClick: () -> Unit = {},\n onUserClick: (UserWithEditContext) -> Unit = {},\n onUserAvatarClick: (avatarUrl: String?) -> Unit = {},\n+ onRetryClick: () -> Unit = {},\n ) {\n val state = uiState.collectAsState().value\n \n@@ -89,8 +90,8 @@ fun SelfHostedUsersScreen(\n \n is SelfHostedUserState.EmptyUserList -> {\n MessageView(\n- R.drawable.ic_people_white_24dp,\n- R.string.no_users,\n+ imageRes = R.drawable.ic_people_white_24dp,\n+ messageRes = R.string.no_users,\n )\n }\n \n@@ -106,7 +107,9 @@ fun SelfHostedUsersScreen(\n }\n \n is SelfHostedUserState.Offline -> {\n- OfflineView()\n+ OfflineView(\n+ onRetryClick = onRetryClick\n+ )\n }\n }\n }\ndiff --git a/WordPress/src/main/java/org/wordpress/android/ui/selfhostedusers/SelfHostedUsersViewModel.kt b/WordPress/src/main/java/org/wordpress/android/ui/selfhostedusers/SelfHostedUsersViewModel.kt\nindex b2417f2bd1b6..5036d7241eb8 100644\n--- a/WordPress/src/main/java/org/wordpress/android/ui/selfhostedusers/SelfHostedUsersViewModel.kt\n+++ b/WordPress/src/main/java/org/wordpress/android/ui/selfhostedusers/SelfHostedUsersViewModel.kt\n@@ -87,6 +87,14 @@ class SelfHostedUsersViewModel @Inject constructor(\n }\n }\n \n+ /**\n+ * Called when the retry button is clicked\n+ */\n+ fun onRetryClick() {\n+ _uiState.value = SelfHostedUserState.Loading\n+ fetchUsers()\n+ }\n+\n sealed class SelfHostedUserState {\n data object Loading : SelfHostedUserState()\n data object Offline : SelfHostedUserState()\ndiff --git a/WordPress/src/main/res/layout/actionable_empty_view.xml b/WordPress/src/main/res/layout/actionable_empty_view.xml\nindex df91852324b8..87742ae76478 100644\n--- a/WordPress/src/main/res/layout/actionable_empty_view.xml\n+++ b/WordPress/src/main/res/layout/actionable_empty_view.xml\n@@ -62,7 +62,7 @@\n android:layout_height=\"wrap_content\"\n android:layout_marginTop=\"@dimen/margin_extra_large\"\n android:adjustViewBounds=\"true\"\n- android:contentDescription=\"@string/content_description_person_reading_device_notification\"\n+ android:contentDescription=\"@null\"\n android:visibility=\"gone\" />\n \n \n", "created_at": "2024-10-08T09:59:17Z", "version": "25.41", "FAIL_TO_PASS": [ "gradle_test_execution" ], "PASS_TO_PASS": [], "ERROR_TO_PASS": [], "environment_setup_commit": "1281a8b67d76f91ccd54ec23ba30c1fe0951f9b0" }, { "repo": "wordpress-mobile/WordPress-Android", "pull_number": 19491, "instance_id": "wordpress-mobile__WordPress-Android-19491", "issue_numbers": [ "19344" ], "base_commit": "7512b5117138769a7c83dd3e0929f1a5088bbfcf", "patch": "diff --git a/WordPress/src/main/java/org/wordpress/android/ui/posts/PostActionHandler.kt b/WordPress/src/main/java/org/wordpress/android/ui/posts/PostActionHandler.kt\nindex 79cfcf757fa0..cf0aa6e7cb4a 100644\n--- a/WordPress/src/main/java/org/wordpress/android/ui/posts/PostActionHandler.kt\n+++ b/WordPress/src/main/java/org/wordpress/android/ui/posts/PostActionHandler.kt\n@@ -79,6 +79,7 @@ class PostActionHandler(\n invalidateList.invoke()\n })\n \n+ @Suppress(\"LongMethod\")\n fun handlePostButton(buttonType: PostListButtonType, post: PostModel, hasAutoSave: Boolean) {\n when (buttonType) {\n BUTTON_EDIT -> editPostButtonAction(site, post)\n@@ -134,7 +135,9 @@ class PostActionHandler(\n BUTTON_PROMOTE_WITH_BLAZE -> {\n triggerPostListAction.invoke(PostListAction.ShowPromoteWithBlaze(post))\n }\n- BUTTON_COMMENTS -> {} // todo: implement\n+ BUTTON_COMMENTS -> {\n+ triggerPostListAction.invoke(PostListAction.ShowComments(site, post))\n+ }\n }\n }\n \ndiff --git a/WordPress/src/main/java/org/wordpress/android/ui/posts/PostListAction.kt b/WordPress/src/main/java/org/wordpress/android/ui/posts/PostListAction.kt\nindex 7c3f089ccef0..3a9c7ee10936 100644\n--- a/WordPress/src/main/java/org/wordpress/android/ui/posts/PostListAction.kt\n+++ b/WordPress/src/main/java/org/wordpress/android/ui/posts/PostListAction.kt\n@@ -13,6 +13,8 @@ import org.wordpress.android.ui.pages.SnackbarMessageHolder\n import org.wordpress.android.ui.photopicker.MediaPickerLauncher\n import org.wordpress.android.ui.posts.RemotePreviewLogicHelper.RemotePreviewType\n import org.wordpress.android.ui.prefs.AppPrefs\n+import org.wordpress.android.ui.reader.ReaderActivityLauncher\n+import org.wordpress.android.ui.reader.ReaderPostPagerActivity\n import org.wordpress.android.ui.stories.intro.StoriesIntroDialogFragment\n import org.wordpress.android.ui.uploads.UploadService\n import org.wordpress.android.util.AppLog\n@@ -53,8 +55,8 @@ sealed class PostListAction {\n class ViewStats(val site: SiteModel, val post: PostModel) : PostListAction()\n class ViewPost(val site: SiteModel, val post: PostModel) : PostListAction()\n class DismissPendingNotification(val pushId: Int) : PostListAction()\n-\n class ShowPromoteWithBlaze(val post: PostModel) : PostListAction()\n+ class ShowComments(val site: SiteModel, val post: PostModel) : PostListAction()\n }\n \n @Suppress(\"TooGenericExceptionCaught\", \"LongMethod\", \"ComplexMethod\", \"LongParameterList\")\n@@ -131,5 +133,16 @@ fun handlePostListAction(\n action.showSnackbar.invoke(action.messageError)\n }\n }\n+ is PostListAction.ShowComments -> {\n+ ReaderActivityLauncher.showReaderPostDetail(\n+ activity,\n+ false,\n+ action.site.siteId,\n+ action.post.remotePostId,\n+ ReaderPostPagerActivity.DirectOperation.COMMENT_JUMP,\n+ 0,\n+ false,\n+ null)\n+ }\n }\n }\ndiff --git a/WordPress/src/main/java/org/wordpress/android/viewmodel/posts/PostListItemUiStateHelper.kt b/WordPress/src/main/java/org/wordpress/android/viewmodel/posts/PostListItemUiStateHelper.kt\nindex 915d884477ab..b017797480fa 100644\n--- a/WordPress/src/main/java/org/wordpress/android/viewmodel/posts/PostListItemUiStateHelper.kt\n+++ b/WordPress/src/main/java/org/wordpress/android/viewmodel/posts/PostListItemUiStateHelper.kt\n@@ -47,6 +47,7 @@ import org.wordpress.android.viewmodel.posts.PostListItemType.PostListItemUiStat\n import org.wordpress.android.viewmodel.uistate.ProgressBarUiState\n import org.wordpress.android.widgets.PostListButtonType\n import org.wordpress.android.widgets.PostListButtonType.BUTTON_CANCEL_PENDING_AUTO_UPLOAD\n+import org.wordpress.android.widgets.PostListButtonType.BUTTON_COMMENTS\n import org.wordpress.android.widgets.PostListButtonType.BUTTON_COPY\n import org.wordpress.android.widgets.PostListButtonType.BUTTON_COPY_URL\n import org.wordpress.android.widgets.PostListButtonType.BUTTON_DELETE\n@@ -113,7 +114,6 @@ class PostListItemUiStateHelper @Inject constructor(\n post\n ),\n )\n- // val defaultActions = createDefaultViewActions(buttonTypes, onButtonClicked)\n val moreActions = createMoreActions(buttonTypes, onButtonClicked)\n \n val remotePostId = RemotePostId(RemoteId(post.remotePostId))\n@@ -459,6 +459,8 @@ class PostListItemUiStateHelper @Inject constructor(\n \n buttonTypes.addDeletingOrTrashAction(isLocalDraft, postStatus)\n \n+ buttonTypes.addCommentActionIfNeeded(postStatus)\n+\n return sortPostListButtons(buttonTypes)\n }\n \n@@ -492,6 +494,12 @@ class PostListItemUiStateHelper @Inject constructor(\n }\n }\n \n+ private fun MutableList.addCommentActionIfNeeded(postStatus: PostStatus) {\n+ if (postStatus == PUBLISHED) {\n+ add(BUTTON_COMMENTS)\n+ }\n+ }\n+\n private fun createMoreActions(\n buttonTypes: List,\n onButtonClicked: (PostListButtonType) -> Unit\n", "test_patch": "diff --git a/WordPress/src/test/java/org/wordpress/android/viewmodel/posts/PostListItemUiStateHelperTest.kt b/WordPress/src/test/java/org/wordpress/android/viewmodel/posts/PostListItemUiStateHelperTest.kt\nindex d8f6bd64dfbb..f0fb1c926fa3 100644\n--- a/WordPress/src/test/java/org/wordpress/android/viewmodel/posts/PostListItemUiStateHelperTest.kt\n+++ b/WordPress/src/test/java/org/wordpress/android/viewmodel/posts/PostListItemUiStateHelperTest.kt\n@@ -224,8 +224,9 @@ class PostListItemUiStateHelperTest {\n assertThat(moreActions[2].buttonType).isEqualTo(PostListButtonType.BUTTON_COPY)\n assertThat(moreActions[3].buttonType).isEqualTo(PostListButtonType.BUTTON_COPY_URL)\n assertThat(moreActions[4].buttonType).isEqualTo(PostListButtonType.BUTTON_STATS)\n- assertThat(moreActions[5].buttonType).isEqualTo(PostListButtonType.BUTTON_TRASH)\n- assertThat(moreActions).hasSize(6)\n+ assertThat(moreActions[5].buttonType).isEqualTo(PostListButtonType.BUTTON_COMMENTS)\n+ assertThat(moreActions[6].buttonType).isEqualTo(PostListButtonType.BUTTON_TRASH)\n+ assertThat(moreActions).hasSize(7)\n }\n \n @Test\n@@ -240,8 +241,9 @@ class PostListItemUiStateHelperTest {\n assertThat(moreActions[1].buttonType).isEqualTo(PostListButtonType.BUTTON_MOVE_TO_DRAFT)\n assertThat(moreActions[2].buttonType).isEqualTo(PostListButtonType.BUTTON_COPY)\n assertThat(moreActions[3].buttonType).isEqualTo(PostListButtonType.BUTTON_COPY_URL)\n- assertThat(moreActions[4].buttonType).isEqualTo(PostListButtonType.BUTTON_TRASH)\n- assertThat(moreActions).hasSize(5)\n+ assertThat(moreActions[4].buttonType).isEqualTo(PostListButtonType.BUTTON_COMMENTS)\n+ assertThat(moreActions[5].buttonType).isEqualTo(PostListButtonType.BUTTON_TRASH)\n+ assertThat(moreActions).hasSize(6)\n }\n \n @Test\n@@ -257,8 +259,9 @@ class PostListItemUiStateHelperTest {\n assertThat(moreActions[2].buttonType).isEqualTo(PostListButtonType.BUTTON_COPY)\n assertThat(moreActions[3].buttonType).isEqualTo(PostListButtonType.BUTTON_COPY_URL)\n assertThat(moreActions[4].buttonType).isEqualTo(PostListButtonType.BUTTON_STATS)\n- assertThat(moreActions[5].buttonType).isEqualTo(PostListButtonType.BUTTON_TRASH)\n- assertThat(moreActions).hasSize(6)\n+ assertThat(moreActions[5].buttonType).isEqualTo(PostListButtonType.BUTTON_COMMENTS)\n+ assertThat(moreActions[6].buttonType).isEqualTo(PostListButtonType.BUTTON_TRASH)\n+ assertThat(moreActions).hasSize(7)\n }\n \n @Test\n@@ -273,8 +276,9 @@ class PostListItemUiStateHelperTest {\n assertThat(moreActions[1].buttonType).isEqualTo(PostListButtonType.BUTTON_MOVE_TO_DRAFT)\n assertThat(moreActions[2].buttonType).isEqualTo(PostListButtonType.BUTTON_COPY)\n assertThat(moreActions[3].buttonType).isEqualTo(PostListButtonType.BUTTON_COPY_URL)\n- assertThat(moreActions[4].buttonType).isEqualTo(PostListButtonType.BUTTON_TRASH)\n- assertThat(moreActions).hasSize(5)\n+ assertThat(moreActions[4].buttonType).isEqualTo(PostListButtonType.BUTTON_COMMENTS)\n+ assertThat(moreActions[5].buttonType).isEqualTo(PostListButtonType.BUTTON_TRASH)\n+ assertThat(moreActions).hasSize(6)\n }\n \n @Test\n@@ -289,8 +293,9 @@ class PostListItemUiStateHelperTest {\n assertThat(moreActions[2].buttonType).isEqualTo(PostListButtonType.BUTTON_MOVE_TO_DRAFT)\n assertThat(moreActions[3].buttonType).isEqualTo(PostListButtonType.BUTTON_COPY)\n assertThat(moreActions[4].buttonType).isEqualTo(PostListButtonType.BUTTON_COPY_URL)\n- assertThat(moreActions[5].buttonType).isEqualTo(PostListButtonType.BUTTON_TRASH)\n- assertThat(moreActions).hasSize(6)\n+ assertThat(moreActions[5].buttonType).isEqualTo(PostListButtonType.BUTTON_COMMENTS)\n+ assertThat(moreActions[6].buttonType).isEqualTo(PostListButtonType.BUTTON_TRASH)\n+ assertThat(moreActions).hasSize(7)\n }\n \n @Test\n@@ -307,8 +312,9 @@ class PostListItemUiStateHelperTest {\n assertThat(moreActions[1].buttonType).isEqualTo(PostListButtonType.BUTTON_MOVE_TO_DRAFT)\n assertThat(moreActions[2].buttonType).isEqualTo(PostListButtonType.BUTTON_COPY)\n assertThat(moreActions[3].buttonType).isEqualTo(PostListButtonType.BUTTON_COPY_URL)\n- assertThat(moreActions[4].buttonType).isEqualTo(PostListButtonType.BUTTON_TRASH)\n- assertThat(moreActions).hasSize(5)\n+ assertThat(moreActions[4].buttonType).isEqualTo(PostListButtonType.BUTTON_COMMENTS)\n+ assertThat(moreActions[5].buttonType).isEqualTo(PostListButtonType.BUTTON_TRASH)\n+ assertThat(moreActions).hasSize(6)\n }\n \n @Test\n@@ -407,8 +413,9 @@ class PostListItemUiStateHelperTest {\n assertThat(moreActions[2].buttonType).isEqualTo(PostListButtonType.BUTTON_MOVE_TO_DRAFT)\n assertThat(moreActions[3].buttonType).isEqualTo(PostListButtonType.BUTTON_COPY)\n assertThat(moreActions[4].buttonType).isEqualTo(PostListButtonType.BUTTON_COPY_URL)\n- assertThat(moreActions[5].buttonType).isEqualTo(PostListButtonType.BUTTON_TRASH)\n- assertThat(moreActions).hasSize(6)\n+ assertThat(moreActions[5].buttonType).isEqualTo(PostListButtonType.BUTTON_COMMENTS)\n+ assertThat(moreActions[6].buttonType).isEqualTo(PostListButtonType.BUTTON_TRASH)\n+ assertThat(moreActions).hasSize(7)\n }\n \n @Test\n@@ -487,8 +494,9 @@ class PostListItemUiStateHelperTest {\n assertThat(moreActions[2].buttonType).isEqualTo(PostListButtonType.BUTTON_MOVE_TO_DRAFT)\n assertThat(moreActions[3].buttonType).isEqualTo(PostListButtonType.BUTTON_COPY)\n assertThat(moreActions[4].buttonType).isEqualTo(PostListButtonType.BUTTON_COPY_URL)\n- assertThat(moreActions[5].buttonType).isEqualTo(PostListButtonType.BUTTON_TRASH)\n- assertThat(moreActions).hasSize(6)\n+ assertThat(moreActions[5].buttonType).isEqualTo(PostListButtonType.BUTTON_COMMENTS)\n+ assertThat(moreActions[6].buttonType).isEqualTo(PostListButtonType.BUTTON_TRASH)\n+ assertThat(moreActions).hasSize(7)\n }\n \n @Test\n@@ -824,8 +832,9 @@ class PostListItemUiStateHelperTest {\n assertThat(moreActions[0].buttonType).isEqualTo(PostListButtonType.BUTTON_RETRY)\n assertThat(moreActions[1].buttonType).isEqualTo(PostListButtonType.BUTTON_MOVE_TO_DRAFT)\n assertThat(moreActions[2].buttonType).isEqualTo(PostListButtonType.BUTTON_COPY)\n- assertThat(moreActions[3].buttonType).isEqualTo(PostListButtonType.BUTTON_DELETE)\n- assertThat(moreActions).hasSize(4)\n+ assertThat(moreActions[3].buttonType).isEqualTo(PostListButtonType.BUTTON_COMMENTS)\n+ assertThat(moreActions[4].buttonType).isEqualTo(PostListButtonType.BUTTON_DELETE)\n+ assertThat(moreActions).hasSize(5)\n }\n \n @Test\n", "problem_statement": "UI Modernization Posts: Implement \"comments\" option tap\nFigma Design eYeHXEMDbnFptE40xUqZ2T-fi-836_5909\r\n```[tasklist]\n### Tasks\n- [x] Apply logic to launch directly into post comments on tap\n```\r\n\n", "hints_text": "", "created_at": "2023-10-31T18:58:03Z", "version": "23.5", "FAIL_TO_PASS": [ "gradle_test_execution" ], "PASS_TO_PASS": [], "ERROR_TO_PASS": [], "environment_setup_commit": "843bb9325e868c5a18177ff203ed9a3f08cd8daa" }, { "repo": "ankidroid/Anki-Android", "pull_number": 15871, "instance_id": "ankidroid__Anki-Android-15871", "issue_numbers": [ "15863" ], "base_commit": "bbfd8f4a10c796d4b955d54530c7f11e81ca250d", "patch": "diff --git a/AnkiDroid/src/main/java/com/ichi2/anki/AbstractFlashcardViewer.kt b/AnkiDroid/src/main/java/com/ichi2/anki/AbstractFlashcardViewer.kt\nindex 61c9f6f9e1f0..1833f97897a1 100644\n--- a/AnkiDroid/src/main/java/com/ichi2/anki/AbstractFlashcardViewer.kt\n+++ b/AnkiDroid/src/main/java/com/ichi2/anki/AbstractFlashcardViewer.kt\n@@ -49,7 +49,6 @@ import androidx.core.view.WindowInsetsControllerCompat\n import androidx.core.view.children\n import androidx.core.view.isVisible\n import androidx.lifecycle.Lifecycle.State.RESUMED\n-import androidx.webkit.WebViewAssetLoader\n import anki.collection.OpChanges\n import com.drakeet.drawer.FullDraggableContainer\n import com.google.android.material.snackbar.Snackbar\n@@ -996,7 +995,7 @@ abstract class AbstractFlashcardViewer :\n }\n \n protected open fun createWebView(): WebView {\n- val assetLoader = getViewerAssetLoader(webviewDomain)\n+ val resourceHandler = ViewerResourceHandler(this, webviewDomain)\n val webView: WebView = MyWebView(this).apply {\n scrollBarStyle = View.SCROLLBARS_OUTSIDE_OVERLAY\n with(settings) {\n@@ -1014,7 +1013,7 @@ abstract class AbstractFlashcardViewer :\n isScrollbarFadingEnabled = true\n // Set transparent color to prevent flashing white when night mode enabled\n setBackgroundColor(Color.argb(1, 0, 0, 0))\n- CardViewerWebClient(assetLoader, this@AbstractFlashcardViewer).apply {\n+ CardViewerWebClient(resourceHandler, this@AbstractFlashcardViewer).apply {\n webViewClient = this\n this@AbstractFlashcardViewer.webViewClient = this\n }\n@@ -2239,7 +2238,7 @@ abstract class AbstractFlashcardViewer :\n }\n \n protected inner class CardViewerWebClient internal constructor(\n- private val loader: WebViewAssetLoader?,\n+ private val loader: ViewerResourceHandler?,\n private val onPageFinishedCallback: OnPageFinishedCallback? = null\n ) : WebViewClient() {\n private var pageFinishedFired = true\n@@ -2261,9 +2260,7 @@ abstract class AbstractFlashcardViewer :\n request: WebResourceRequest\n ): WebResourceResponse? {\n val url = request.url\n- if (request.method == \"GET\") {\n- loader!!.shouldInterceptRequest(url)?.let { return it }\n- }\n+ loader!!.shouldInterceptRequest(request)?.let { return it }\n if (url.toString().startsWith(\"file://\")) {\n url.path?.let { path -> migrationService?.migrateFileImmediately(File(path)) }\n }\ndiff --git a/AnkiDroid/src/main/java/com/ichi2/anki/ViewerAssetLoader.kt b/AnkiDroid/src/main/java/com/ichi2/anki/ViewerAssetLoader.kt\ndeleted file mode 100644\nindex c97e57f56cdf..000000000000\n--- a/AnkiDroid/src/main/java/com/ichi2/anki/ViewerAssetLoader.kt\n+++ /dev/null\n@@ -1,46 +0,0 @@\n-/*\n- * Copyright (c) 2023 Brayan Oliveira \n- *\n- * This program is free software; you can redistribute it and/or modify it under\n- * the terms of the GNU General Public License as published by the Free Software\n- * Foundation; either version 3 of the License, or (at your option) any later\n- * version.\n- *\n- * This program is distributed in the hope that it will be useful, but WITHOUT ANY\n- * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A\n- * PARTICULAR PURPOSE. See the GNU General Public License for more details.\n- *\n- * You should have received a copy of the GNU General Public License along with\n- * this program. If not, see .\n- */\n-package com.ichi2.anki\n-\n-import android.content.Context\n-import android.webkit.WebResourceResponse\n-import androidx.webkit.WebViewAssetLoader\n-import com.ichi2.utils.AssetHelper.guessMimeType\n-import timber.log.Timber\n-import java.io.ByteArrayInputStream\n-import java.io.File\n-import java.io.FileInputStream\n-\n-fun Context.getViewerAssetLoader(domain: String): WebViewAssetLoader {\n- val mediaDir = CollectionHelper.getMediaDirectory(this)\n- return WebViewAssetLoader.Builder()\n- .setHttpAllowed(true)\n- .setDomain(domain)\n- .addPathHandler(\"/\") { path: String ->\n- if (path == \"favicon.ico\") {\n- return@addPathHandler WebResourceResponse(null, null, ByteArrayInputStream(ByteArray(0)))\n- }\n- try {\n- val file = File(mediaDir, path)\n- val inputStream = FileInputStream(file)\n- WebResourceResponse(guessMimeType(path), null, inputStream)\n- } catch (e: Exception) {\n- Timber.d(\"File not found: %s\", path)\n- null\n- }\n- }\n- .build()\n-}\ndiff --git a/AnkiDroid/src/main/java/com/ichi2/anki/ViewerResourceHandler.kt b/AnkiDroid/src/main/java/com/ichi2/anki/ViewerResourceHandler.kt\nnew file mode 100644\nindex 000000000000..378802bc6d73\n--- /dev/null\n+++ b/AnkiDroid/src/main/java/com/ichi2/anki/ViewerResourceHandler.kt\n@@ -0,0 +1,109 @@\n+/*\n+ * Copyright (c) 2023 Brayan Oliveira \n+ * Copyright (c) 2023 David Allison \n+ *\n+ * This program is free software; you can redistribute it and/or modify it under\n+ * the terms of the GNU General Public License as published by the Free Software\n+ * Foundation; either version 3 of the License, or (at your option) any later\n+ * version.\n+ *\n+ * This program is distributed in the hope that it will be useful, but WITHOUT ANY\n+ * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A\n+ * PARTICULAR PURPOSE. See the GNU General Public License for more details.\n+ *\n+ * You should have received a copy of the GNU General Public License along with\n+ * this program. If not, see .\n+ */\n+package com.ichi2.anki\n+\n+import android.content.Context\n+import android.webkit.WebResourceRequest\n+import android.webkit.WebResourceResponse\n+import com.ichi2.utils.AssetHelper.guessMimeType\n+import timber.log.Timber\n+import java.io.ByteArrayInputStream\n+import java.io.File\n+import java.io.FileInputStream\n+import java.io.InputStream\n+import java.io.RandomAccessFile\n+import java.nio.channels.Channels\n+\n+private const val RANGE_HEADER = \"Range\"\n+\n+/**\n+ * @param authority the authority of the WebView Url, e.g. `127.0.0.1:40001`.\n+ */\n+class ViewerResourceHandler(context: Context, private val authority: String) {\n+ private val mediaDir = CollectionHelper.getMediaDirectory(context)\n+\n+ fun shouldInterceptRequest(request: WebResourceRequest): WebResourceResponse? {\n+ val url = request.url\n+ val path = url.path\n+\n+ if (request.method != \"GET\" || path == null || url.authority != authority) {\n+ return null\n+ }\n+ if (path == \"/favicon.ico\") {\n+ return WebResourceResponse(null, null, ByteArrayInputStream(ByteArray(0)))\n+ }\n+\n+ try {\n+ val file = File(mediaDir, path)\n+ if (!file.exists()) {\n+ return null\n+ }\n+ request.requestHeaders[RANGE_HEADER]?.let { range ->\n+ return handlePartialContent(file, range)\n+ }\n+ val inputStream = FileInputStream(file)\n+ return WebResourceResponse(guessMimeType(path), null, inputStream)\n+ } catch (e: Exception) {\n+ Timber.d(\"File not found\")\n+ return null\n+ }\n+ }\n+\n+ private fun handlePartialContent(file: File, range: String): WebResourceResponse {\n+ val rangeHeader = RangeHeader.from(range, defaultEnd = file.length() - 1)\n+\n+ val mimeType = guessMimeType(file.path)\n+ val inputStream = file.toInputStream(rangeHeader)\n+ val (start, end) = rangeHeader\n+ val responseHeaders = mapOf(\n+ \"Content-Range\" to \"bytes $start-$end/${file.length()}\",\n+ \"Accept-Range\" to \"bytes\"\n+ )\n+ return WebResourceResponse(\n+ mimeType,\n+ null,\n+ 206,\n+ \"Partial Content\",\n+ responseHeaders,\n+ inputStream\n+ )\n+ }\n+}\n+\n+/**\n+ * Handles the \"range\" header in a HTTP Request\n+ */\n+data class RangeHeader(val start: Long, val end: Long) {\n+ companion object {\n+ fun from(range: String, defaultEnd: Long): RangeHeader {\n+ val numbers = range.substring(\"bytes=\".length).split('-')\n+ val unspecifiedEnd = numbers.getOrNull(1).isNullOrEmpty()\n+ return RangeHeader(\n+ start = numbers[0].toLong(),\n+ end = if (unspecifiedEnd) defaultEnd else numbers[1].toLong()\n+ )\n+ }\n+ }\n+}\n+\n+fun File.toInputStream(header: RangeHeader): InputStream {\n+ // PERF: Test to see if a custom FileInputStream + available() would be faster\n+ val randomAccessFile = RandomAccessFile(this, \"r\")\n+ return Channels.newInputStream(randomAccessFile.channel).also {\n+ it.skip(header.start)\n+ }\n+}\ndiff --git a/AnkiDroid/src/main/java/com/ichi2/anki/pages/RangeHeader.kt b/AnkiDroid/src/main/java/com/ichi2/anki/pages/RangeHeader.kt\ndeleted file mode 100644\nindex d614dad4514c..000000000000\n--- a/AnkiDroid/src/main/java/com/ichi2/anki/pages/RangeHeader.kt\n+++ /dev/null\n@@ -1,50 +0,0 @@\n-/*\n- * Copyright (c) 2023 David Allison \n- *\n- * This program is free software; you can redistribute it and/or modify it under\n- * the terms of the GNU General Public License as published by the Free Software\n- * Foundation; either version 3 of the License, or (at your option) any later\n- * version.\n- *\n- * This program is distributed in the hope that it will be useful, but WITHOUT ANY\n- * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A\n- * PARTICULAR PURPOSE. See the GNU General Public License for more details.\n- *\n- * You should have received a copy of the GNU General Public License along with\n- * this program. If not, see .\n- */\n-\n-package com.ichi2.anki.pages\n-\n-import fi.iki.elonen.NanoHTTPD.IHTTPSession\n-import java.io.File\n-import java.io.InputStream\n-import java.io.RandomAccessFile\n-import java.nio.channels.Channels\n-\n-/**\n- * Handles the \"range\" header in a HTTP Request\n- */\n-data class RangeHeader(val start: Long, val end: Long) {\n- val contentLength: Long get() = end - start + 1\n-\n- companion object {\n- fun from(session: IHTTPSession, defaultEnd: Long): RangeHeader? {\n- val range = session.headers[\"range\"]?.trim() ?: return null\n- val numbers = range.substring(\"bytes=\".length).split('-')\n- val unspecifiedEnd = numbers.getOrNull(1).isNullOrEmpty()\n- return RangeHeader(\n- start = numbers[0].toLong(),\n- end = if (unspecifiedEnd) defaultEnd else numbers[1].toLong()\n- )\n- }\n- }\n-}\n-\n-fun File.toInputStream(header: RangeHeader): InputStream {\n- // PERF: Test to see if a custom FileInputStream + available() would be faster\n- val randomAccessFile = RandomAccessFile(this, \"r\")\n- return Channels.newInputStream(randomAccessFile.channel).also {\n- it.skip(header.start)\n- }\n-}\ndiff --git a/AnkiDroid/src/main/java/com/ichi2/anki/previewer/CardViewerFragment.kt b/AnkiDroid/src/main/java/com/ichi2/anki/previewer/CardViewerFragment.kt\nindex 0dd7b491c418..c021e5a91203 100644\n--- a/AnkiDroid/src/main/java/com/ichi2/anki/previewer/CardViewerFragment.kt\n+++ b/AnkiDroid/src/main/java/com/ichi2/anki/previewer/CardViewerFragment.kt\n@@ -36,8 +36,8 @@ import androidx.fragment.app.Fragment\n import androidx.lifecycle.flowWithLifecycle\n import androidx.lifecycle.lifecycleScope\n import com.ichi2.anki.R\n+import com.ichi2.anki.ViewerResourceHandler\n import com.ichi2.anki.dialogs.TtsVoicesDialogFragment\n-import com.ichi2.anki.getViewerAssetLoader\n import com.ichi2.anki.localizedErrorMessage\n import com.ichi2.anki.pages.AnkiServer\n import com.ichi2.anki.snackbar.showSnackbar\n@@ -119,13 +119,13 @@ abstract class CardViewerFragment(@LayoutRes layout: Int) : Fragment(layout) {\n }\n \n private fun onCreateWebViewClient(savedInstanceState: Bundle?): WebViewClient {\n- val assetLoader = requireContext().getViewerAssetLoader(AnkiServer.LOCALHOST)\n+ val resourceHandler = ViewerResourceHandler(requireContext(), AnkiServer.LOCALHOST)\n return object : WebViewClient() {\n override fun shouldInterceptRequest(\n view: WebView?,\n request: WebResourceRequest\n ): WebResourceResponse? {\n- return assetLoader.shouldInterceptRequest(request.url)\n+ return resourceHandler.shouldInterceptRequest(request)\n }\n \n override fun onPageFinished(view: WebView?, url: String?) {\ndiff --git a/AnkiDroid/src/main/java/com/ichi2/libanki/TemplateManager.kt b/AnkiDroid/src/main/java/com/ichi2/libanki/TemplateManager.kt\nindex 7e4ff839706f..8b8853e6ad2f 100644\n--- a/AnkiDroid/src/main/java/com/ichi2/libanki/TemplateManager.kt\n+++ b/AnkiDroid/src/main/java/com/ichi2/libanki/TemplateManager.kt\n@@ -329,7 +329,7 @@ fun parseVideos(text: String, mediaDir: String): String {\n }\n \n /**\n- * Parses the sources of the ``, `