From 3b63ab3493b99c93903b22cd1a6b90d68b9926bb Mon Sep 17 00:00:00 2001 From: Daniel Alome Date: Tue, 15 Sep 2026 23:40:27 +0100 Subject: [PATCH 01/11] style: spotless reformat LspThreadInfo, no functional change Editing the file for ADFA-4191 pulls it under the Spotless ratchet. --- .../lsp/java/debug/LspThreadInfo.kt | 39 +++++++++++-------- 1 file changed, 22 insertions(+), 17 deletions(-) diff --git a/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/debug/LspThreadInfo.kt b/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/debug/LspThreadInfo.kt index 6e14adad46..f93809fbf4 100644 --- a/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/debug/LspThreadInfo.kt +++ b/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/debug/LspThreadInfo.kt @@ -68,24 +68,27 @@ class JavaStackFrame( }?.run { val variables = mutableListOf>() - val thisObject = runCatching { - this.thisObject() - }.getOrElse { e -> - when (e) { - is VMDisconnectedException -> { - logger.warn("VM disconnected while fetching 'this' object.", e) - return@evaluate emptyList() - } - is ObjectCollectedException -> { - logger.warn("Object collected by GC during debug", e) - null - } - else -> { - logger.error("Unexpected error fetching thisObject", e) - null + val thisObject = + runCatching { + this.thisObject() + }.getOrElse { e -> + when (e) { + is VMDisconnectedException -> { + logger.warn("VM disconnected while fetching 'this' object.", e) + return@evaluate emptyList() + } + + is ObjectCollectedException -> { + logger.warn("Object collected by GC during debug", e) + null + } + + else -> { + logger.error("Unexpected error fetching thisObject", e) + null + } } } - } if (thisObject != null) { variables.add( ThisVariable( @@ -164,7 +167,9 @@ class JavaStackFrame( } // TODO: Support other types of variable values - else -> throw IllegalStateException("Unsupported variable kind: ${variable.kind}") + else -> { + throw IllegalStateException("Unsupported variable kind: ${variable.kind}") + } } } } From 74e2d3c2b82b252fc3f754642109308e91dd5354 Mon Sep 17 00:00:00 2001 From: Daniel Alome Date: Tue, 15 Sep 2026 23:45:15 +0100 Subject: [PATCH 02/11] feat: make stepping and the variables list usable for Kotlin Stepping excluded only the Java runtime, so a step over an ordinary Kotlin line stopped inside Intrinsics on a null check and inside the stdlib on most calls. The Kotlin runtime packages are excluded too now. An inline lambda body compiles into the caller's class, so this does not stop a user stepping into their own lambda. An inline function's body also compiles into the caller, and line stepping walked through it one synthetic line at a time. Kotlin marks those regions with a $i$f$ local, so a step that lands in one now continues until it leaves, bounded so a step can never hang. The variables list showed the compiler's own locals: inline markers and the suspend state machine. Those are hidden. An inline lambda receiver is kept and shown as this@label, since it is the user's receiver rather than noise. Two locations still read the VM default stratum, which ADFA-4190 should have caught: the call stack's source name and line. They report the wrong file for an inlined frame, which is reachable now that stepping enters one. testing/resources/kotlin-debug-fixture carries the debuggee QA works from. It is a source file rather than a project because the Kotlin template already produces one, so QA exercises the path a user takes. --- .../lsp/java/debug/JavaDebugAdapter.kt | 66 ++++++++++++++++ .../lsp/java/debug/LspThreadInfo.kt | 11 ++- .../androidide/lsp/java/debug/Variables.kt | 5 +- .../lsp/java/debug/utils/KotlinLocals.kt | 25 ++++++ .../lsp/java/debug/utils/ModelUtils.kt | 3 +- .../lsp/java/debug/KotlinLocalsTest.kt | 77 +++++++++++++++++++ .../kotlin-debug-fixture/DebugFixture.kt | 58 ++++++++++++++ .../resources/kotlin-debug-fixture/README.md | 42 ++++++++++ 8 files changed, 282 insertions(+), 5 deletions(-) create mode 100644 lsp/java/src/main/java/com/itsaky/androidide/lsp/java/debug/utils/KotlinLocals.kt create mode 100644 lsp/java/src/test/java/com/itsaky/androidide/lsp/java/debug/KotlinLocalsTest.kt create mode 100644 testing/resources/kotlin-debug-fixture/DebugFixture.kt create mode 100644 testing/resources/kotlin-debug-fixture/README.md diff --git a/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/debug/JavaDebugAdapter.kt b/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/debug/JavaDebugAdapter.kt index c9fb79a128..46ba95a17b 100644 --- a/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/debug/JavaDebugAdapter.kt +++ b/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/debug/JavaDebugAdapter.kt @@ -28,12 +28,15 @@ import com.itsaky.androidide.lsp.java.debug.spec.BreakpointSpec import com.itsaky.androidide.lsp.java.debug.utils.asDepthInt import com.itsaky.androidide.lsp.java.debug.utils.asJdiInt import com.itsaky.androidide.lsp.java.debug.utils.asLspLocation +import com.itsaky.androidide.lsp.java.debug.utils.isInlinedRegion import com.itsaky.androidide.lsp.java.debug.utils.isKotlinSource import com.itsaky.androidide.lsp.java.debug.utils.kotlinBinaryNamesOf import com.itsaky.androidide.projects.ProjectManagerImpl import com.itsaky.androidide.projects.api.ModuleProject import com.itsaky.androidide.utils.withStopWatch +import com.sun.jdi.AbsentInformationException import com.sun.jdi.Bootstrap +import com.sun.jdi.IncompatibleThreadStateException import com.sun.jdi.ThreadReference import com.sun.jdi.VMDisconnectedException import com.sun.jdi.VirtualMachine @@ -69,6 +72,7 @@ internal class JavaDebugAdapter : private var listenerThread: JDWPListenerThread? = null private var _listenerState: ListenerState? = null + private var inlineStepCount = 0 val listenerState: ListenerState get() = @@ -89,8 +93,12 @@ internal class JavaDebugAdapter : "jdk.*", "com.sun.*", "sun.*", + "kotlin.*", + "kotlinx.*", ) + private const val MAX_INLINE_STEPS = 64 + /** * Get the current instance of the [JavaDebugAdapter]. */ @@ -449,6 +457,7 @@ internal class JavaDebugAdapter : logger.debug("Step {} thread {}", request.type, suspendedThread.thread.name()) clearPreviousStep(vm.vm, suspendedThread.thread) + inlineStepCount = 0 val reqMgr = vm.vm.eventRequestManager() val req = @@ -515,6 +524,57 @@ internal class JavaDebugAdapter : } } + private fun resumeStepThroughInlinedBody( + vm: VmConnection, + e: StepEvent, + thread: ThreadReference, + ): Boolean { + val request = e.request() as? StepRequest ?: return false + + if (request.depth() == StepRequest.STEP_INTO) { + return false + } + + val visibleLocalNames = + try { + thread.frame(0).visibleVariables().map { it.name() } + } catch (err: AbsentInformationException) { + return false + } catch (err: IncompatibleThreadStateException) { + return false + } + + if (!isInlinedRegion(visibleLocalNames)) { + return false + } + + if (++inlineStepCount > MAX_INLINE_STEPS) { + logger.warn( + "Still inside an inlined body after {} steps, reporting current location", + MAX_INLINE_STEPS, + ) + return false + } + + clearPreviousStep(vm.vm, thread) + + val req = + vm.vm.eventRequestManager().createStepRequest( + thread, + StepRequest.STEP_LINE, + request.depth(), + ) + for (pattern in DEFAULT_CLASS_EXCLUSION_FILTERS) { + req.addClassExclusionFilter(pattern) + } + req.setSuspendPolicy(EventRequest.SUSPEND_ALL) + req.addCountFilter(1) + req.enable() + thread.resume() + vm.threadState.invalidateAll() + return true + } + private fun clearPreviousStep( vm: VirtualMachine, thread: ThreadReference, @@ -560,6 +620,12 @@ internal class JavaDebugAdapter : val location = e.location() val thread = e.thread() + if (resumeStepThroughInlinedBody(vm, e, thread)) { + return + } + + inlineStepCount = 0 + listenerState.client.onStep( event = LspStepEvent( diff --git a/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/debug/LspThreadInfo.kt b/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/debug/LspThreadInfo.kt index f93809fbf4..ab091b954a 100644 --- a/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/debug/LspThreadInfo.kt +++ b/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/debug/LspThreadInfo.kt @@ -9,6 +9,9 @@ import com.itsaky.androidide.lsp.debug.model.Value import com.itsaky.androidide.lsp.debug.model.Variable import com.itsaky.androidide.lsp.debug.model.VariableKind import com.itsaky.androidide.lsp.java.debug.utils.isOpaque +import com.itsaky.androidide.lsp.java.debug.utils.isSyntheticKotlinLocal +import com.itsaky.androidide.lsp.java.debug.utils.lineNumberInSource +import com.itsaky.androidide.lsp.java.debug.utils.sourceNameOrNull import com.sun.jdi.Location import com.sun.jdi.Method import com.sun.jdi.ObjectCollectedException @@ -28,8 +31,8 @@ class JavaStackFrame( val frame: StackFrame, val location: Location = frame.location(), val method: Method? = location.method(), - val sourceName: String = location.sourceName(), - val lineNumber: Long = location.lineNumber().toLong(), + val sourceName: String = location.sourceNameOrNull() ?: "", + val lineNumber: Long = location.lineNumberInSource().toLong(), ) : LspStackFrame { companion object { private val logger = LoggerFactory.getLogger(JavaStackFrame::class.java) @@ -107,6 +110,10 @@ class JavaStackFrame( return@mapNotNull null } + if (isSyntheticKotlinLocal(variable.name())) { + return@mapNotNull null + } + try { JavaLocalVariable.forVariable( thread = thread, diff --git a/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/debug/Variables.kt b/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/debug/Variables.kt index 5bb76132e4..c026abae35 100644 --- a/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/debug/Variables.kt +++ b/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/debug/Variables.kt @@ -7,6 +7,7 @@ import com.itsaky.androidide.lsp.debug.model.Variable import com.itsaky.androidide.lsp.debug.model.VariableDescriptor import com.itsaky.androidide.lsp.debug.model.VariableKind import com.itsaky.androidide.lsp.java.debug.utils.VariableValues +import com.itsaky.androidide.lsp.java.debug.utils.kotlinLocalDisplayName import com.itsaky.androidide.lsp.java.debug.utils.mirrorOf import com.sun.jdi.ArrayReference import com.sun.jdi.ArrayType @@ -195,7 +196,9 @@ internal abstract class AbstractJavaVariable( // TODO: Support other array-like types (like lists). is ArrayType -> VariableKind.ARRAYLIKE + is ObjectReference -> VariableKind.REFERENCE + else -> VariableKind.UNKNOWN } } @@ -327,7 +330,7 @@ internal open class JavaLocalVariable( value: Value?, ) : AbstractJavaVariable( thread = thread, - name = variable.name(), + name = kotlinLocalDisplayName(variable.name()), typeName = variable.typeName(), type = if (variable is ObjectReference) variable.referenceType() else variable.type(), value = value, diff --git a/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/debug/utils/KotlinLocals.kt b/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/debug/utils/KotlinLocals.kt new file mode 100644 index 0000000000..195bcfac6d --- /dev/null +++ b/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/debug/utils/KotlinLocals.kt @@ -0,0 +1,25 @@ +package com.itsaky.androidide.lsp.java.debug.utils + +private const val INLINE_MARKER_PREFIX = "\$i\$" +private const val INLINE_RECEIVER_PREFIX = "\$this\$" + +private val SUSPEND_MACHINE_LOCALS = + setOf( + "\$continuation", + "\$result", + "\$completion", + ) + +fun isSyntheticKotlinLocal(name: String): Boolean = name.startsWith(INLINE_MARKER_PREFIX) || name in SUSPEND_MACHINE_LOCALS + +fun isInlinedRegion(visibleLocalNames: Collection): Boolean = + visibleLocalNames.any { name -> name.startsWith(INLINE_MARKER_PREFIX) } + +fun kotlinLocalDisplayName(name: String): String { + if (!name.startsWith(INLINE_RECEIVER_PREFIX)) { + return name + } + + val label = name.removePrefix(INLINE_RECEIVER_PREFIX) + return if (label.isEmpty()) name else "this@$label" +} diff --git a/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/debug/utils/ModelUtils.kt b/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/debug/utils/ModelUtils.kt index d8994aef60..a0a2589770 100644 --- a/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/debug/utils/ModelUtils.kt +++ b/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/debug/utils/ModelUtils.kt @@ -41,8 +41,7 @@ fun Location.asLspLocation(useDeclTypeName: Boolean = true): LspLocation { if (fo == null) { val className = - this - .sourcePath() + (this.sourcePathOrNull() ?: "") .replace('/', '.') .substringBeforeLast(".java") logger.debug("finding source file for class: '{}'", className) diff --git a/lsp/java/src/test/java/com/itsaky/androidide/lsp/java/debug/KotlinLocalsTest.kt b/lsp/java/src/test/java/com/itsaky/androidide/lsp/java/debug/KotlinLocalsTest.kt new file mode 100644 index 0000000000..6932977746 --- /dev/null +++ b/lsp/java/src/test/java/com/itsaky/androidide/lsp/java/debug/KotlinLocalsTest.kt @@ -0,0 +1,77 @@ +/* + * This file is part of AndroidIDE. + * + * AndroidIDE is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * AndroidIDE is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with AndroidIDE. If not, see . + */ +package com.itsaky.androidide.lsp.java.debug + +import com.google.common.truth.Truth.assertThat +import com.itsaky.androidide.lsp.java.debug.utils.isInlinedRegion +import com.itsaky.androidide.lsp.java.debug.utils.isSyntheticKotlinLocal +import com.itsaky.androidide.lsp.java.debug.utils.kotlinLocalDisplayName +import org.junit.Test + +class KotlinLocalsTest { + @Test + fun `inline markers are synthetic`() { + assertThat(isSyntheticKotlinLocal("\$i\$f\$Column")).isTrue() + assertThat(isSyntheticKotlinLocal("\$i\$a\$-map-Foo")).isTrue() + assertThat(isSyntheticKotlinLocal("\$i\$f\$all")).isTrue() + } + + @Test + fun `suspend state machine locals are synthetic`() { + assertThat(isSyntheticKotlinLocal("\$continuation")).isTrue() + assertThat(isSyntheticKotlinLocal("\$result")).isTrue() + assertThat(isSyntheticKotlinLocal("\$completion")).isTrue() + } + + @Test + fun `user locals are kept`() { + assertThat(isSyntheticKotlinLocal("answer")).isFalse() + assertThat(isSyntheticKotlinLocal("savedInstanceState")).isFalse() + assertThat(isSyntheticKotlinLocal("this")).isFalse() + assertThat(isSyntheticKotlinLocal("_binding")).isFalse() + } + + @Test + fun `inline lambda receivers are kept and renamed`() { + assertThat(isSyntheticKotlinLocal("\$this\$run")).isFalse() + assertThat(kotlinLocalDisplayName("\$this\$run")).isEqualTo("this@run") + assertThat(kotlinLocalDisplayName("\$this\$apply")).isEqualTo("this@apply") + } + + @Test + fun `ordinary names are not renamed`() { + assertThat(kotlinLocalDisplayName("answer")).isEqualTo("answer") + assertThat(kotlinLocalDisplayName("this")).isEqualTo("this") + assertThat(kotlinLocalDisplayName("\$this\$")).isEqualTo("\$this\$") + } + + @Test + fun `a frame holding an inline marker is an inlined region`() { + assertThat(isInlinedRegion(listOf("answer", "\$i\$f\$measured"))).isTrue() + } + + @Test + fun `a frame without inline markers is not an inlined region`() { + assertThat(isInlinedRegion(listOf("answer", "savedInstanceState"))).isFalse() + assertThat(isInlinedRegion(emptyList())).isFalse() + } + + @Test + fun `a suspend frame alone is not an inlined region`() { + assertThat(isInlinedRegion(listOf("\$continuation", "\$result"))).isFalse() + } +} diff --git a/testing/resources/kotlin-debug-fixture/DebugFixture.kt b/testing/resources/kotlin-debug-fixture/DebugFixture.kt new file mode 100644 index 0000000000..d71006dce4 --- /dev/null +++ b/testing/resources/kotlin-debug-fixture/DebugFixture.kt @@ -0,0 +1,58 @@ +package com.example.debugfixture + +inline fun measured( + label: String, + body: () -> T, +): T { + val started = System.nanoTime() + val result = body() + println("$label took ${System.nanoTime() - started}") + return result +} + +fun topLevel(n: Int): Int { + val doubled = n * 2 + return doubled +} + +class Greeter( + private val name: String, +) { + fun greet(): String { + val greeting = "hello $name" + return greeting + } + + fun greetAll(names: List): List = + names.map { each -> + val greeting = "hello $each" + greeting + } + + fun timed(): Int = + measured("greeter") { + val doubled = topLevel(21) + doubled + } + + fun deferred(): Runnable = + object : Runnable { + override fun run() { + val answer = 42 + println("anonymous object ran: $answer") + } + } +} + +suspend fun suspending(n: Int): Int { + val doubled = topLevel(n) + return doubled + 1 +} + +fun runAll() { + val greeter = Greeter("world") + println(greeter.greet()) + println(greeter.greetAll(listOf("first", "second"))) + println(greeter.timed()) + greeter.deferred().run() +} diff --git a/testing/resources/kotlin-debug-fixture/README.md b/testing/resources/kotlin-debug-fixture/README.md new file mode 100644 index 0000000000..1637ff976d --- /dev/null +++ b/testing/resources/kotlin-debug-fixture/README.md @@ -0,0 +1,42 @@ +# Kotlin debugger fixture + +`DebugFixture.kt` is the debuggee for the Kotlin debugger work (ADFA-4175). It is a plain source +file rather than a whole project: CoGo's own Kotlin template already produces a working Android +project, so QA exercises the same path a user does instead of a bespoke fixture that can drift. + +## Setup + +1. In CoGo, create a new project from a **Kotlin** template. +2. Copy `DebugFixture.kt` into `app/src/main/java/com/example/debugfixture/`. +3. Call `runAll()` from `MainActivity.onCreate`, after `setContentView`. +4. Build and launch under the debugger (the bug icon, not the play icon). + +`runAll` reaches every construct below except `suspending`, which needs a coroutine context - call +it from the app's own scope if the template provides one. + +## Line map + +Each line below is a breakpoint target. Line numbers are stable as long as the file is not edited. + +| Line | Construct | Compiles to | +|------|-----------|-------------| +| 7 | inline function body | the **caller's** class, not `measured` | +| 14 | top-level function | `DebugFixtureKt` | +| 22 | class method | `Greeter` | +| 28 | lambda passed to `map` | the caller's class (`map` is inline) | +| 34 | lambda passed to an inline function | the caller's class | +| 41 | anonymous object | `Greeter$deferred$1` - a separate class | +| 48 | suspend function | `DebugFixtureKt` + a continuation | + +Line 41 is the important one. A Kotlin file compiles to many classes, and `Greeter` loads before +`Greeter$deferred$1`, so a breakpoint there only binds if the `ClassPrepare` request is not capped +at the first matching class (ADFA-4190). + +Line 34 is the inline case: its Java-stratum line number is synthetic and past the end of the file, +so the debugger must report the Kotlin-stratum position instead (ADFA-4190, ADFA-4191). + +## Known limitation + +Stepping across a coroutine suspension point does not work. A suspend function resumes on a +different thread and JDI's step request is thread-scoped, so the step is lost. Breakpoints inside +suspend bodies still hit. See ADFA-4175. From 5730c7f37bdba067e26d0604de910ba6967565f7 Mon Sep 17 00:00:00 2001 From: Daniel Alome Date: Thu, 17 Sep 2026 14:46:03 +0100 Subject: [PATCH 03/11] fix: drop inline step continuation, address review on ADFA-4191 The continuation asked whether the frame carries a $i$ local and kept stepping while it did. Kotlin scopes an inlined lambda argument with $i$a$ in the class the lambda was written in, so that test is true inside the user's own lambda: Step Over inside forEach, map, let or run walked every line of it and reported a location up to 64 steps away. The predicate answers which locals to hide, not whose code is running, and reusing it for the second question was the error. Telling a library body inlined into the user's class from a lambda the user wrote there needs the Kotlin-stratum source path checked against the project's source roots. That is its own piece of work, so the continuation is removed rather than patched, and with it go the step depth reused from the user's request, the SUSPEND_ALL iterations that were never matched by a resume, and the unsynchronised adapter-wide counter. Step filters and the variables list are unchanged and still do their jobs. The fixture README claimed the debugger reports the Kotlin-stratum position; it reports the Java stratum everywhere, so it now says what the code does and carries the Step Over limitation. --- .../lsp/java/debug/JavaDebugAdapter.kt | 62 ------------------- .../lsp/java/debug/utils/KotlinLocals.kt | 18 +++++- .../lsp/java/debug/KotlinLocalsTest.kt | 18 ++---- .../resources/kotlin-debug-fixture/README.md | 14 ++++- 4 files changed, 30 insertions(+), 82 deletions(-) diff --git a/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/debug/JavaDebugAdapter.kt b/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/debug/JavaDebugAdapter.kt index 92a4db000c..110fbb1011 100644 --- a/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/debug/JavaDebugAdapter.kt +++ b/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/debug/JavaDebugAdapter.kt @@ -28,7 +28,6 @@ import com.itsaky.androidide.lsp.java.debug.spec.BreakpointSpec import com.itsaky.androidide.lsp.java.debug.utils.asDepthInt import com.itsaky.androidide.lsp.java.debug.utils.asJdiInt import com.itsaky.androidide.lsp.java.debug.utils.asLspLocation -import com.itsaky.androidide.lsp.java.debug.utils.isInlinedRegion import com.itsaky.androidide.lsp.java.debug.utils.isKotlinSource import com.itsaky.androidide.lsp.java.debug.utils.kotlinBinaryNamesOf import com.itsaky.androidide.projects.ProjectManagerImpl @@ -72,7 +71,6 @@ internal class JavaDebugAdapter : private var listenerThread: JDWPListenerThread? = null private var _listenerState: ListenerState? = null - private var inlineStepCount = 0 val listenerState: ListenerState get() = @@ -97,8 +95,6 @@ internal class JavaDebugAdapter : "kotlinx.*", ) - private const val MAX_INLINE_STEPS = 64 - /** * Get the current instance of the [JavaDebugAdapter]. */ @@ -459,7 +455,6 @@ internal class JavaDebugAdapter : logger.debug("Step {} thread {}", request.type, suspendedThread.thread.name()) clearPreviousStep(vm.vm, suspendedThread.thread) - inlineStepCount = 0 val reqMgr = vm.vm.eventRequestManager() val req = @@ -526,57 +521,6 @@ internal class JavaDebugAdapter : } } - private fun resumeStepThroughInlinedBody( - vm: VmConnection, - e: StepEvent, - thread: ThreadReference, - ): Boolean { - val request = e.request() as? StepRequest ?: return false - - if (request.depth() == StepRequest.STEP_INTO) { - return false - } - - val visibleLocalNames = - try { - thread.frame(0).visibleVariables().map { it.name() } - } catch (err: AbsentInformationException) { - return false - } catch (err: IncompatibleThreadStateException) { - return false - } - - if (!isInlinedRegion(visibleLocalNames)) { - return false - } - - if (++inlineStepCount > MAX_INLINE_STEPS) { - logger.warn( - "Still inside an inlined body after {} steps, reporting current location", - MAX_INLINE_STEPS, - ) - return false - } - - clearPreviousStep(vm.vm, thread) - - val req = - vm.vm.eventRequestManager().createStepRequest( - thread, - StepRequest.STEP_LINE, - request.depth(), - ) - for (pattern in DEFAULT_CLASS_EXCLUSION_FILTERS) { - req.addClassExclusionFilter(pattern) - } - req.setSuspendPolicy(EventRequest.SUSPEND_ALL) - req.addCountFilter(1) - req.enable() - thread.resume() - vm.threadState.invalidateAll() - return true - } - private fun clearPreviousStep( vm: VirtualMachine, thread: ThreadReference, @@ -622,12 +566,6 @@ internal class JavaDebugAdapter : val location = e.location() val thread = e.thread() - if (resumeStepThroughInlinedBody(vm, e, thread)) { - return - } - - inlineStepCount = 0 - listenerState.client.onStep( event = LspStepEvent( diff --git a/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/debug/utils/KotlinLocals.kt b/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/debug/utils/KotlinLocals.kt index 195bcfac6d..52b1fd4ae4 100644 --- a/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/debug/utils/KotlinLocals.kt +++ b/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/debug/utils/KotlinLocals.kt @@ -10,11 +10,23 @@ private val SUSPEND_MACHINE_LOCALS = "\$completion", ) +/** + * Whether [name] is a local the Kotlin compiler generated rather than one the user wrote. + * + * Covers the inline markers (`$i$f$` for an inlined function body, `$i$a$` for an inlined lambda + * argument) and the suspend state machine's own locals. These carry no meaning for someone reading + * their own code, so the variables list hides them. + * + * This answers what to *display*. It does not answer whether execution is inside library code: an + * inlined lambda the user wrote carries `$i$a$` in the user's own class, so the marker cannot tell + * the two apart. + */ fun isSyntheticKotlinLocal(name: String): Boolean = name.startsWith(INLINE_MARKER_PREFIX) || name in SUSPEND_MACHINE_LOCALS -fun isInlinedRegion(visibleLocalNames: Collection): Boolean = - visibleLocalNames.any { name -> name.startsWith(INLINE_MARKER_PREFIX) } - +/** + * The name to show for [name], mapping an inline lambda receiver to the Kotlin syntax for it, so + * `$this$run` reads as `this@run`. Any other name is returned unchanged. + */ fun kotlinLocalDisplayName(name: String): String { if (!name.startsWith(INLINE_RECEIVER_PREFIX)) { return name diff --git a/lsp/java/src/test/java/com/itsaky/androidide/lsp/java/debug/KotlinLocalsTest.kt b/lsp/java/src/test/java/com/itsaky/androidide/lsp/java/debug/KotlinLocalsTest.kt index 6932977746..c7ec02aadd 100644 --- a/lsp/java/src/test/java/com/itsaky/androidide/lsp/java/debug/KotlinLocalsTest.kt +++ b/lsp/java/src/test/java/com/itsaky/androidide/lsp/java/debug/KotlinLocalsTest.kt @@ -17,7 +17,6 @@ package com.itsaky.androidide.lsp.java.debug import com.google.common.truth.Truth.assertThat -import com.itsaky.androidide.lsp.java.debug.utils.isInlinedRegion import com.itsaky.androidide.lsp.java.debug.utils.isSyntheticKotlinLocal import com.itsaky.androidide.lsp.java.debug.utils.kotlinLocalDisplayName import org.junit.Test @@ -60,18 +59,9 @@ class KotlinLocalsTest { } @Test - fun `a frame holding an inline marker is an inlined region`() { - assertThat(isInlinedRegion(listOf("answer", "\$i\$f\$measured"))).isTrue() - } - - @Test - fun `a frame without inline markers is not an inlined region`() { - assertThat(isInlinedRegion(listOf("answer", "savedInstanceState"))).isFalse() - assertThat(isInlinedRegion(emptyList())).isFalse() - } - - @Test - fun `a suspend frame alone is not an inlined region`() { - assertThat(isInlinedRegion(listOf("\$continuation", "\$result"))).isFalse() + fun `an inlined lambda argument is hidden, not treated as library code`() { + // $i$a$ scopes a lambda the user wrote, inlined into the user's own class, so it is noise in + // the variables list but says nothing about whose code is executing. + assertThat(isSyntheticKotlinLocal("\$i\$a\$-forEach-MainActivity")).isTrue() } } diff --git a/testing/resources/kotlin-debug-fixture/README.md b/testing/resources/kotlin-debug-fixture/README.md index 1637ff976d..058300e609 100644 --- a/testing/resources/kotlin-debug-fixture/README.md +++ b/testing/resources/kotlin-debug-fixture/README.md @@ -32,11 +32,19 @@ Line 41 is the important one. A Kotlin file compiles to many classes, and `Greet `Greeter$deferred$1`, so a breakpoint there only binds if the `ClassPrepare` request is not capped at the first matching class (ADFA-4190). -Line 34 is the inline case: its Java-stratum line number is synthetic and past the end of the file, -so the debugger must report the Kotlin-stratum position instead (ADFA-4190, ADFA-4191). +Line 34 is the inline case. The debugger places and reports every location in the Java stratum, and +the Kotlin inliner writes the inlined body's lines into the caller's line table under synthetic +numbers past the end of the file. So a breakpoint on line 7 (the body of `measured`) binds against +`measured`'s own class rather than against the copy inlined into line 34's caller, and a location +that does land in an inlined body reports a line past the end of the file. Reporting the +Kotlin-stratum position there is what would fix it. -## Known limitation +## Known limitations Stepping across a coroutine suspension point does not work. A suspend function resumes on a different thread and JDI's step request is thread-scoped, so the step is lost. Breakpoints inside suspend bodies still hit. See ADFA-4175. + +Step Over does not treat an inlined body as one step: it walks the inlined lines the same way it +walks any other. Skipping them needs the Kotlin stratum to tell a library body inlined into the +user's class apart from a lambda the user wrote there, which the inline markers alone cannot do. From 938c75c2a6d0965df34514e3168bf43a8321bcbb Mon Sep 17 00:00:00 2001 From: Daniel Alome Date: Thu, 17 Sep 2026 19:50:20 +0100 Subject: [PATCH 04/11] fix: match the locals Kotlin actually emits, address review on ADFA-4191 The receiver rename was written against `$this$run`, which the compiler never emits. A lambda receiver comes out named after the enclosing method's synthetic lambda, `$this$direct_u24lambda_u240`, and an inlined function's receiver as `$this$map$iv`, so the variables list showed `this@direct_u24lambda_u240` and `this@map$iv`: labels absent from anyone's source, on `run`, `let`, `apply` and `map`. A label is now derived only where one the user could have written survives, and the mangled lambda name is left as it is rather than dressed up. The inliner appends one `$iv` per inlining to every local copied out of an inlined body, and neither predicate accounted for it. The user's own `started`, `result` and `label` were shown as `started$iv` and friends, and stdlib internals such as `destination$iv$iv` were not recognised as synthetic. The suffixes come off before either question is asked. Stripping cannot separate a library body's locals from the user's own, so a stdlib internal still shows under its unsuffixed name; that is the same limit the `$i$` KDoc already records. `AbsentInformationException` and `IncompatibleThreadStateException` went unused when the step continuation was deleted, which broke `spotlessCheck` and blocked the merge. Two pre-existing defects in the blocks this PR edits: variables were read from the refetched frame but their values from the captured one, which loses the whole list to `InvalidStackFrameException` once an evaluation has resumed the thread; and `is ObjectReference` was asked of a `Type`, which no JDI type satisfies, so every object variable reported `UNKNOWN` and lost its icon. The same dead test in `JavaLocalVariable` always took its else branch. The fixture README claimed line 7 compiles into the caller's class. `javap -l` says `measured` keeps its real lines 7-10 and the inlined copy lands at 64-67 of a 58-line file, so a line 7 breakpoint binds to `DebugFixtureKt` and, since `runAll` only reaches `measured` inlined, does not hit at all. It now says so, and records that stepping through an inlined body reports the wrong file rather than only a line past the end of one. The resources index lists the fixture. --- .../lsp/java/debug/JavaDebugAdapter.kt | 2 - .../lsp/java/debug/LspThreadInfo.kt | 2 +- .../androidide/lsp/java/debug/Variables.kt | 4 +- .../lsp/java/debug/utils/KotlinLocals.kt | 48 +++++++++++++++---- .../lsp/java/debug/KotlinLocalsTest.kt | 29 +++++++++-- testing/resources/README.md | 5 +- .../resources/kotlin-debug-fixture/README.md | 26 +++++++--- 7 files changed, 90 insertions(+), 26 deletions(-) diff --git a/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/debug/JavaDebugAdapter.kt b/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/debug/JavaDebugAdapter.kt index 110fbb1011..b8eae7dc53 100644 --- a/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/debug/JavaDebugAdapter.kt +++ b/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/debug/JavaDebugAdapter.kt @@ -33,9 +33,7 @@ import com.itsaky.androidide.lsp.java.debug.utils.kotlinBinaryNamesOf import com.itsaky.androidide.projects.ProjectManagerImpl import com.itsaky.androidide.projects.api.ModuleProject import com.itsaky.androidide.utils.withStopWatch -import com.sun.jdi.AbsentInformationException import com.sun.jdi.Bootstrap -import com.sun.jdi.IncompatibleThreadStateException import com.sun.jdi.ThreadReference import com.sun.jdi.VMDisconnectedException import com.sun.jdi.VirtualMachine diff --git a/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/debug/LspThreadInfo.kt b/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/debug/LspThreadInfo.kt index ab091b954a..7e49c2bd15 100644 --- a/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/debug/LspThreadInfo.kt +++ b/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/debug/LspThreadInfo.kt @@ -119,7 +119,7 @@ class JavaStackFrame( thread = thread, stackFrame = this@JavaStackFrame, variable = variable, - value = frame.getValue(variable), + value = getValue(variable), ) } catch (e: VMDisconnectedException) { throw e diff --git a/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/debug/Variables.kt b/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/debug/Variables.kt index c026abae35..872a83ce81 100644 --- a/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/debug/Variables.kt +++ b/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/debug/Variables.kt @@ -197,7 +197,7 @@ internal abstract class AbstractJavaVariable( // TODO: Support other array-like types (like lists). is ArrayType -> VariableKind.ARRAYLIKE - is ObjectReference -> VariableKind.REFERENCE + is ReferenceType -> VariableKind.REFERENCE else -> VariableKind.UNKNOWN } @@ -332,7 +332,7 @@ internal open class JavaLocalVariable( thread = thread, name = kotlinLocalDisplayName(variable.name()), typeName = variable.typeName(), - type = if (variable is ObjectReference) variable.referenceType() else variable.type(), + type = variable.type(), value = value, ) { companion object { diff --git a/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/debug/utils/KotlinLocals.kt b/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/debug/utils/KotlinLocals.kt index 52b1fd4ae4..7f3919cacc 100644 --- a/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/debug/utils/KotlinLocals.kt +++ b/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/debug/utils/KotlinLocals.kt @@ -2,6 +2,8 @@ package com.itsaky.androidide.lsp.java.debug.utils private const val INLINE_MARKER_PREFIX = "\$i\$" private const val INLINE_RECEIVER_PREFIX = "\$this\$" +private const val INLINE_COPY_SUFFIX = "\$iv" +private const val MANGLED_DOLLAR = "_u24" private val SUSPEND_MACHINE_LOCALS = setOf( @@ -17,21 +19,47 @@ private val SUSPEND_MACHINE_LOCALS = * argument) and the suspend state machine's own locals. These carry no meaning for someone reading * their own code, so the variables list hides them. * - * This answers what to *display*. It does not answer whether execution is inside library code: an - * inlined lambda the user wrote carries `$i$a$` in the user's own class, so the marker cannot tell - * the two apart. + * Every local copied out of an inlined body also carries one `$iv` per inlining, so the suffixes come + * off first. Stripping does not separate a library body's locals from the user's own inline-function + * locals -- both arrive suffixed -- so a stdlib internal such as `destination$iv$iv` survives this + * predicate under its unsuffixed name. Telling the two apart needs the Kotlin stratum, which is the + * same limit that applies to `$i$`. */ -fun isSyntheticKotlinLocal(name: String): Boolean = name.startsWith(INLINE_MARKER_PREFIX) || name in SUSPEND_MACHINE_LOCALS +fun isSyntheticKotlinLocal(name: String): Boolean { + val base = withoutInlineCopySuffixes(name) + return base.startsWith(INLINE_MARKER_PREFIX) || base in SUSPEND_MACHINE_LOCALS +} /** - * The name to show for [name], mapping an inline lambda receiver to the Kotlin syntax for it, so - * `$this$run` reads as `this@run`. Any other name is returned unchanged. + * The name to show for [name]: the source name for a local copied out of an inlined body, and the + * Kotlin syntax for an inline receiver where one can be recovered. + * + * `$this$map$iv` reads as `this@map`. A lambda receiver is emitted named after the enclosing method's + * synthetic lambda instead -- `$this$direct_u24lambda_u240`, where `_u24` is a mangled `$` -- and no + * label the user could have written is recoverable from it, so that name is left alone rather than + * turned into a `this@` that appears nowhere in their source. */ fun kotlinLocalDisplayName(name: String): String { - if (!name.startsWith(INLINE_RECEIVER_PREFIX)) { - return name + val base = withoutInlineCopySuffixes(name) + if (!base.startsWith(INLINE_RECEIVER_PREFIX)) { + return base } - val label = name.removePrefix(INLINE_RECEIVER_PREFIX) - return if (label.isEmpty()) name else "this@$label" + val label = base.removePrefix(INLINE_RECEIVER_PREFIX) + return if (isSourceLabel(label)) "this@$label" else base +} + +/** [name] with every `$iv` the inliner appended removed, one per inlining. */ +private fun withoutInlineCopySuffixes(name: String): String { + var base = name + while (base.length > INLINE_COPY_SUFFIX.length && base.endsWith(INLINE_COPY_SUFFIX)) { + base = base.dropLast(INLINE_COPY_SUFFIX.length) + } + return base } + +/** Whether [label] is a name the user could have written, rather than a synthetic lambda's. */ +private fun isSourceLabel(label: String): Boolean = + label.isNotEmpty() && + !label.contains(MANGLED_DOLLAR) && + label.all { it.isLetterOrDigit() || it == '_' } diff --git a/lsp/java/src/test/java/com/itsaky/androidide/lsp/java/debug/KotlinLocalsTest.kt b/lsp/java/src/test/java/com/itsaky/androidide/lsp/java/debug/KotlinLocalsTest.kt index c7ec02aadd..5c2afab308 100644 --- a/lsp/java/src/test/java/com/itsaky/androidide/lsp/java/debug/KotlinLocalsTest.kt +++ b/lsp/java/src/test/java/com/itsaky/androidide/lsp/java/debug/KotlinLocalsTest.kt @@ -29,6 +29,12 @@ class KotlinLocalsTest { assertThat(isSyntheticKotlinLocal("\$i\$f\$all")).isTrue() } + @Test + fun `an inline marker copied out of a nested inlining is still synthetic`() { + assertThat(isSyntheticKotlinLocal("\$i\$f\$measured\$iv")).isTrue() + assertThat(isSyntheticKotlinLocal("\$i\$f\$mapTo\$iv\$iv")).isTrue() + } + @Test fun `suspend state machine locals are synthetic`() { assertThat(isSyntheticKotlinLocal("\$continuation")).isTrue() @@ -45,10 +51,25 @@ class KotlinLocalsTest { } @Test - fun `inline lambda receivers are kept and renamed`() { - assertThat(isSyntheticKotlinLocal("\$this\$run")).isFalse() - assertThat(kotlinLocalDisplayName("\$this\$run")).isEqualTo("this@run") - assertThat(kotlinLocalDisplayName("\$this\$apply")).isEqualTo("this@apply") + fun `a local copied out of an inlined body shows the name its source gave it`() { + assertThat(kotlinLocalDisplayName("started\$iv")).isEqualTo("started") + assertThat(kotlinLocalDisplayName("label\$iv")).isEqualTo("label") + assertThat(kotlinLocalDisplayName("item\$iv\$iv")).isEqualTo("item") + } + + @Test + fun `an inline receiver keeps its label through the copy suffixes`() { + assertThat(isSyntheticKotlinLocal("\$this\$map\$iv")).isFalse() + assertThat(kotlinLocalDisplayName("\$this\$map\$iv")).isEqualTo("this@map") + assertThat(kotlinLocalDisplayName("\$this\$mapTo\$iv\$iv")).isEqualTo("this@mapTo") + } + + @Test + fun `a synthetic lambda receiver is left alone rather than given a fabricated label`() { + // Kotlin names a lambda's receiver after the enclosing method's synthetic lambda, where _u24 + // is a mangled '$'. No label the user wrote is recoverable from it. + assertThat(kotlinLocalDisplayName("\$this\$direct_u24lambda_u240")) + .isEqualTo("\$this\$direct_u24lambda_u240") } @Test diff --git a/testing/resources/README.md b/testing/resources/README.md index 1fd2ca84fe..68d7fe1622 100644 --- a/testing/resources/README.md +++ b/testing/resources/README.md @@ -5,4 +5,7 @@ This directory contains resources for unit tests related to the tooling API serv - `test-project`: A basic project used for testing almost everything related to the tooling API (multi-module support, build cancellations, dependency & task resolutions, model builders, etc.). This project is not buildable i.e. running `assembleDebug` in this project will fail. -- `sample-project`: A basic project which can be built, used in some rare cases (like testing configuration cache support). \ No newline at end of file +- `sample-project`: A basic project which can be built, used in some rare cases (like testing configuration cache support). +- `kotlin-debug-fixture`: A single Kotlin source file used as the debuggee for the Kotlin debugger + work (ADFA-4175). It is copied into a project made from CoGo's Kotlin template rather than built + here; see its own README for the line map and known limitations. diff --git a/testing/resources/kotlin-debug-fixture/README.md b/testing/resources/kotlin-debug-fixture/README.md index 058300e609..4c6679935e 100644 --- a/testing/resources/kotlin-debug-fixture/README.md +++ b/testing/resources/kotlin-debug-fixture/README.md @@ -12,7 +12,9 @@ project, so QA exercises the same path a user does instead of a bespoke fixture 4. Build and launch under the debugger (the bug icon, not the play icon). `runAll` reaches every construct below except `suspending`, which needs a coroutine context - call -it from the app's own scope if the template provides one. +it from the app's own scope if the template provides one. It reaches `measured` only inlined into +its callers, never as a call into `measured` itself, so the line 7 breakpoint is expected not to +hit; see the line map. ## Line map @@ -20,7 +22,7 @@ Each line below is a breakpoint target. Line numbers are stable as long as the f | Line | Construct | Compiles to | |------|-----------|-------------| -| 7 | inline function body | the **caller's** class, not `measured` | +| 7 | inline function body | `DebugFixtureKt` - does **not** hit, see below | | 14 | top-level function | `DebugFixtureKt` | | 22 | class method | `Greeter` | | 28 | lambda passed to `map` | the caller's class (`map` is inline) | @@ -34,10 +36,13 @@ at the first matching class (ADFA-4190). Line 34 is the inline case. The debugger places and reports every location in the Java stratum, and the Kotlin inliner writes the inlined body's lines into the caller's line table under synthetic -numbers past the end of the file. So a breakpoint on line 7 (the body of `measured`) binds against -`measured`'s own class rather than against the copy inlined into line 34's caller, and a location -that does land in an inlined body reports a line past the end of the file. Reporting the -Kotlin-stratum position there is what would fix it. +numbers past the end of the file. `javap -l` on the compiled fixture shows `DebugFixtureKt.measured` +keeping its real lines 7-10, and `Greeter.timed` carrying the inlined copy as lines 64-67 of a +58-line file. + +So a breakpoint on line 7 binds against `measured`'s own class and never against the copy inlined +into a caller. Since `runAll` only ever reaches `measured` inlined, that breakpoint does not hit at +all - expected, not a defect to file. Reporting the Kotlin-stratum position is what would fix it. ## Known limitations @@ -48,3 +53,12 @@ suspend bodies still hit. See ADFA-4175. Step Over does not treat an inlined body as one step: it walks the inlined lines the same way it walks any other. Skipping them needs the Kotlin stratum to tell a library body inlined into the user's class apart from a lambda the user wrote there, which the inline markers alone cannot do. + +While it walks them, the editor is sent the **wrong file**, not only a line past the end of one. +`Greeter.greetAll` carries output lines 60-63, which the SMAP maps to `_Collections.kt:1557` and +`1628-1630`, the stdlib `map` body. The Java stratum has one `SourceFile` per class, so those lines +are reported as `DebugFixture.kt`: Step Over in `greetAll` walks `27 -> 60 -> 61 -> 62 -> 28` and +asks the editor to highlight `DebugFixture.kt:60` in a 59-line file while execution is really in the +standard library. The `kotlin.*` / `kotlinx.*` step filters do not prevent this, because the inlined +body lives in the user's own class and a class-name filter never sees it. Reachable through any +`map`, `forEach`, `let` or `run`. From 264440f42c672c73f1373d2d5a11c86daf8a4cf1 Mon Sep 17 00:00:00 2001 From: Daniel Alome Date: Mon, 21 Sep 2026 12:33:32 +0100 Subject: [PATCH 05/11] fix: report the call stack in the Kotlin stratum, address review on ADFA-4191 Round 4 findings. The call-stack row read the Java stratum, which has one SourceFile per class, so a frame inside an inlined stdlib body was labelled with the caller's file at a synthetic line past its end. The Kotlin stratum is the only one with a multi-file table, so it names the file the code was written in. JDI falls back to the declaring type's default stratum when Kotlin is absent, so the new helpers are safe on a Java class. Placement stays in the Java stratum: the row is display-only and its one consumer is a TextView. Stripping $iv for display renamed mapTo's own item and destination into names indistinguishable from the user's. The suffix is the only cue separating them, so it stays on, at the cost of a user's own inline-function local reading started$iv. That also retires the this@ rename, which the compiler's emitted names never made correct: $this$map$iv became this@map, and map's lambda takes a parameter rather than a receiver, so that label compiles nowhere. The only shapes a user could have written are already left alone, so the helper had no case left to serve and is gone. JavaFieldVariable passed the declaring type as the field's type. Beyond the icon, that fed VariableValues.parseValue, so editing an int field parsed against its owner and failed, and canMutate reported every field immutable. field.type() throws ClassNotLoadedException, which the locals path already guards per variable, so the field loop now guards the same way rather than losing the whole member list to one unloaded type. --- .../lsp/java/debug/LspThreadInfo.kt | 8 ++-- .../androidide/lsp/java/debug/Variables.kt | 18 +++++--- .../lsp/java/debug/utils/KotlinLocals.kt | 43 +++++-------------- .../androidide/lsp/java/debug/utils/Strata.kt | 22 ++++++++++ .../lsp/java/debug/KotlinLocalsTest.kt | 32 ++++---------- .../resources/kotlin-debug-fixture/README.md | 15 ++++++- 6 files changed, 72 insertions(+), 66 deletions(-) diff --git a/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/debug/LspThreadInfo.kt b/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/debug/LspThreadInfo.kt index 7e49c2bd15..d13363139c 100644 --- a/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/debug/LspThreadInfo.kt +++ b/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/debug/LspThreadInfo.kt @@ -10,8 +10,8 @@ import com.itsaky.androidide.lsp.debug.model.Variable import com.itsaky.androidide.lsp.debug.model.VariableKind import com.itsaky.androidide.lsp.java.debug.utils.isOpaque import com.itsaky.androidide.lsp.java.debug.utils.isSyntheticKotlinLocal -import com.itsaky.androidide.lsp.java.debug.utils.lineNumberInSource -import com.itsaky.androidide.lsp.java.debug.utils.sourceNameOrNull +import com.itsaky.androidide.lsp.java.debug.utils.lineNumberInKotlin +import com.itsaky.androidide.lsp.java.debug.utils.sourceNameInKotlinOrNull import com.sun.jdi.Location import com.sun.jdi.Method import com.sun.jdi.ObjectCollectedException @@ -31,8 +31,8 @@ class JavaStackFrame( val frame: StackFrame, val location: Location = frame.location(), val method: Method? = location.method(), - val sourceName: String = location.sourceNameOrNull() ?: "", - val lineNumber: Long = location.lineNumberInSource().toLong(), + val sourceName: String = location.sourceNameInKotlinOrNull() ?: "", + val lineNumber: Long = location.lineNumberInKotlin().toLong(), ) : LspStackFrame { companion object { private val logger = LoggerFactory.getLogger(JavaStackFrame::class.java) diff --git a/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/debug/Variables.kt b/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/debug/Variables.kt index 872a83ce81..943626f56b 100644 --- a/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/debug/Variables.kt +++ b/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/debug/Variables.kt @@ -7,7 +7,6 @@ import com.itsaky.androidide.lsp.debug.model.Variable import com.itsaky.androidide.lsp.debug.model.VariableDescriptor import com.itsaky.androidide.lsp.debug.model.VariableKind import com.itsaky.androidide.lsp.java.debug.utils.VariableValues -import com.itsaky.androidide.lsp.java.debug.utils.kotlinLocalDisplayName import com.itsaky.androidide.lsp.java.debug.utils.mirrorOf import com.sun.jdi.ArrayReference import com.sun.jdi.ArrayType @@ -30,6 +29,7 @@ import com.sun.jdi.ShortType import com.sun.jdi.StringReference import com.sun.jdi.ThreadReference import com.sun.jdi.Type +import com.sun.jdi.VMDisconnectedException import com.sun.jdi.Value import com.sun.jdi.VoidValue import org.slf4j.LoggerFactory @@ -233,8 +233,15 @@ internal abstract class AbstractJavaVariable( .allFields() .associateWith { field -> if (field.isStatic) refType.getValue(field) else ref.getValue(field) - }.map { (field, value) -> - JavaFieldVariable(thread, ref, refType, field, value) + }.mapNotNull { (field, value) -> + try { + JavaFieldVariable(thread, ref, field, value) + } catch (err: VMDisconnectedException) { + throw err + } catch (err: Throwable) { + logger.error("Failed to create variable wrapper for field {}", field.name(), err) + null + } }.toSet() } ?: emptySet() } @@ -274,14 +281,13 @@ internal class ThisVariable( internal class JavaFieldVariable( thread: ThreadReference, private val ref: ObjectReference, - refType: ReferenceType, private val field: Field, value: Value?, ) : AbstractJavaVariable( thread = thread, name = field.name(), typeName = field.typeName(), - type = refType, + type = field.type(), value = value, ) { companion object { @@ -330,7 +336,7 @@ internal open class JavaLocalVariable( value: Value?, ) : AbstractJavaVariable( thread = thread, - name = kotlinLocalDisplayName(variable.name()), + name = variable.name(), typeName = variable.typeName(), type = variable.type(), value = value, diff --git a/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/debug/utils/KotlinLocals.kt b/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/debug/utils/KotlinLocals.kt index 7f3919cacc..404d82d156 100644 --- a/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/debug/utils/KotlinLocals.kt +++ b/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/debug/utils/KotlinLocals.kt @@ -1,9 +1,7 @@ package com.itsaky.androidide.lsp.java.debug.utils private const val INLINE_MARKER_PREFIX = "\$i\$" -private const val INLINE_RECEIVER_PREFIX = "\$this\$" private const val INLINE_COPY_SUFFIX = "\$iv" -private const val MANGLED_DOLLAR = "_u24" private val SUSPEND_MACHINE_LOCALS = setOf( @@ -19,36 +17,23 @@ private val SUSPEND_MACHINE_LOCALS = * argument) and the suspend state machine's own locals. These carry no meaning for someone reading * their own code, so the variables list hides them. * - * Every local copied out of an inlined body also carries one `$iv` per inlining, so the suffixes come - * off first. Stripping does not separate a library body's locals from the user's own inline-function - * locals -- both arrive suffixed -- so a stdlib internal such as `destination$iv$iv` survives this - * predicate under its unsuffixed name. Telling the two apart needs the Kotlin stratum, which is the - * same limit that applies to `$i$`. + * A marker says what to hide, not whose code is running: `$i$a$` scopes a lambda the user wrote, + * inlined into the user's own class, exactly as `$i$f$` scopes a library body inlined there. + * + * Every local copied out of an inlined body carries one `$iv` per inlining, so the suffixes come off + * before the prefix and set tests -- `$i$f$mapTo$iv$iv` is a marker just as `$i$f$mapTo` is. + * + * The suffix stays on the names that survive, and is deliberately not stripped for display. + * `item$iv$iv` and `destination$iv$iv` are `mapTo`'s loop variable and accumulator, not the user's, + * and the suffix is the only cue marking them so: shown as `item` and `destination` they sit beside + * a user's own `item` with nothing to tell them apart. The cost is that a user's own inline-function + * local reads `started$iv`. Separating the two needs the Kotlin stratum. */ fun isSyntheticKotlinLocal(name: String): Boolean { val base = withoutInlineCopySuffixes(name) return base.startsWith(INLINE_MARKER_PREFIX) || base in SUSPEND_MACHINE_LOCALS } -/** - * The name to show for [name]: the source name for a local copied out of an inlined body, and the - * Kotlin syntax for an inline receiver where one can be recovered. - * - * `$this$map$iv` reads as `this@map`. A lambda receiver is emitted named after the enclosing method's - * synthetic lambda instead -- `$this$direct_u24lambda_u240`, where `_u24` is a mangled `$` -- and no - * label the user could have written is recoverable from it, so that name is left alone rather than - * turned into a `this@` that appears nowhere in their source. - */ -fun kotlinLocalDisplayName(name: String): String { - val base = withoutInlineCopySuffixes(name) - if (!base.startsWith(INLINE_RECEIVER_PREFIX)) { - return base - } - - val label = base.removePrefix(INLINE_RECEIVER_PREFIX) - return if (isSourceLabel(label)) "this@$label" else base -} - /** [name] with every `$iv` the inliner appended removed, one per inlining. */ private fun withoutInlineCopySuffixes(name: String): String { var base = name @@ -57,9 +42,3 @@ private fun withoutInlineCopySuffixes(name: String): String { } return base } - -/** Whether [label] is a name the user could have written, rather than a synthetic lambda's. */ -private fun isSourceLabel(label: String): Boolean = - label.isNotEmpty() && - !label.contains(MANGLED_DOLLAR) && - label.all { it.isLetterOrDigit() || it == '_' } diff --git a/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/debug/utils/Strata.kt b/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/debug/utils/Strata.kt index cf9fb6e228..08e100e242 100644 --- a/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/debug/utils/Strata.kt +++ b/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/debug/utils/Strata.kt @@ -50,6 +50,28 @@ fun Location.sourceNameOrNull(): String? = fun Location.lineNumberInSource(): Int = lineNumber(JAVA_STRATUM) +/** + * This location read in the Kotlin stratum, which is the only one with a multi-file table. + * + * The Java stratum has one `SourceFile` per class, so a body inlined from another file is reported + * under the caller's file name at a synthetic line past its end. The Kotlin stratum names the file + * the code was written in. The two agree outside inlined code. + * + * Placement must stay in the Java stratum ([locationsOfLineInSource]), so these are for display + * only: a position reported here does not round-trip to a breakpoint. + * + * JDI falls back to the declaring type's default stratum when [KOTLIN_STRATUM] is absent, so these + * are safe on a Java class. + */ +fun Location.lineNumberInKotlin(): Int = lineNumber(KOTLIN_STRATUM) + +fun Location.sourceNameInKotlinOrNull(): String? = + try { + sourceName(KOTLIN_STRATUM) + } catch (err: AbsentInformationException) { + null + } + /** * Locations for [line] read in the same stratum [lineNumberInSource] reports in. * diff --git a/lsp/java/src/test/java/com/itsaky/androidide/lsp/java/debug/KotlinLocalsTest.kt b/lsp/java/src/test/java/com/itsaky/androidide/lsp/java/debug/KotlinLocalsTest.kt index 5c2afab308..0377d9f8a0 100644 --- a/lsp/java/src/test/java/com/itsaky/androidide/lsp/java/debug/KotlinLocalsTest.kt +++ b/lsp/java/src/test/java/com/itsaky/androidide/lsp/java/debug/KotlinLocalsTest.kt @@ -18,7 +18,6 @@ package com.itsaky.androidide.lsp.java.debug import com.google.common.truth.Truth.assertThat import com.itsaky.androidide.lsp.java.debug.utils.isSyntheticKotlinLocal -import com.itsaky.androidide.lsp.java.debug.utils.kotlinLocalDisplayName import org.junit.Test class KotlinLocalsTest { @@ -51,32 +50,19 @@ class KotlinLocalsTest { } @Test - fun `a local copied out of an inlined body shows the name its source gave it`() { - assertThat(kotlinLocalDisplayName("started\$iv")).isEqualTo("started") - assertThat(kotlinLocalDisplayName("label\$iv")).isEqualTo("label") - assertThat(kotlinLocalDisplayName("item\$iv\$iv")).isEqualTo("item") + fun `a local copied out of an inlined body is shown, suffix and all`() { + // mapTo's loop variable and accumulator reach the list under these names; the suffix is the + // only cue that they are not the user's, so it is neither hidden nor stripped. + assertThat(isSyntheticKotlinLocal("item\$iv\$iv")).isFalse() + assertThat(isSyntheticKotlinLocal("destination\$iv\$iv")).isFalse() + assertThat(isSyntheticKotlinLocal("started\$iv")).isFalse() } @Test - fun `an inline receiver keeps its label through the copy suffixes`() { + fun `an inline receiver is shown under the name the compiler emitted`() { assertThat(isSyntheticKotlinLocal("\$this\$map\$iv")).isFalse() - assertThat(kotlinLocalDisplayName("\$this\$map\$iv")).isEqualTo("this@map") - assertThat(kotlinLocalDisplayName("\$this\$mapTo\$iv\$iv")).isEqualTo("this@mapTo") - } - - @Test - fun `a synthetic lambda receiver is left alone rather than given a fabricated label`() { - // Kotlin names a lambda's receiver after the enclosing method's synthetic lambda, where _u24 - // is a mangled '$'. No label the user wrote is recoverable from it. - assertThat(kotlinLocalDisplayName("\$this\$direct_u24lambda_u240")) - .isEqualTo("\$this\$direct_u24lambda_u240") - } - - @Test - fun `ordinary names are not renamed`() { - assertThat(kotlinLocalDisplayName("answer")).isEqualTo("answer") - assertThat(kotlinLocalDisplayName("this")).isEqualTo("this") - assertThat(kotlinLocalDisplayName("\$this\$")).isEqualTo("\$this\$") + assertThat(isSyntheticKotlinLocal("\$this\$mapTo\$iv\$iv")).isFalse() + assertThat(isSyntheticKotlinLocal("\$this\$direct_u24lambda_u240")).isFalse() } @Test diff --git a/testing/resources/kotlin-debug-fixture/README.md b/testing/resources/kotlin-debug-fixture/README.md index 4c6679935e..5d3a4f75d0 100644 --- a/testing/resources/kotlin-debug-fixture/README.md +++ b/testing/resources/kotlin-debug-fixture/README.md @@ -58,7 +58,20 @@ While it walks them, the editor is sent the **wrong file**, not only a line past `Greeter.greetAll` carries output lines 60-63, which the SMAP maps to `_Collections.kt:1557` and `1628-1630`, the stdlib `map` body. The Java stratum has one `SourceFile` per class, so those lines are reported as `DebugFixture.kt`: Step Over in `greetAll` walks `27 -> 60 -> 61 -> 62 -> 28` and -asks the editor to highlight `DebugFixture.kt:60` in a 59-line file while execution is really in the +asks the editor to highlight `DebugFixture.kt:60` in a 58-line file while execution is really in the standard library. The `kotlin.*` / `kotlinx.*` step filters do not prevent this, because the inlined body lives in the user's own class and a class-name filter never sees it. Reachable through any `map`, `forEach`, `let` or `run`. + +The call stack disagrees with the editor while that happens, and the call stack is the correct one. +Its rows read the Kotlin stratum, the only stratum with a multi-file table, so the frame reads +`_Collections.kt:1557` while the editor highlights `DebugFixture.kt:60`. Breakpoints are still +placed and reported in the Java stratum, so the row is display-only and does not round-trip to a +breakpoint. Expect the two to differ inside an inlined body and to agree everywhere else. + +The variables list carries a stdlib inline function's own locals alongside the user's. Stopped at +line 28, in the lambda passed to `map`, it shows `item$iv$iv` and `destination$iv$iv` - `mapTo`'s +loop variable and accumulator, not yours. The `$iv` suffix is left on deliberately: it is the only +cue separating them from names the user wrote. The same suffix lands on a user's own inline-function +locals, so stepping through `measured` inlined into `Greeter.timed` shows `started$iv`, `result$iv` +and `label$iv`. Stripping it only where it is safe needs the Kotlin stratum. From fb881d2717d42954202e617836b22a9bf6a28fa6 Mon Sep 17 00:00:00 2001 From: Daniel Alome Date: Mon, 21 Sep 2026 16:45:45 +0100 Subject: [PATCH 06/11] fix: read the KotlinDebug stratum, address review on ADFA-4191 - The editor is sent the KotlinDebug call site inside an inlined body, so stepping through `Greeter.greetAll` highlights `DebugFixture.kt:27` rather than line 60 of a 58-line file. Gated on the Kotlin and Java strata disagreeing, not on a non-positive result: KotlinDebug maps only inline-derived lines and JDI answers an unmapped code index by best match, so a blind read returns an unrelated call site for every ordinary line in a method that inlines anywhere. The call-stack row keeps the Kotlin stratum. - `lineNumberInKotlin` falls back to the Java-stratum line, so a code index the Kotlin stratum does not map no longer renders as `:-1`. - A field whose declared type the VM never loaded keeps its row; the value fetch moved inside the per-field guard; a final field is no longer offered as editable, which no JDI path could have honoured. - `$this$` receivers are filtered, which section 3 asks for and dropping the rename had left undone. - The compiler's own constants replace the hand-copied literals. The `$iv` stripping helper is gone: it could not change the prefix test, and the set test shape it existed for is not attested. - The fixture README records the editor/call-stack split as it now stands and carries the `Steps to QA` text for ADFA-4175. --- .../androidide/lsp/java/debug/Variables.kt | 33 +++++++- .../lsp/java/debug/utils/KotlinLocals.kt | 56 +++++++------- .../lsp/java/debug/utils/ModelUtils.kt | 12 ++- .../androidide/lsp/java/debug/utils/Strata.kt | 59 ++++++++++++-- .../lsp/java/debug/KotlinLocalsTest.kt | 10 ++- .../resources/kotlin-debug-fixture/README.md | 76 ++++++++++++++----- 6 files changed, 187 insertions(+), 59 deletions(-) diff --git a/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/debug/Variables.kt b/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/debug/Variables.kt index 943626f56b..9fb3b4fff8 100644 --- a/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/debug/Variables.kt +++ b/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/debug/Variables.kt @@ -13,6 +13,7 @@ import com.sun.jdi.ArrayType import com.sun.jdi.BooleanType import com.sun.jdi.ByteType import com.sun.jdi.CharType +import com.sun.jdi.ClassNotLoadedException import com.sun.jdi.DoubleType import com.sun.jdi.Field import com.sun.jdi.FloatType @@ -231,10 +232,9 @@ internal abstract class AbstractJavaVariable( return evaluationContext.evaluate(thread) { refType .allFields() - .associateWith { field -> - if (field.isStatic) refType.getValue(field) else ref.getValue(field) - }.mapNotNull { (field, value) -> + .mapNotNull { field -> try { + val value = if (field.isStatic) refType.getValue(field) else ref.getValue(field) JavaFieldVariable(thread, ref, field, value) } catch (err: VMDisconnectedException) { throw err @@ -278,6 +278,24 @@ internal class ThisVariable( } } +/** + * The field's declared type, standing in the owner's type for one the VM has never loaded. + * + * [Field.type] throws [ClassNotLoadedException] for a field whose declared type no code has touched + * yet, which is exactly the case where seeing the row read `null` is informative. An unloaded field + * type is a reference type by definition, so the stand-in classifies the same and leaves + * `VariableValues.canMutate` false. + */ +private fun fieldType( + ref: ObjectReference, + field: Field, +): Type = + try { + field.type() + } catch (err: ClassNotLoadedException) { + ref.referenceType() + } + internal class JavaFieldVariable( thread: ThreadReference, private val ref: ObjectReference, @@ -287,7 +305,7 @@ internal class JavaFieldVariable( thread = thread, name = field.name(), typeName = field.typeName(), - type = field.type(), + type = fieldType(ref, field), value = value, ) { companion object { @@ -296,6 +314,13 @@ internal class JavaFieldVariable( override suspend fun jdiValue() = value + /** + * No JDI path can write a final field: `ObjectReferenceImpl.setValue` and `ClassTypeImpl.setValue` + * both reject one before any JDWP traffic, so offering the edit can only end in a failure message + * blaming the user's input. A Kotlin `val` compiles to a final backing field. + */ + override suspend fun isMutable(): Boolean = !field.isFinal && super.isMutable() + @Suppress("UNCHECKED_CAST") override suspend fun value(): ValueT { if (this.value == null) { diff --git a/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/debug/utils/KotlinLocals.kt b/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/debug/utils/KotlinLocals.kt index 404d82d156..6748294842 100644 --- a/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/debug/utils/KotlinLocals.kt +++ b/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/debug/utils/KotlinLocals.kt @@ -1,44 +1,46 @@ package com.itsaky.androidide.lsp.java.debug.utils +import org.jetbrains.kotlin.codegen.AsmUtil.LABELED_THIS_PARAMETER +import org.jetbrains.kotlin.codegen.coroutines.CONTINUATION_VARIABLE_NAME +import org.jetbrains.kotlin.codegen.coroutines.SUSPEND_CALL_RESULT_NAME +import org.jetbrains.kotlin.codegen.coroutines.SUSPEND_FUNCTION_COMPLETION_PARAMETER_NAME + +/** + * The inline marker prefix. The compiler writes this literal itself and exports no constant for it, + * unlike the other names here. + */ private const val INLINE_MARKER_PREFIX = "\$i\$" -private const val INLINE_COPY_SUFFIX = "\$iv" private val SUSPEND_MACHINE_LOCALS = setOf( - "\$continuation", - "\$result", - "\$completion", + CONTINUATION_VARIABLE_NAME, + SUSPEND_CALL_RESULT_NAME, + SUSPEND_FUNCTION_COMPLETION_PARAMETER_NAME, ) /** * Whether [name] is a local the Kotlin compiler generated rather than one the user wrote. * - * Covers the inline markers (`$i$f$` for an inlined function body, `$i$a$` for an inlined lambda - * argument) and the suspend state machine's own locals. These carry no meaning for someone reading - * their own code, so the variables list hides them. + * Covers the three shapes ADFA-4191 section 3 lists: the inline markers (`$i$f$` for an inlined + * function body, `$i$a$` for an inlined lambda argument), the inline receivers (`$this$`), and the + * suspend state machine's own locals. These carry no meaning for someone reading their own code, so + * the variables list hides them. * * A marker says what to hide, not whose code is running: `$i$a$` scopes a lambda the user wrote, * inlined into the user's own class, exactly as `$i$f$` scopes a library body inlined there. * - * Every local copied out of an inlined body carries one `$iv` per inlining, so the suffixes come off - * before the prefix and set tests -- `$i$f$mapTo$iv$iv` is a marker just as `$i$f$mapTo` is. + * Hiding every `$this$` costs the receiver of a `run`/`apply` block the user wrote, which is a real + * variable under an unwritable name: the compiler emits it as `$this$_u24lambda_u24`, and + * no label a user could have typed is recoverable from that. The alternative was showing `this@map` + * for a stdlib extension receiver, which does not compile anywhere in their source. * - * The suffix stays on the names that survive, and is deliberately not stripped for display. - * `item$iv$iv` and `destination$iv$iv` are `mapTo`'s loop variable and accumulator, not the user's, - * and the suffix is the only cue marking them so: shown as `item` and `destination` they sit beside - * a user's own `item` with nothing to tell them apart. The cost is that a user's own inline-function - * local reads `started$iv`. Separating the two needs the Kotlin stratum. + * The `$iv` an inlining appends is deliberately left on the names that survive. `item$iv$iv` and + * `destination$iv$iv` are `mapTo`'s loop variable and accumulator, not the user's, and the suffix is + * the only cue marking them so: shown as `item` and `destination` they sit beside a user's own + * `item` with nothing to tell them apart. The cost is that a user's own inline-function local reads + * `started$iv`. Separating the two needs the Kotlin stratum. */ -fun isSyntheticKotlinLocal(name: String): Boolean { - val base = withoutInlineCopySuffixes(name) - return base.startsWith(INLINE_MARKER_PREFIX) || base in SUSPEND_MACHINE_LOCALS -} - -/** [name] with every `$iv` the inliner appended removed, one per inlining. */ -private fun withoutInlineCopySuffixes(name: String): String { - var base = name - while (base.length > INLINE_COPY_SUFFIX.length && base.endsWith(INLINE_COPY_SUFFIX)) { - base = base.dropLast(INLINE_COPY_SUFFIX.length) - } - return base -} +fun isSyntheticKotlinLocal(name: String): Boolean = + name.startsWith(INLINE_MARKER_PREFIX) || + name.startsWith(LABELED_THIS_PARAMETER) || + name in SUSPEND_MACHINE_LOCALS diff --git a/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/debug/utils/ModelUtils.kt b/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/debug/utils/ModelUtils.kt index 104ccc6bca..19de7f9bf6 100644 --- a/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/debug/utils/ModelUtils.kt +++ b/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/debug/utils/ModelUtils.kt @@ -82,6 +82,16 @@ fun Location.asLspLocation(useDeclTypeName: Boolean = true): LspLocation { ) } +/** + * The [LspLocation] for a Kotlin location, reported in the file the user can open. + * + * Inside a body inlined from elsewhere the Java-stratum line is a synthetic number past the end of + * the caller's file, so the editor is asked to highlight a line that does not exist. The + * `KotlinDebug` stratum maps that line back to the call site the user wrote, which is a real line in + * this same file and round-trips to a breakpoint. The call-stack row keeps the Kotlin stratum, which + * names the library file the code was written in, so the two disagree inside an inlined body by + * design. + */ private fun Location.asKotlinLspLocation(): LspLocation { val relativePath = sourcePathOrNull() val resolved = relativePath?.let(::resolveInSourceRoots) @@ -102,7 +112,7 @@ private fun Location.asKotlinLspLocation(): LspLocation { return LspLocation( source = source, - line = lineNumberInSource() - 1, + line = (inlineCallSiteLineOrNull() ?: lineNumberInSource()) - 1, column = null, ) } diff --git a/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/debug/utils/Strata.kt b/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/debug/utils/Strata.kt index 08e100e242..1ba43a8907 100644 --- a/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/debug/utils/Strata.kt +++ b/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/debug/utils/Strata.kt @@ -4,14 +4,18 @@ import com.sun.jdi.AbsentInformationException import com.sun.jdi.Location import com.sun.jdi.ObjectCollectedException import com.sun.jdi.ReferenceType +import org.jetbrains.kotlin.codegen.inline.KOTLIN_DEBUG_STRATA_NAME +import org.jetbrains.kotlin.codegen.inline.KOTLIN_STRATA_NAME const val JAVA_STRATUM = "Java" -const val KOTLIN_STRATUM = "Kotlin" + +/** The compiler's placeholder file for generated code, which belongs to no call site. */ +private const val FAKE_SOURCE_NAME = "fake.kt" val ReferenceType.isKotlinType: Boolean get() = try { - availableStrata().contains(KOTLIN_STRATUM) + availableStrata().contains(KOTLIN_STRATA_NAME) } catch (err: AbsentInformationException) { false } catch (err: ObjectCollectedException) { @@ -60,18 +64,61 @@ fun Location.lineNumberInSource(): Int = lineNumber(JAVA_STRATUM) * Placement must stay in the Java stratum ([locationsOfLineInSource]), so these are for display * only: a position reported here does not round-trip to a breakpoint. * - * JDI falls back to the declaring type's default stratum when [KOTLIN_STRATUM] is absent, so these - * are safe on a Java class. + * JDI falls back to the declaring type's default stratum when the Kotlin stratum is absent, so these + * are safe on a Java class. A code index the stratum does not map reads back as -1, which would + * render as `:-1`, so the Java-stratum line stands in for it. */ -fun Location.lineNumberInKotlin(): Int = lineNumber(KOTLIN_STRATUM) +fun Location.lineNumberInKotlin(): Int = lineNumber(KOTLIN_STRATA_NAME).takeIf { it > 0 } ?: lineNumberInSource() fun Location.sourceNameInKotlinOrNull(): String? = try { - sourceName(KOTLIN_STRATUM) + sourceName(KOTLIN_STRATA_NAME) } catch (err: AbsentInformationException) { null } +/** + * The line of this class's own source that produced this location, or null when none did. + * + * `KotlinDebug` maps an inlined body's synthetic output lines back to the call site the user wrote, + * so it is the one stratum that names a position the editor can open and a breakpoint can bind to. + * Its line table covers those lines and nothing else: `SMAPBuilder` builds it solely from mappings + * carrying a call site. + * + * JDI answers an unmapped code index by best match rather than by failing. `ConcreteMethodImpl` + * drops the lines a stratum does not map, then `codeIndexToLineInfo` returns the nearest preceding + * line it kept, so in a method that inlines anywhere a line outside every inlined body reads back as + * some unrelated call site. Gating on [isInlinedBody] rather than on a non-positive result is what + * keeps that out; a method with no inlining at all is the only case that does return -1. + */ +fun Location.inlineCallSiteLineOrNull(): Int? { + if (!isInlinedBody()) { + return null + } + + return try { + lineNumber(KOTLIN_DEBUG_STRATA_NAME).takeIf { it > 0 } + } catch (err: AbsentInformationException) { + null + } +} + +/** + * Whether this location is code inlined into the declaring class from elsewhere. + * + * The Kotlin stratum maps the class's own lines to themselves and writes everything inlined into it + * past the end of that range, so the two strata agree exactly off inlined code. `fake.kt` also reads + * as a foreign file but is generated code rather than an inlining, so it has no call site to find. + */ +private fun Location.isInlinedBody(): Boolean { + val kotlinName = sourceNameInKotlinOrNull() ?: return false + if (kotlinName == FAKE_SOURCE_NAME) { + return false + } + + return kotlinName != sourceNameOrNull() || lineNumberInKotlin() != lineNumberInSource() +} + /** * Locations for [line] read in the same stratum [lineNumberInSource] reports in. * diff --git a/lsp/java/src/test/java/com/itsaky/androidide/lsp/java/debug/KotlinLocalsTest.kt b/lsp/java/src/test/java/com/itsaky/androidide/lsp/java/debug/KotlinLocalsTest.kt index 0377d9f8a0..4b174016f8 100644 --- a/lsp/java/src/test/java/com/itsaky/androidide/lsp/java/debug/KotlinLocalsTest.kt +++ b/lsp/java/src/test/java/com/itsaky/androidide/lsp/java/debug/KotlinLocalsTest.kt @@ -59,10 +59,12 @@ class KotlinLocalsTest { } @Test - fun `an inline receiver is shown under the name the compiler emitted`() { - assertThat(isSyntheticKotlinLocal("\$this\$map\$iv")).isFalse() - assertThat(isSyntheticKotlinLocal("\$this\$mapTo\$iv\$iv")).isFalse() - assertThat(isSyntheticKotlinLocal("\$this\$direct_u24lambda_u240")).isFalse() + fun `inline receivers are synthetic`() { + // map's and mapTo's extension receivers, and the receiver of a lambda the user wrote. No + // label a user could have typed is recoverable from any of them, so all three are hidden. + assertThat(isSyntheticKotlinLocal("\$this\$map\$iv")).isTrue() + assertThat(isSyntheticKotlinLocal("\$this\$mapTo\$iv\$iv")).isTrue() + assertThat(isSyntheticKotlinLocal("\$this\$direct_u24lambda_u240")).isTrue() } @Test diff --git a/testing/resources/kotlin-debug-fixture/README.md b/testing/resources/kotlin-debug-fixture/README.md index 5d3a4f75d0..e1d3e4cdca 100644 --- a/testing/resources/kotlin-debug-fixture/README.md +++ b/testing/resources/kotlin-debug-fixture/README.md @@ -51,23 +51,24 @@ different thread and JDI's step request is thread-scoped, so the step is lost. B suspend bodies still hit. See ADFA-4175. Step Over does not treat an inlined body as one step: it walks the inlined lines the same way it -walks any other. Skipping them needs the Kotlin stratum to tell a library body inlined into the -user's class apart from a lambda the user wrote there, which the inline markers alone cannot do. - -While it walks them, the editor is sent the **wrong file**, not only a line past the end of one. -`Greeter.greetAll` carries output lines 60-63, which the SMAP maps to `_Collections.kt:1557` and -`1628-1630`, the stdlib `map` body. The Java stratum has one `SourceFile` per class, so those lines -are reported as `DebugFixture.kt`: Step Over in `greetAll` walks `27 -> 60 -> 61 -> 62 -> 28` and -asks the editor to highlight `DebugFixture.kt:60` in a 58-line file while execution is really in the -standard library. The `kotlin.*` / `kotlinx.*` step filters do not prevent this, because the inlined -body lives in the user's own class and a class-name filter never sees it. Reachable through any -`map`, `forEach`, `let` or `run`. - -The call stack disagrees with the editor while that happens, and the call stack is the correct one. -Its rows read the Kotlin stratum, the only stratum with a multi-file table, so the frame reads -`_Collections.kt:1557` while the editor highlights `DebugFixture.kt:60`. Breakpoints are still -placed and reported in the Java stratum, so the row is display-only and does not round-trip to a -breakpoint. Expect the two to differ inside an inlined body and to agree everywhere else. +walks any other. `Greeter.greetAll` carries output lines 60-63, the stdlib `map` body inlined into +it, so Step Over from line 27 walks `27 -> 60 -> 61 -> 62 -> 28` and takes four presses to reach the +lambda body. The `kotlin.*` / `kotlinx.*` step filters do not prevent this, because the inlined body +lives in the user's own class and a class-name filter never sees it. Reachable through any `map`, +`forEach`, `let` or `run`. + +The editor stays on a real line throughout. The `KotlinDebug` stratum maps output lines 60-63 back +to `DebugFixture.kt:27`, the `names.map { ... }` call site, and 64-67 back to `DebugFixture.kt:33`, +the `measured("greeter")` call site, so the highlight sits on the call site for each intervening +press instead of moving to line 60 of a 58-line file. Step Over therefore looks like it does nothing +until the press that leaves the inlined body. That is the remaining half of ADFA-4175's inline +stepping item: the position is right, the number of presses is not. + +The call stack disagrees with the editor while that happens, and each is right about a different +question. Its rows read the Kotlin stratum, the only stratum with a multi-file table, so the frame +reads `_Collections.kt:1557` - where the code was written - while the editor highlights +`DebugFixture.kt:27` - where the user wrote the call. Breakpoints are still placed and reported in +the Java stratum. Expect the two to differ inside an inlined body and to agree everywhere else. The variables list carries a stdlib inline function's own locals alongside the user's. Stopped at line 28, in the lambda passed to `map`, it shows `item$iv$iv` and `destination$iv$iv` - `mapTo`'s @@ -75,3 +76,44 @@ loop variable and accumulator, not yours. The `$iv` suffix is left on deliberate cue separating them from names the user wrote. The same suffix lands on a user's own inline-function locals, so stepping through `measured` inlined into `Greeter.timed` shows `started$iv`, `result$iv` and `label$iv`. Stripping it only where it is safe needs the Kotlin stratum. + +The receiver of a `run` or `apply` block is hidden along with the compiler's own. It reaches the +frame as `$this$_u24lambda_u24`, no label a user could have written is recoverable from +that, and ADFA-4191 section 3 asks for `$this$` to be filtered. The object is still reachable under +the name it was called on. + +## Steps to QA + +For ADFA-4175. `acli` cannot write the `Steps to QA` custom field, so this is the text to paste in. + +```gherkin +Given a project made from the Kotlin template with DebugFixture.kt added per Setup +When a breakpoint is set on line 22 and runAll() runs under the debugger +Then execution suspends and the call stack names DebugFixture.kt:22 + +Given execution is suspended on line 27 of DebugFixture.kt +When the user taps Step Over +Then the editor highlight stays within DebugFixture.kt and never a line past 58 +And repeated Step Over reaches line 28 + +Given execution is suspended on line 22 of DebugFixture.kt +When the user taps Step Over on the string template that null-checks name +Then execution does not stop inside kotlin.jvm.internal.Intrinsics + +Given execution is suspended on line 28, inside the lambda passed to map +When the user opens the variables tree +Then no entry whose name starts with $i$, $this$ or $continuation is shown +And the user's own each and greeting are shown + +Given execution is suspended on line 41, inside the anonymous Runnable +When the breakpoint on line 41 is set before Greeter loads +Then the breakpoint still binds and hits + +Given execution is suspended anywhere in DebugFixture.kt +When the user expands this on a Greeter instance +Then the name field is listed and is not offered as editable +``` + +A breakpoint on line 7 is expected **not** to hit; see the line map. A breakpoint inside +`suspending` hits, but stepping across the suspension point does not resume - both are known +limitations above, not QA failures. From 218009c7bbbb179de7f0850bf122ad6500e60e84 Mon Sep 17 00:00:00 2001 From: Daniel Alome Date: Mon, 21 Sep 2026 17:30:08 +0100 Subject: [PATCH 07/11] style: spotless reformat, no functional change --- .../lsp/java/debug/EventConsumer.kt | 42 +- .../androidide/lsp/java/debug/EventHandler.kt | 536 +++++++++--------- 2 files changed, 293 insertions(+), 285 deletions(-) diff --git a/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/debug/EventConsumer.kt b/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/debug/EventConsumer.kt index da26939dbc..4b50d6b6af 100644 --- a/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/debug/EventConsumer.kt +++ b/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/debug/EventConsumer.kt @@ -15,29 +15,37 @@ import com.sun.jdi.event.VMDisconnectEvent import com.sun.jdi.event.VMStartEvent import com.sun.jdi.event.WatchpointEvent - /** * A consumer of JDWP events. */ interface EventConsumer { - fun vmStartEvent(e: VMStartEvent) {} - fun vmDeathEvent(e: VMDeathEvent) {} - fun vmDisconnectEvent(e: VMDisconnectEvent) {} + fun vmStartEvent(e: VMStartEvent) {} + + fun vmDeathEvent(e: VMDeathEvent) {} + + fun vmDisconnectEvent(e: VMDisconnectEvent) {} + + fun threadStartEvent(e: ThreadStartEvent) {} + + fun threadDeathEvent(e: ThreadDeathEvent) {} + + fun classPrepareEvent(e: ClassPrepareEvent) {} + + fun classUnloadEvent(e: ClassUnloadEvent) {} + + fun breakpointEvent(e: BreakpointEvent) {} + + fun fieldWatchEvent(e: WatchpointEvent) {} + + fun stepEvent(e: StepEvent) {} - fun threadStartEvent(e: ThreadStartEvent) {} - fun threadDeathEvent(e: ThreadDeathEvent) {} + fun exceptionEvent(e: ExceptionEvent) {} - fun classPrepareEvent(e: ClassPrepareEvent) {} - fun classUnloadEvent(e: ClassUnloadEvent) {} + fun methodEntryEvent(e: MethodEntryEvent) {} - fun breakpointEvent(e: BreakpointEvent) {} - fun fieldWatchEvent(e: WatchpointEvent) {} - fun stepEvent(e: StepEvent) {} - fun exceptionEvent(e: ExceptionEvent) {} + fun methodExitEvent(e: MethodExitEvent): Boolean = false - fun methodEntryEvent(e: MethodEntryEvent) {} - fun methodExitEvent(e: MethodExitEvent): Boolean = false - fun vmInterrupted() {} + fun vmInterrupted() {} - fun receivedEvent(event: Event) {} -} \ No newline at end of file + fun receivedEvent(event: Event) {} +} diff --git a/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/debug/EventHandler.kt b/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/debug/EventHandler.kt index a129eac02a..fe33a29b60 100644 --- a/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/debug/EventHandler.kt +++ b/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/debug/EventHandler.kt @@ -37,278 +37,278 @@ import org.slf4j.LoggerFactory * @author Akash Yadav */ internal class EventHandler( - private val vm: VirtualMachine, - private val threadState: ThreadState, - private val stopOnVmStart: Boolean, - private val consumer: EventConsumer + private val vm: VirtualMachine, + private val threadState: ThreadState, + private val stopOnVmStart: Boolean, + private val consumer: EventConsumer, ) : AutoCloseable { - - internal val eventRequestSpecList = EventRequestSpecList(vm) - - @Volatile - private var connected = true - private var vmDied = false - private var completed = false - - @OptIn(DelicateCoroutinesApi::class, ExperimentalCoroutinesApi::class) - private val adapterContext = newSingleThreadContext("JDWPEventHandler") - private val adapterScope = CoroutineScope(adapterContext) - private var eventsJob: Job? = null - - companion object { - private val logger = LoggerFactory.getLogger(EventHandler::class.java) - } - - /** - * Run the event handler. - */ - fun startListening() { - eventsJob = adapterScope.launch { - val job = coroutineContext.job - val queue = vm.eventQueue() - while (connected && job.isActive && !job.isCancelled) { - try { - val events = queue.remove() - var resumeVm = false - for (event in events.eventIterator()) { - logger.info("startListening: received event: {}", event) - val stopForEvent = handleEvent(event) - logger.info( - "startListening: handled event: {}, resumeVm={}, stopForEvent={}", - event, - resumeVm, - stopForEvent - ) - - resumeVm = resumeVm || !stopForEvent - } - - if (resumeVm) { - logger.debug("resuming VM") - events.resume() - } else if (events.suspendPolicy() == EventRequest.SUSPEND_ALL) { - // notify consumer that the VM has interrupted - logger.info("startListening: VM interrupted") - setCurrentThread(events) - consumer.vmInterrupted() - } - } catch (interrupt: InterruptedException) { - logger.debug("event handler interrupted") - // Ignore, changes will be seen at top of the loop - } catch (err: VMDisconnectedException) { - handleDisconnectedException() - } - } - - completed = true - eventsJob = null - logger.info("EventHandler completed") - } - } - - private fun setCurrentThread(set: EventSet) { - val thread: ThreadReference? - if (set.size > 0) { - /* - * If any event in the set has a thread associated with it, - * they all will, so just grab the first one. - */ - val event = set.iterator().next() // Is there a better way? - thread = eventThread(event) - } else { - thread = null - } - setCurrentThread(thread) - } - - private fun setCurrentThread(thread: ThreadReference?) { - threadState.invalidateAll() - threadState.setCurrentThread(thread) - } - - /** - * Handle the event. - * - * @param event The event to handle. - * @return `true` if the VM should be stopped, false otherwise. - */ - private fun handleEvent(event: Event): Boolean { - consumer.receivedEvent(event) - - return when (event) { - is ExceptionEvent -> exceptionEvent(event) - is BreakpointEvent -> breakpointEvent(event) - is WatchpointEvent -> fieldWatchEvent(event) - is StepEvent -> stepEvent(event) - is MethodEntryEvent -> methodEntryEvent(event) - is MethodExitEvent -> methodExitEvent(event) - is ClassPrepareEvent -> classPrepareEvent(event) - is ClassUnloadEvent -> classUnloadEvent(event) - is ThreadStartEvent -> threadStartEvent(event) - is ThreadDeathEvent -> threadDeathEvent(event) - is VMStartEvent -> vmStartEvent(event) - else -> handleExitEvent(event) - } - } - - /** - * @see [handleEvent] - */ - private fun vmStartEvent(event: VMStartEvent): Boolean { - consumer.vmStartEvent(event) - return stopOnVmStart - } - - /** - * @see [handleEvent] - */ - private fun breakpointEvent(event: BreakpointEvent): Boolean { - consumer.breakpointEvent(event) - return true - } - - /** - * @see [handleEvent] - */ - private fun methodEntryEvent(event: MethodEntryEvent): Boolean { - consumer.methodEntryEvent(event) - return true - } - - /** - * @see [handleEvent] - */ - private fun methodExitEvent(event: MethodExitEvent): Boolean { - return consumer.methodExitEvent(event) - } - - /** - * @see [handleEvent] - */ - private fun fieldWatchEvent(event: WatchpointEvent): Boolean { - consumer.fieldWatchEvent(event) - return true - } - - /** - * @see [handleEvent] - */ - private fun stepEvent(event: StepEvent): Boolean { - consumer.stepEvent(event) - return true - } - - /** - * @see [handleEvent] - */ - private fun classPrepareEvent(event: ClassPrepareEvent): Boolean { - consumer.classPrepareEvent(event) + internal val eventRequestSpecList = EventRequestSpecList(vm) + + @Volatile + private var connected = true + private var vmDied = false + private var completed = false + + @OptIn(DelicateCoroutinesApi::class, ExperimentalCoroutinesApi::class) + private val adapterContext = newSingleThreadContext("JDWPEventHandler") + private val adapterScope = CoroutineScope(adapterContext) + private var eventsJob: Job? = null + + companion object { + private val logger = LoggerFactory.getLogger(EventHandler::class.java) + } + + /** + * Run the event handler. + */ + fun startListening() { + eventsJob = + adapterScope.launch { + val job = coroutineContext.job + val queue = vm.eventQueue() + while (connected && job.isActive && !job.isCancelled) { + try { + val events = queue.remove() + var resumeVm = false + for (event in events.eventIterator()) { + logger.info("startListening: received event: {}", event) + val stopForEvent = handleEvent(event) + logger.info( + "startListening: handled event: {}, resumeVm={}, stopForEvent={}", + event, + resumeVm, + stopForEvent, + ) + + resumeVm = resumeVm || !stopForEvent + } + + if (resumeVm) { + logger.debug("resuming VM") + events.resume() + } else if (events.suspendPolicy() == EventRequest.SUSPEND_ALL) { + // notify consumer that the VM has interrupted + logger.info("startListening: VM interrupted") + setCurrentThread(events) + consumer.vmInterrupted() + } + } catch (interrupt: InterruptedException) { + logger.debug("event handler interrupted") + // Ignore, changes will be seen at top of the loop + } catch (err: VMDisconnectedException) { + handleDisconnectedException() + } + } + + completed = true + eventsJob = null + logger.info("EventHandler completed") + } + } + + private fun setCurrentThread(set: EventSet) { + val thread: ThreadReference? + if (set.size > 0) { + /* + * If any event in the set has a thread associated with it, + * they all will, so just grab the first one. + */ + val event = set.iterator().next() // Is there a better way? + thread = eventThread(event) + } else { + thread = null + } + setCurrentThread(thread) + } + + private fun setCurrentThread(thread: ThreadReference?) { + threadState.invalidateAll() + threadState.setCurrentThread(thread) + } + + /** + * Handle the event. + * + * @param event The event to handle. + * @return `true` if the VM should be stopped, false otherwise. + */ + private fun handleEvent(event: Event): Boolean { + consumer.receivedEvent(event) + + return when (event) { + is ExceptionEvent -> exceptionEvent(event) + is BreakpointEvent -> breakpointEvent(event) + is WatchpointEvent -> fieldWatchEvent(event) + is StepEvent -> stepEvent(event) + is MethodEntryEvent -> methodEntryEvent(event) + is MethodExitEvent -> methodExitEvent(event) + is ClassPrepareEvent -> classPrepareEvent(event) + is ClassUnloadEvent -> classUnloadEvent(event) + is ThreadStartEvent -> threadStartEvent(event) + is ThreadDeathEvent -> threadDeathEvent(event) + is VMStartEvent -> vmStartEvent(event) + else -> handleExitEvent(event) + } + } + + /** + * @see [handleEvent] + */ + private fun vmStartEvent(event: VMStartEvent): Boolean { + consumer.vmStartEvent(event) + return stopOnVmStart + } + + /** + * @see [handleEvent] + */ + private fun breakpointEvent(event: BreakpointEvent): Boolean { + consumer.breakpointEvent(event) + return true + } + + /** + * @see [handleEvent] + */ + private fun methodEntryEvent(event: MethodEntryEvent): Boolean { + consumer.methodEntryEvent(event) + return true + } + + /** + * @see [handleEvent] + */ + private fun methodExitEvent(event: MethodExitEvent): Boolean = consumer.methodExitEvent(event) + + /** + * @see [handleEvent] + */ + private fun fieldWatchEvent(event: WatchpointEvent): Boolean { + consumer.fieldWatchEvent(event) + return true + } + + /** + * @see [handleEvent] + */ + private fun stepEvent(event: StepEvent): Boolean { + consumer.stepEvent(event) + return true + } + + /** + * @see [handleEvent] + */ + private fun classPrepareEvent(event: ClassPrepareEvent): Boolean { + consumer.classPrepareEvent(event) val success = eventRequestSpecList.resolve(event) if (!success) { logger.error("Error resolving event request for event: $event") } return false - } - - - /** - * @see [handleEvent] - */ - private fun classUnloadEvent(event: ClassUnloadEvent): Boolean { - consumer.classUnloadEvent(event) - return false - } - - /** - * @see [handleEvent] - */ - private fun exceptionEvent(event: ExceptionEvent): Boolean { - consumer.exceptionEvent(event) - return true - } - - /** - * @see [handleEvent] - */ - private fun threadStartEvent(event: ThreadStartEvent): Boolean { - threadState.addThread(event.thread()) - consumer.threadStartEvent(event) - return false - } - - /** - * @see [handleEvent] - */ - private fun threadDeathEvent(event: ThreadDeathEvent): Boolean { - threadState.addThread(event.thread()) - consumer.threadDeathEvent(event) - return false - } - - private fun eventThread(event: Event) = when (event) { - is ClassPrepareEvent -> event.thread() - is LocatableEvent -> event.thread() - is ThreadStartEvent -> event.thread() - is ThreadDeathEvent -> event.thread() - is VMStartEvent -> event.thread() - else -> null - } - - @Synchronized - private fun handleDisconnectedException() { - // Flush the event queue. Dealing only with vm death or disconnection to ensure - // proper termination of this handler - - val queue = vm.eventQueue() - while (connected) { - try { - val eventSet = queue.remove() - val iter = eventSet.eventIterator() - while (iter.hasNext()) { - handleExitEvent(iter.next()) - } - } catch (exc: InterruptedException) { - // ignore - } catch (exc: InternalError) { - // ignore - } - } - } - - private fun handleExitEvent(event: Event): Boolean { - when (event) { - is VMDeathEvent -> { - vmDied = true - return vmDeathEvent(event) - } - - is VMDisconnectEvent -> { - connected = false - if (!vmDied) { - vmDisconnectEvent(event) - } - - return false - } - - else -> throw IllegalArgumentException("Unknown event type: $event") - } - } - - private fun vmDeathEvent(event: VMDeathEvent): Boolean { - consumer.vmDeathEvent(event) - return false - } - - private fun vmDisconnectEvent(event: VMDisconnectEvent): Boolean { - consumer.vmDisconnectEvent(event) - return false - } - - override fun close() { - connected = false - eventsJob?.cancel(CancellationException("EventHandler closed")) - eventsJob = null - } -} \ No newline at end of file + } + + /** + * @see [handleEvent] + */ + private fun classUnloadEvent(event: ClassUnloadEvent): Boolean { + consumer.classUnloadEvent(event) + return false + } + + /** + * @see [handleEvent] + */ + private fun exceptionEvent(event: ExceptionEvent): Boolean { + consumer.exceptionEvent(event) + return true + } + + /** + * @see [handleEvent] + */ + private fun threadStartEvent(event: ThreadStartEvent): Boolean { + threadState.addThread(event.thread()) + consumer.threadStartEvent(event) + return false + } + + /** + * @see [handleEvent] + */ + private fun threadDeathEvent(event: ThreadDeathEvent): Boolean { + threadState.addThread(event.thread()) + consumer.threadDeathEvent(event) + return false + } + + private fun eventThread(event: Event) = + when (event) { + is ClassPrepareEvent -> event.thread() + is LocatableEvent -> event.thread() + is ThreadStartEvent -> event.thread() + is ThreadDeathEvent -> event.thread() + is VMStartEvent -> event.thread() + else -> null + } + + @Synchronized + private fun handleDisconnectedException() { + // Flush the event queue. Dealing only with vm death or disconnection to ensure + // proper termination of this handler + + val queue = vm.eventQueue() + while (connected) { + try { + val eventSet = queue.remove() + val iter = eventSet.eventIterator() + while (iter.hasNext()) { + handleExitEvent(iter.next()) + } + } catch (exc: InterruptedException) { + // ignore + } catch (exc: InternalError) { + // ignore + } + } + } + + private fun handleExitEvent(event: Event): Boolean { + when (event) { + is VMDeathEvent -> { + vmDied = true + return vmDeathEvent(event) + } + + is VMDisconnectEvent -> { + connected = false + if (!vmDied) { + vmDisconnectEvent(event) + } + + return false + } + + else -> { + throw IllegalArgumentException("Unknown event type: $event") + } + } + } + + private fun vmDeathEvent(event: VMDeathEvent): Boolean { + consumer.vmDeathEvent(event) + return false + } + + private fun vmDisconnectEvent(event: VMDisconnectEvent): Boolean { + consumer.vmDisconnectEvent(event) + return false + } + + override fun close() { + connected = false + eventsJob?.cancel(CancellationException("EventHandler closed")) + eventsJob = null + } +} From 93481809d73a01c634bd15f265d9bd55de5b47c6 Mon Sep 17 00:00:00 2001 From: Daniel Alome Date: Mon, 21 Sep 2026 17:30:50 +0100 Subject: [PATCH 08/11] feat: step through an inlined body in one press, ADFA-4191 AC1 An inline function's body compiles into its caller, so line stepping walked it one line at a time and stopped on lines the user never wrote. A step that lands inside an inlined body now issues its own step and reports nothing, until the thread leaves the region or a 64-step budget runs out. Against the compiled fixture, `Greeter.greetAll` really walks `27 -> 60 -> 61 -> 62 -> 28 -> 29 -> 62 -> 63 -> 60 -> 30` and the user sees `27 -> 28 -> 29 -> 30`; `Greeter.timed` reports `33 -> 34 -> 35 -> 36`. Each press lands on the next line of the same Kotlin file, which is AC1. The three defects that sank the earlier attempt are addressed rather than carried over: - The continuation is always `STEP_OVER`, whatever depth the user asked for. An inlined body has no frame of its own, so `STEP_OUT` popped a real frame per iteration. - It suspends only the event thread, and returning `false` from the consumer leaves the resume to `EventHandler`, so every suspend is matched by one under the same policy instead of accumulating a VM-wide count the user's Resume can never pay off. - The budget rides on the `StepRequest` via `putProperty` rather than on the adapter, so two threads stepping at once cannot spend each other's and there is no shared mutable field to publish. `EventConsumer.stepEvent` returns `Boolean` for this, as `methodExitEvent` already did. --- .../lsp/java/debug/EventConsumer.kt | 2 +- .../androidide/lsp/java/debug/EventHandler.kt | 5 +- .../lsp/java/debug/JavaDebugAdapter.kt | 111 +++++++++++++++--- .../resources/kotlin-debug-fixture/README.md | 42 ++++--- 4 files changed, 119 insertions(+), 41 deletions(-) diff --git a/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/debug/EventConsumer.kt b/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/debug/EventConsumer.kt index 4b50d6b6af..6e3ebb182f 100644 --- a/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/debug/EventConsumer.kt +++ b/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/debug/EventConsumer.kt @@ -37,7 +37,7 @@ interface EventConsumer { fun fieldWatchEvent(e: WatchpointEvent) {} - fun stepEvent(e: StepEvent) {} + fun stepEvent(e: StepEvent): Boolean = true fun exceptionEvent(e: ExceptionEvent) {} diff --git a/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/debug/EventHandler.kt b/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/debug/EventHandler.kt index fe33a29b60..3f8c9d8874 100644 --- a/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/debug/EventHandler.kt +++ b/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/debug/EventHandler.kt @@ -191,10 +191,7 @@ internal class EventHandler( /** * @see [handleEvent] */ - private fun stepEvent(event: StepEvent): Boolean { - consumer.stepEvent(event) - return true - } + private fun stepEvent(event: StepEvent): Boolean = consumer.stepEvent(event) /** * @see [handleEvent] diff --git a/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/debug/JavaDebugAdapter.kt b/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/debug/JavaDebugAdapter.kt index b8eae7dc53..70867ddfc7 100644 --- a/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/debug/JavaDebugAdapter.kt +++ b/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/debug/JavaDebugAdapter.kt @@ -28,12 +28,14 @@ import com.itsaky.androidide.lsp.java.debug.spec.BreakpointSpec import com.itsaky.androidide.lsp.java.debug.utils.asDepthInt import com.itsaky.androidide.lsp.java.debug.utils.asJdiInt import com.itsaky.androidide.lsp.java.debug.utils.asLspLocation +import com.itsaky.androidide.lsp.java.debug.utils.inlineCallSiteLineOrNull import com.itsaky.androidide.lsp.java.debug.utils.isKotlinSource import com.itsaky.androidide.lsp.java.debug.utils.kotlinBinaryNamesOf import com.itsaky.androidide.projects.ProjectManagerImpl import com.itsaky.androidide.projects.api.ModuleProject import com.itsaky.androidide.utils.withStopWatch import com.sun.jdi.Bootstrap +import com.sun.jdi.Location import com.sun.jdi.ThreadReference import com.sun.jdi.VMDisconnectedException import com.sun.jdi.VirtualMachine @@ -93,6 +95,16 @@ internal class JavaDebugAdapter : "kotlinx.*", ) + /** + * The most silent steps taken to leave one inlined body, after which the thread stops where + * it is. A bound is needed because an inlined body's length is the callee's, not the + * caller's, and a pathological one would otherwise hold the UI. + */ + private const val MAX_INLINE_STEPS = 64 + + /** Key for the silent-step budget carried on a continuation [StepRequest]. */ + private const val INLINE_STEP_BUDGET = "inlineStepBudget" + /** * Get the current instance of the [JavaDebugAdapter]. */ @@ -452,22 +464,15 @@ internal class JavaDebugAdapter : logger.debug("Step {} thread {}", request.type, suspendedThread.thread.name()) - clearPreviousStep(vm.vm, suspendedThread.thread) - - val reqMgr = vm.vm.eventRequestManager() val req = - reqMgr.createStepRequest( - suspendedThread.thread, - StepRequest.STEP_LINE, - request.type.asDepthInt(), + createStepRequest( + vm = vm.vm, + thread = suspendedThread.thread, + depth = request.type.asDepthInt(), + suspendPolicy = EventRequest.SUSPEND_ALL, + countFilter = request.countFilter, ) - for (pattern in DEFAULT_CLASS_EXCLUSION_FILTERS) { - req.addClassExclusionFilter(pattern) - } - - req.setSuspendPolicy(EventRequest.SUSPEND_ALL) - req.addCountFilter(request.countFilter) req.enable() suspendedThread.thread.resume() vm.threadState.invalidateAll() @@ -519,6 +524,31 @@ internal class JavaDebugAdapter : } } + private fun createStepRequest( + vm: VirtualMachine, + thread: ThreadReference, + depth: Int, + suspendPolicy: Int, + countFilter: Int, + ): StepRequest { + clearPreviousStep(vm, thread) + + val req = + vm.eventRequestManager().createStepRequest( + thread, + StepRequest.STEP_LINE, + depth, + ) + + for (pattern in DEFAULT_CLASS_EXCLUSION_FILTERS) { + req.addClassExclusionFilter(pattern) + } + + req.setSuspendPolicy(suspendPolicy) + req.addCountFilter(countFilter) + return req + } + private fun clearPreviousStep( vm: VirtualMachine, thread: ThreadReference, @@ -556,7 +586,7 @@ internal class JavaDebugAdapter : ) } - override fun stepEvent(e: StepEvent) { + override fun stepEvent(e: StepEvent): Boolean { logger.debug("stepEvent: {}", e) e.virtualMachine().checkIsCurrentVm() @@ -564,6 +594,10 @@ internal class JavaDebugAdapter : val location = e.location() val thread = e.thread() + if (stepOnThroughInlinedBody(vm.vm, e, location, thread)) { + return false + } + listenerState.client.onStep( event = LspStepEvent( @@ -572,6 +606,55 @@ internal class JavaDebugAdapter : threadId = thread.uniqueID().toString(), ), ) + + return true + } + + /** + * Step on without reporting when a step lands inside a body inlined from elsewhere. + * + * An inline function's body compiles into its caller, so line stepping walks it one line at a + * time and every one of those lines is a position the user never wrote. Continuing until the + * thread leaves the inlined region is what makes Step Over cost one press per call rather than + * one per line of the callee. + * + * The continuation is always [StepRequest.STEP_OVER] whatever the user asked for, because an + * inlined body has no frame of its own and [StepRequest.STEP_OUT] would pop the caller's real + * frame on every iteration. It suspends only the event thread, since nothing else needs the world + * stopped between silent iterations, and returning `false` leaves the resume to [EventHandler] so + * every suspend is matched by one under the same policy. The budget rides on the request rather + * than on the adapter, so two threads stepping at once cannot spend each other's. + * + * @return whether a continuation was issued, in which case nothing is reported to the client. + */ + private fun stepOnThroughInlinedBody( + vm: VirtualMachine, + e: StepEvent, + location: Location, + thread: ThreadReference, + ): Boolean { + if (location.inlineCallSiteLineOrNull() == null) { + return false + } + + val taken = (e.request().getProperty(INLINE_STEP_BUDGET) as? Int) ?: 0 + if (taken >= MAX_INLINE_STEPS) { + logger.warn("Stopping in an inlined body after {} steps at {}", taken, location) + return false + } + + val req = + createStepRequest( + vm = vm, + thread = thread, + depth = StepRequest.STEP_OVER, + suspendPolicy = EventRequest.SUSPEND_EVENT_THREAD, + countFilter = 1, + ) + + req.putProperty(INLINE_STEP_BUDGET, taken + 1) + req.enable() + return true } override fun vmDisconnectEvent(e: VMDisconnectEvent) { diff --git a/testing/resources/kotlin-debug-fixture/README.md b/testing/resources/kotlin-debug-fixture/README.md index e1d3e4cdca..4e4f573b3c 100644 --- a/testing/resources/kotlin-debug-fixture/README.md +++ b/testing/resources/kotlin-debug-fixture/README.md @@ -50,25 +50,23 @@ Stepping across a coroutine suspension point does not work. A suspend function r different thread and JDI's step request is thread-scoped, so the step is lost. Breakpoints inside suspend bodies still hit. See ADFA-4175. -Step Over does not treat an inlined body as one step: it walks the inlined lines the same way it -walks any other. `Greeter.greetAll` carries output lines 60-63, the stdlib `map` body inlined into -it, so Step Over from line 27 walks `27 -> 60 -> 61 -> 62 -> 28` and takes four presses to reach the -lambda body. The `kotlin.*` / `kotlinx.*` step filters do not prevent this, because the inlined body -lives in the user's own class and a class-name filter never sees it. Reachable through any `map`, -`forEach`, `let` or `run`. - -The editor stays on a real line throughout. The `KotlinDebug` stratum maps output lines 60-63 back -to `DebugFixture.kt:27`, the `names.map { ... }` call site, and 64-67 back to `DebugFixture.kt:33`, -the `measured("greeter")` call site, so the highlight sits on the call site for each intervening -press instead of moving to line 60 of a 58-line file. Step Over therefore looks like it does nothing -until the press that leaves the inlined body. That is the remaining half of ADFA-4175's inline -stepping item: the position is right, the number of presses is not. - -The call stack disagrees with the editor while that happens, and each is right about a different -question. Its rows read the Kotlin stratum, the only stratum with a multi-file table, so the frame -reads `_Collections.kt:1557` - where the code was written - while the editor highlights -`DebugFixture.kt:27` - where the user wrote the call. Breakpoints are still placed and reported in -the Java stratum. Expect the two to differ inside an inlined body and to agree everywhere else. +Step Over treats an inlined body as part of the call that produced it. `Greeter.greetAll` carries +output lines 60-63, the stdlib `map` body inlined into it, so the thread really walks +`27 -> 60 -> 61 -> 62 -> 28`, but 60-63 are stepped through without being reported and the user sees +`27 -> 28 -> 29 -> 30`. `Greeter.timed` behaves the same way over the `measured` body it inlines at +64-67, reporting `33 -> 34 -> 35 -> 36`. The `kotlin.*` / `kotlinx.*` step filters play no part in +this: an inlined body lives in the user's own class, so a class-name filter never sees it. + +A landing counts as inlined when the Kotlin and Java strata disagree about it, and the continuation +is capped at 64 silent steps per press. Past the cap the thread stops where it is, which is the one +way a step can still come to rest inside an inlined body. + +When it does, the editor and the call stack disagree, and each is right about a different question. +The editor is sent the `KotlinDebug` position - `DebugFixture.kt:27` for output lines 60-63, the +`names.map { ... }` call site - which is a real line it can open and a breakpoint can bind to. The +call-stack row reads the Kotlin stratum, the only one with a multi-file table, so it reads +`_Collections.kt:1557`, where the code was written. Breakpoints are still placed and reported in the +Java stratum. Expect the two to differ inside an inlined body and to agree everywhere else. The variables list carries a stdlib inline function's own locals alongside the user's. Stopped at line 28, in the lambda passed to `map`, it shows `item$iv$iv` and `destination$iv$iv` - `mapTo`'s @@ -92,9 +90,9 @@ When a breakpoint is set on line 22 and runAll() runs under the debugger Then execution suspends and the call stack names DebugFixture.kt:22 Given execution is suspended on line 27 of DebugFixture.kt -When the user taps Step Over -Then the editor highlight stays within DebugFixture.kt and never a line past 58 -And repeated Step Over reaches line 28 +When the user taps Step Over once +Then execution suspends on line 28, the lambda body +And no line past 58 is shown at any point Given execution is suspended on line 22 of DebugFixture.kt When the user taps Step Over on the string template that null-checks name From 9fb58628a70aa72d69155e2f97d30cf21aa2b283 Mon Sep 17 00:00:00 2001 From: Daniel Alome Date: Mon, 21 Sep 2026 23:39:21 +0100 Subject: [PATCH 09/11] fix: keep the inline step continuation on SUSPEND_ALL On-device QA wedged the debugger after the first inline skip: Step Over from line 27 correctly reported line 28, and every step after that failed with IllegalStateException: No thread is currently suspended `EventHandler` records the suspended thread in exactly one place, and only for a set that suspended everything: } else if (events.suspendPolicy() == EventRequest.SUSPEND_ALL) { setCurrentThread(events) consumer.vmInterrupted() } The continuation was `SUSPEND_EVENT_THREAD`, so the step it finally stopped on took neither branch: `threadState.current` stayed null and `step()` rejected every later request. The asymmetry that suggestion was meant to avoid is already handled by returning `false` and letting `EventHandler` resume the set, so the policy can stay `SUSPEND_ALL`: each silent iteration's VM-wide suspend is matched by the resume of that same set, and the final stop leaves the thread suspended exactly as a breakpoint does. --- .../androidide/lsp/java/debug/JavaDebugAdapter.kt | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/debug/JavaDebugAdapter.kt b/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/debug/JavaDebugAdapter.kt index 70867ddfc7..fb86610467 100644 --- a/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/debug/JavaDebugAdapter.kt +++ b/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/debug/JavaDebugAdapter.kt @@ -620,11 +620,16 @@ internal class JavaDebugAdapter : * * The continuation is always [StepRequest.STEP_OVER] whatever the user asked for, because an * inlined body has no frame of its own and [StepRequest.STEP_OUT] would pop the caller's real - * frame on every iteration. It suspends only the event thread, since nothing else needs the world - * stopped between silent iterations, and returning `false` leaves the resume to [EventHandler] so - * every suspend is matched by one under the same policy. The budget rides on the request rather + * frame on every iteration. Returning `false` leaves the resume to [EventHandler], so each silent + * iteration's suspend is matched by the resume of the same event set rather than accumulating a + * VM-wide count that only the user's Resume could pay off. The budget rides on the request rather * than on the adapter, so two threads stepping at once cannot spend each other's. * + * The policy stays [EventRequest.SUSPEND_ALL]: [EventHandler] records the suspended thread only + * for a set with that policy, so a continuation that suspended just the event thread would leave + * `threadState.current` null and every later [step] would fail with "No thread is currently + * suspended". + * * @return whether a continuation was issued, in which case nothing is reported to the client. */ private fun stepOnThroughInlinedBody( @@ -648,7 +653,7 @@ internal class JavaDebugAdapter : vm = vm, thread = thread, depth = StepRequest.STEP_OVER, - suspendPolicy = EventRequest.SUSPEND_EVENT_THREAD, + suspendPolicy = EventRequest.SUSPEND_ALL, countFilter = 1, ) From f83fb3adb1ed62ec2f4dd29cc158afc5d2729747 Mon Sep 17 00:00:00 2001 From: Daniel Alome Date: Tue, 22 Sep 2026 16:10:59 +0100 Subject: [PATCH 10/11] fix: let Step Into enter an inline body, address review on ADFA-4191 - The inlined-body skip ignored the step depth, so Step Into could never reach an `inline fun` body: the continuation always issued `STEP_OVER`. With a breakpoint on such a body not binding at the inlined call sites either, an `inline fun` was undebuggable end to end. A `STEP_INTO` request is now left alone, which is the other half of ADFA-4191 section 2. - `LocalVariable.type()` throws `ClassNotLoadedException` exactly as `Field.type()` does, and the locals path had no stand-in, so a local whose declared type the VM never loaded was dropped from the panel rather than listed as null. `localType` mirrors `fieldType`, and covers `forVariable`'s own call as well as the constructor's. - The `$this$` filter missed the declaration-site receivers. A member inline function leaves its receiver behind as the bare `this_`, which shares no prefix with the `$this` family. `this_` is matched exactly or with its `$iv` copies, so a local the user named `this_count` is kept. - `EventHandler` accumulated the resume rather than the stop, so one event asking to resume beat another asking to stop. Not reachable while a breakpoint cannot bind inside an inlined body, but the polarity is wrong either way. - `fake.kt` was a hand-copied literal; it is `SourceMapper.FAKE_FILE_NAME`, on the classpath the two stratum names already come from. - `isInlinedBody` is extracted over the four values it reads and tested directly: same file and line, same file different line, different file, `fake.kt`, and no Kotlin name. The same-file case is the one the gate would lose if it were ever simplified to a `KotlinDebug` read alone. - `EventConsumer.stepEvent`'s new `Boolean` says what it means, and a frame with no source name renders `:27` rather than `:27`. --- .../lsp/java/debug/EventConsumer.kt | 5 ++ .../androidide/lsp/java/debug/EventHandler.kt | 13 +-- .../lsp/java/debug/JavaDebugAdapter.kt | 8 ++ .../lsp/java/debug/LspThreadInfo.kt | 2 +- .../androidide/lsp/java/debug/Variables.kt | 22 ++++- .../lsp/java/debug/utils/KotlinLocals.kt | 26 ++++-- .../androidide/lsp/java/debug/utils/Strata.kt | 29 ++++-- .../lsp/java/debug/KotlinLocalsTest.kt | 17 ++++ .../androidide/lsp/java/debug/StrataTest.kt | 88 +++++++++++++++++++ 9 files changed, 192 insertions(+), 18 deletions(-) create mode 100644 lsp/java/src/test/java/com/itsaky/androidide/lsp/java/debug/StrataTest.kt diff --git a/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/debug/EventConsumer.kt b/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/debug/EventConsumer.kt index 6e3ebb182f..c5c5e0e649 100644 --- a/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/debug/EventConsumer.kt +++ b/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/debug/EventConsumer.kt @@ -37,6 +37,11 @@ interface EventConsumer { fun fieldWatchEvent(e: WatchpointEvent) {} + /** + * Called for a step event. + * + * @return `true` to keep the VM suspended for this event, `false` to let it resume. + */ fun stepEvent(e: StepEvent): Boolean = true fun exceptionEvent(e: ExceptionEvent) {} diff --git a/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/debug/EventHandler.kt b/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/debug/EventHandler.kt index 3f8c9d8874..11bc795056 100644 --- a/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/debug/EventHandler.kt +++ b/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/debug/EventHandler.kt @@ -69,21 +69,24 @@ internal class EventHandler( while (connected && job.isActive && !job.isCancelled) { try { val events = queue.remove() - var resumeVm = false + // A stop from any event in the set wins over a resume from any other: a + // composite can pair a silently handled event with one the client is told + // about, and resuming then runs the app while the IDE shows it paused. + var stopForSet = false for (event in events.eventIterator()) { logger.info("startListening: received event: {}", event) val stopForEvent = handleEvent(event) logger.info( - "startListening: handled event: {}, resumeVm={}, stopForEvent={}", + "startListening: handled event: {}, stopForSet={}, stopForEvent={}", event, - resumeVm, + stopForSet, stopForEvent, ) - resumeVm = resumeVm || !stopForEvent + stopForSet = stopForSet || stopForEvent } - if (resumeVm) { + if (!stopForSet) { logger.debug("resuming VM") events.resume() } else if (events.suspendPolicy() == EventRequest.SUSPEND_ALL) { diff --git a/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/debug/JavaDebugAdapter.kt b/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/debug/JavaDebugAdapter.kt index fb86610467..1865fa14c0 100644 --- a/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/debug/JavaDebugAdapter.kt +++ b/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/debug/JavaDebugAdapter.kt @@ -630,6 +630,10 @@ internal class JavaDebugAdapter : * `threadState.current` null and every later [step] would fail with "No thread is currently * suspended". * + * A [StepRequest.STEP_INTO] is left alone: the user asked to enter the callee, and for an inline + * function the body is the callee. Skipping it would make an `inline fun` undebuggable, since a + * breakpoint on its body does not bind at the inlined call sites either. + * * @return whether a continuation was issued, in which case nothing is reported to the client. */ private fun stepOnThroughInlinedBody( @@ -638,6 +642,10 @@ internal class JavaDebugAdapter : location: Location, thread: ThreadReference, ): Boolean { + if ((e.request() as? StepRequest)?.depth() == StepRequest.STEP_INTO) { + return false + } + if (location.inlineCallSiteLineOrNull() == null) { return false } diff --git a/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/debug/LspThreadInfo.kt b/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/debug/LspThreadInfo.kt index d13363139c..ababb6be03 100644 --- a/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/debug/LspThreadInfo.kt +++ b/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/debug/LspThreadInfo.kt @@ -31,7 +31,7 @@ class JavaStackFrame( val frame: StackFrame, val location: Location = frame.location(), val method: Method? = location.method(), - val sourceName: String = location.sourceNameInKotlinOrNull() ?: "", + val sourceName: String = location.sourceNameInKotlinOrNull() ?: "", val lineNumber: Long = location.lineNumberInKotlin().toLong(), ) : LspStackFrame { companion object { diff --git a/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/debug/Variables.kt b/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/debug/Variables.kt index 9fb3b4fff8..835a98542a 100644 --- a/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/debug/Variables.kt +++ b/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/debug/Variables.kt @@ -354,6 +354,24 @@ internal class JavaFieldVariable( } } +/** + * The local's declared type, standing in the frame's own type for one the VM has never loaded. + * + * [LocalVariable.type] throws [ClassNotLoadedException] exactly as [Field.type] does, and without a + * stand-in the throw escapes into the caller's guard and drops the whole row, which is the case + * where seeing `parser = null` is informative. An unloaded local type is a reference type by + * definition, so the stand-in classifies the same and leaves `VariableValues.canMutate` false. + */ +private fun localType( + stackFrame: JavaStackFrame, + variable: LocalVariable, +): Type = + try { + variable.type() + } catch (err: ClassNotLoadedException) { + stackFrame.location.declaringType() + } + internal open class JavaLocalVariable( thread: ThreadReference, protected val stackFrame: JavaStackFrame, @@ -363,7 +381,7 @@ internal open class JavaLocalVariable( thread = thread, name = variable.name(), typeName = variable.typeName(), - type = variable.type(), + type = localType(stackFrame, variable), value = value, ) { companion object { @@ -375,7 +393,7 @@ internal open class JavaLocalVariable( variable: LocalVariable, value: Value?, ): JavaLocalVariable<*> = - when (variable.type()) { + when (localType(stackFrame, variable)) { is PrimitiveType -> JavaPrimitiveVariable(thread, stackFrame, variable, value) else -> JavaLocalVariable(thread, stackFrame, variable, value) } diff --git a/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/debug/utils/KotlinLocals.kt b/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/debug/utils/KotlinLocals.kt index 6748294842..c1a08c5360 100644 --- a/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/debug/utils/KotlinLocals.kt +++ b/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/debug/utils/KotlinLocals.kt @@ -1,9 +1,11 @@ package com.itsaky.androidide.lsp.java.debug.utils -import org.jetbrains.kotlin.codegen.AsmUtil.LABELED_THIS_PARAMETER +import org.jetbrains.kotlin.codegen.AsmUtil.INLINE_DECLARATION_SITE_THIS +import org.jetbrains.kotlin.codegen.AsmUtil.THIS_IN_DEFAULT_IMPLS import org.jetbrains.kotlin.codegen.coroutines.CONTINUATION_VARIABLE_NAME import org.jetbrains.kotlin.codegen.coroutines.SUSPEND_CALL_RESULT_NAME import org.jetbrains.kotlin.codegen.coroutines.SUSPEND_FUNCTION_COMPLETION_PARAMETER_NAME +import org.jetbrains.kotlin.codegen.inline.INLINE_FUN_VAR_SUFFIX /** * The inline marker prefix. The compiler writes this literal itself and exports no constant for it, @@ -22,9 +24,14 @@ private val SUSPEND_MACHINE_LOCALS = * Whether [name] is a local the Kotlin compiler generated rather than one the user wrote. * * Covers the three shapes ADFA-4191 section 3 lists: the inline markers (`$i$f$` for an inlined - * function body, `$i$a$` for an inlined lambda argument), the inline receivers (`$this$`), and the - * suspend state machine's own locals. These carry no meaning for someone reading their own code, so - * the variables list hides them. + * function body, `$i$a$` for an inlined lambda argument), the inline receivers, and the suspend + * state machine's own locals. These carry no meaning for someone reading their own code, so the + * variables list hides them. + * + * The receivers come in two shapes. Everything the compiler prefixes with `$this` is one - + * `$this$map`, `$this_foo`, `$this` - and a member inline function's declaration-site receiver is + * the bare `this_`, which shares no prefix with them. `this_` is matched exactly rather than as a + * prefix, so a local the user named `this_count` is left alone. * * A marker says what to hide, not whose code is running: `$i$a$` scopes a lambda the user wrote, * inlined into the user's own class, exactly as `$i$f$` scopes a library body inlined there. @@ -42,5 +49,14 @@ private val SUSPEND_MACHINE_LOCALS = */ fun isSyntheticKotlinLocal(name: String): Boolean = name.startsWith(INLINE_MARKER_PREFIX) || - name.startsWith(LABELED_THIS_PARAMETER) || + name.startsWith(THIS_IN_DEFAULT_IMPLS) || + isDeclarationSiteReceiver(name) || name in SUSPEND_MACHINE_LOCALS + +/** + * Whether [name] is the declaration-site receiver a member inline function leaves behind, `this_`, + * possibly carrying one `$iv` per inlining. + */ +private fun isDeclarationSiteReceiver(name: String): Boolean = + name == INLINE_DECLARATION_SITE_THIS || + name.startsWith(INLINE_DECLARATION_SITE_THIS + INLINE_FUN_VAR_SUFFIX) diff --git a/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/debug/utils/Strata.kt b/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/debug/utils/Strata.kt index 1ba43a8907..675e750536 100644 --- a/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/debug/utils/Strata.kt +++ b/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/debug/utils/Strata.kt @@ -6,11 +6,12 @@ import com.sun.jdi.ObjectCollectedException import com.sun.jdi.ReferenceType import org.jetbrains.kotlin.codegen.inline.KOTLIN_DEBUG_STRATA_NAME import org.jetbrains.kotlin.codegen.inline.KOTLIN_STRATA_NAME +import org.jetbrains.kotlin.codegen.inline.SourceMapper const val JAVA_STRATUM = "Java" /** The compiler's placeholder file for generated code, which belongs to no call site. */ -private const val FAKE_SOURCE_NAME = "fake.kt" +private val FAKE_SOURCE_NAME = SourceMapper.FAKE_FILE_NAME val ReferenceType.isKotlinType: Boolean get() = @@ -110,13 +111,31 @@ fun Location.inlineCallSiteLineOrNull(): Int? { * past the end of that range, so the two strata agree exactly off inlined code. `fake.kt` also reads * as a foreign file but is generated code rather than an inlining, so it has no call site to find. */ -private fun Location.isInlinedBody(): Boolean { - val kotlinName = sourceNameInKotlinOrNull() ?: return false - if (kotlinName == FAKE_SOURCE_NAME) { +private fun Location.isInlinedBody(): Boolean = + isInlinedBody( + kotlinSourceName = sourceNameInKotlinOrNull(), + javaSourceName = sourceNameOrNull(), + kotlinLine = lineNumberInKotlin(), + javaLine = lineNumberInSource(), + ) + +/** + * [isInlinedBody] over the four values it reads, so the decision can be tested without a live VM. + * + * Comparing the line as well as the name is what catches an inline function declared in the same + * file as its caller: the Kotlin stratum then answers the same file name and only the line differs. + */ +fun isInlinedBody( + kotlinSourceName: String?, + javaSourceName: String?, + kotlinLine: Int, + javaLine: Int, +): Boolean { + if (kotlinSourceName == null || kotlinSourceName == FAKE_SOURCE_NAME) { return false } - return kotlinName != sourceNameOrNull() || lineNumberInKotlin() != lineNumberInSource() + return kotlinSourceName != javaSourceName || kotlinLine != javaLine } /** diff --git a/lsp/java/src/test/java/com/itsaky/androidide/lsp/java/debug/KotlinLocalsTest.kt b/lsp/java/src/test/java/com/itsaky/androidide/lsp/java/debug/KotlinLocalsTest.kt index 4b174016f8..57aefed057 100644 --- a/lsp/java/src/test/java/com/itsaky/androidide/lsp/java/debug/KotlinLocalsTest.kt +++ b/lsp/java/src/test/java/com/itsaky/androidide/lsp/java/debug/KotlinLocalsTest.kt @@ -67,6 +67,23 @@ class KotlinLocalsTest { assertThat(isSyntheticKotlinLocal("\$this\$direct_u24lambda_u240")).isTrue() } + @Test + fun `declaration-site receivers are synthetic`() { + // A member inline function leaves its receiver behind as the bare `this_`, which shares no + // prefix with the `$this` family, plus one `$iv` per inlining. + assertThat(isSyntheticKotlinLocal("this_")).isTrue() + assertThat(isSyntheticKotlinLocal("this_\$iv")).isTrue() + assertThat(isSyntheticKotlinLocal("this_\$iv\$iv")).isTrue() + assertThat(isSyntheticKotlinLocal("\$this_foo")).isTrue() + assertThat(isSyntheticKotlinLocal("\$this")).isTrue() + } + + @Test + fun `a user local that merely starts with this_ is kept`() { + assertThat(isSyntheticKotlinLocal("this_count")).isFalse() + assertThat(isSyntheticKotlinLocal("this_thing")).isFalse() + } + @Test fun `an inlined lambda argument is hidden, not treated as library code`() { // $i$a$ scopes a lambda the user wrote, inlined into the user's own class, so it is noise in diff --git a/lsp/java/src/test/java/com/itsaky/androidide/lsp/java/debug/StrataTest.kt b/lsp/java/src/test/java/com/itsaky/androidide/lsp/java/debug/StrataTest.kt new file mode 100644 index 0000000000..f116aeaf53 --- /dev/null +++ b/lsp/java/src/test/java/com/itsaky/androidide/lsp/java/debug/StrataTest.kt @@ -0,0 +1,88 @@ +/* + * This file is part of AndroidIDE. + * + * AndroidIDE is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * AndroidIDE is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with AndroidIDE. If not, see . + */ +package com.itsaky.androidide.lsp.java.debug + +import com.google.common.truth.Truth.assertThat +import com.itsaky.androidide.lsp.java.debug.utils.isInlinedBody +import org.junit.Test + +class StrataTest { + @Test + fun `a line the class wrote itself is not inlined`() { + assertThat( + isInlinedBody( + kotlinSourceName = "DebugFixture.kt", + javaSourceName = "DebugFixture.kt", + kotlinLine = 27, + javaLine = 27, + ), + ).isFalse() + } + + @Test + fun `a body inlined from another file is inlined`() { + // Greeter.greetAll output line 60: the stdlib map body. + assertThat( + isInlinedBody( + kotlinSourceName = "_Collections.kt", + javaSourceName = "DebugFixture.kt", + kotlinLine = 1586, + javaLine = 60, + ), + ).isTrue() + } + + @Test + fun `a body inlined from the same file is inlined`() { + // Greeter.timed output line 64: measured's body, declared in DebugFixture.kt itself, so the + // name matches and only the line differs. Comparing the name alone would miss this. + assertThat( + isInlinedBody( + kotlinSourceName = "DebugFixture.kt", + javaSourceName = "DebugFixture.kt", + kotlinLine = 7, + javaLine = 64, + ), + ).isTrue() + } + + @Test + fun `the compiler's placeholder file is not inlined`() { + // fake.kt reads as a foreign file but is generated code, so SMAPBuilder gives it no call + // site and KotlinDebug would answer by best match. + assertThat( + isInlinedBody( + kotlinSourceName = "fake.kt", + javaSourceName = "DebugFixture.kt", + kotlinLine = 1, + javaLine = 42, + ), + ).isFalse() + } + + @Test + fun `a location with no Kotlin stratum name is not inlined`() { + assertThat( + isInlinedBody( + kotlinSourceName = null, + javaSourceName = "Greeter.java", + kotlinLine = 12, + javaLine = 12, + ), + ).isFalse() + } +} From a1c7cbb1a5340422e6009b38e7e7d1bf3e999dcd Mon Sep 17 00:00:00 2001 From: Daniel Alome Date: Tue, 29 Sep 2026 11:05:49 +0100 Subject: [PATCH 11/11] fix: show Kotlin lambda locals under their source names, ADFA-4191 Kotlin 2.3 names inlined locals name\N, where N is an inline scope number, instead of the old name$iv. The Variables panel showed the raw names, so a lambda passed to map read each\3 and greeting\3. Each inlined lambda leaves a marker local ($i$a$-...\N\...) naming its scope. Locals in those scopes are the user's own and now show without the suffix. Locals of inlined function bodies ($i$f$ scopes), such as mapTo's item\2, keep it: it is the only cue that they are not the user's. Display only; reads and writes still go through the JDI LocalVariable. Verified on the arm64 emulator with testing/resources/kotlin-debug-fixture: each, greeting and doubled show clean, item\2 and label\1 keep their suffix, and editing each still sets the value. --- .../lsp/java/debug/LspThreadInfo.kt | 7 +- .../androidide/lsp/java/debug/Variables.kt | 11 +-- .../lsp/java/debug/utils/KotlinLocals.kt | 24 +++++++ .../lsp/java/debug/KotlinLocalsTest.kt | 68 +++++++++++++++++++ 4 files changed, 105 insertions(+), 5 deletions(-) diff --git a/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/debug/LspThreadInfo.kt b/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/debug/LspThreadInfo.kt index ababb6be03..d41194ae28 100644 --- a/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/debug/LspThreadInfo.kt +++ b/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/debug/LspThreadInfo.kt @@ -10,6 +10,8 @@ import com.itsaky.androidide.lsp.debug.model.Variable import com.itsaky.androidide.lsp.debug.model.VariableKind import com.itsaky.androidide.lsp.java.debug.utils.isOpaque import com.itsaky.androidide.lsp.java.debug.utils.isSyntheticKotlinLocal +import com.itsaky.androidide.lsp.java.debug.utils.kotlinDisplayName +import com.itsaky.androidide.lsp.java.debug.utils.kotlinLambdaScopes import com.itsaky.androidide.lsp.java.debug.utils.lineNumberInKotlin import com.itsaky.androidide.lsp.java.debug.utils.sourceNameInKotlinOrNull import com.sun.jdi.Location @@ -103,7 +105,9 @@ class JavaStackFrame( } try { - visibleVariables() + val locals = visibleVariables() + val lambdaScopes = kotlinLambdaScopes(locals?.map { it.name() }.orEmpty()) + locals ?.mapNotNull { variable -> if (variable.name().isBlank()) { // some opaque frames in core Android classes have empty variable names (like in ZygoteInit) @@ -120,6 +124,7 @@ class JavaStackFrame( stackFrame = this@JavaStackFrame, variable = variable, value = getValue(variable), + name = kotlinDisplayName(variable.name(), lambdaScopes), ) } catch (e: VMDisconnectedException) { throw e diff --git a/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/debug/Variables.kt b/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/debug/Variables.kt index 835a98542a..8566db64f6 100644 --- a/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/debug/Variables.kt +++ b/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/debug/Variables.kt @@ -377,9 +377,10 @@ internal open class JavaLocalVariable( protected val stackFrame: JavaStackFrame, protected val variable: LocalVariable, value: Value?, + name: String, ) : AbstractJavaVariable( thread = thread, - name = variable.name(), + name = name, typeName = variable.typeName(), type = localType(stackFrame, variable), value = value, @@ -392,10 +393,11 @@ internal open class JavaLocalVariable( stackFrame: JavaStackFrame, variable: LocalVariable, value: Value?, + name: String, ): JavaLocalVariable<*> = when (localType(stackFrame, variable)) { - is PrimitiveType -> JavaPrimitiveVariable(thread, stackFrame, variable, value) - else -> JavaLocalVariable(thread, stackFrame, variable, value) + is PrimitiveType -> JavaPrimitiveVariable(thread, stackFrame, variable, value, name) + else -> JavaLocalVariable(thread, stackFrame, variable, value, name) } } @@ -504,7 +506,8 @@ internal class JavaPrimitiveVariable( stackFrame: JavaStackFrame, variable: LocalVariable, value: Value?, -) : JavaLocalVariable(thread, stackFrame, variable, value), + name: String, +) : JavaLocalVariable(thread, stackFrame, variable, value, name), PrimitiveVariable { override val primitiveKind: PrimitiveKind by lazy { when (type) { diff --git a/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/debug/utils/KotlinLocals.kt b/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/debug/utils/KotlinLocals.kt index c1a08c5360..852530d971 100644 --- a/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/debug/utils/KotlinLocals.kt +++ b/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/debug/utils/KotlinLocals.kt @@ -6,6 +6,8 @@ import org.jetbrains.kotlin.codegen.coroutines.CONTINUATION_VARIABLE_NAME import org.jetbrains.kotlin.codegen.coroutines.SUSPEND_CALL_RESULT_NAME import org.jetbrains.kotlin.codegen.coroutines.SUSPEND_FUNCTION_COMPLETION_PARAMETER_NAME import org.jetbrains.kotlin.codegen.inline.INLINE_FUN_VAR_SUFFIX +import org.jetbrains.kotlin.codegen.inline.INLINE_SCOPE_NUMBER_SEPARATOR +import org.jetbrains.kotlin.load.java.JvmAbi.LOCAL_VARIABLE_NAME_PREFIX_INLINE_ARGUMENT /** * The inline marker prefix. The compiler writes this literal itself and exports no constant for it, @@ -60,3 +62,25 @@ fun isSyntheticKotlinLocal(name: String): Boolean = private fun isDeclarationSiteReceiver(name: String): Boolean = name == INLINE_DECLARATION_SITE_THIS || name.startsWith(INLINE_DECLARATION_SITE_THIS + INLINE_FUN_VAR_SUFFIX) + +fun kotlinLambdaScopes(names: List): Set = + names + .filter { it.startsWith(LOCAL_VARIABLE_NAME_PREFIX_INLINE_ARGUMENT) } + .mapNotNullTo(mutableSetOf()) { marker -> + marker + .split(INLINE_SCOPE_NUMBER_SEPARATOR) + .getOrNull(1) + ?.toIntOrNull() + } + +fun kotlinDisplayName( + name: String, + lambdaScopes: Set, +): String { + val parts = name.split(INLINE_SCOPE_NUMBER_SEPARATOR) + if (parts.size != 2 || parts[0].isEmpty()) { + return name + } + val scope = parts[1].toIntOrNull() ?: return name + return if (scope in lambdaScopes) parts[0] else name +} diff --git a/lsp/java/src/test/java/com/itsaky/androidide/lsp/java/debug/KotlinLocalsTest.kt b/lsp/java/src/test/java/com/itsaky/androidide/lsp/java/debug/KotlinLocalsTest.kt index 57aefed057..a8924ae6b0 100644 --- a/lsp/java/src/test/java/com/itsaky/androidide/lsp/java/debug/KotlinLocalsTest.kt +++ b/lsp/java/src/test/java/com/itsaky/androidide/lsp/java/debug/KotlinLocalsTest.kt @@ -18,9 +18,37 @@ package com.itsaky.androidide.lsp.java.debug import com.google.common.truth.Truth.assertThat import com.itsaky.androidide.lsp.java.debug.utils.isSyntheticKotlinLocal +import com.itsaky.androidide.lsp.java.debug.utils.kotlinDisplayName +import com.itsaky.androidide.lsp.java.debug.utils.kotlinLambdaScopes import org.junit.Test class KotlinLocalsTest { + private val greetAllLocals = + listOf( + "\$i\$a\$-map-Greeter\$greetAll\$1\\3\\62\\0", + "greeting\\3", + "each\\3", + "item\\2", + "\$i\$f\$mapTo\\2\\60", + "\$this\$mapTo\\2", + "destination\\2", + "\$i\$f\$map\\1\\27", + "\$this\$map\\1", + "this", + "names", + ) + + private val timedLocals = + listOf( + "\$i\$a\$-measured-Greeter\$timed\$1\\2\\65\\0", + "doubled\\2", + "\$i\$f\$measured\\1\\33", + "started\\1", + "result\\1", + "label\\1", + "this", + ) + @Test fun `inline markers are synthetic`() { assertThat(isSyntheticKotlinLocal("\$i\$f\$Column")).isTrue() @@ -84,6 +112,46 @@ class KotlinLocalsTest { assertThat(isSyntheticKotlinLocal("this_thing")).isFalse() } + @Test + fun `scope-numbered inline markers are synthetic`() { + assertThat(isSyntheticKotlinLocal("\$i\$a\$-map-Greeter\$greetAll\$1\\3\\62\\0")).isTrue() + assertThat(isSyntheticKotlinLocal("\$i\$f\$mapTo\\2\\60")).isTrue() + assertThat(isSyntheticKotlinLocal("\$this\$mapTo\\2")).isTrue() + } + + @Test + fun `lambda scopes come only from inline lambda markers`() { + assertThat(kotlinLambdaScopes(greetAllLocals)).containsExactly(3) + assertThat(kotlinLambdaScopes(timedLocals)).containsExactly(2) + assertThat(kotlinLambdaScopes(listOf("savedInstanceState", "this"))).isEmpty() + } + + @Test + fun `a local in the user's inlined lambda shows its source name`() { + val scopes = kotlinLambdaScopes(greetAllLocals) + assertThat(kotlinDisplayName("each\\3", scopes)).isEqualTo("each") + assertThat(kotlinDisplayName("greeting\\3", scopes)).isEqualTo("greeting") + assertThat(kotlinDisplayName("doubled\\2", kotlinLambdaScopes(timedLocals))).isEqualTo("doubled") + } + + @Test + fun `a local of an inlined function body keeps its scope number`() { + val scopes = kotlinLambdaScopes(greetAllLocals) + assertThat(kotlinDisplayName("item\\2", scopes)).isEqualTo("item\\2") + assertThat(kotlinDisplayName("destination\\2", scopes)).isEqualTo("destination\\2") + assertThat(kotlinDisplayName("started\\1", kotlinLambdaScopes(timedLocals))).isEqualTo("started\\1") + } + + @Test + fun `names without a single scope number are unchanged`() { + val scopes = setOf(1, 2, 3) + assertThat(kotlinDisplayName("names", scopes)).isEqualTo("names") + assertThat(kotlinDisplayName("this", scopes)).isEqualTo("this") + assertThat(kotlinDisplayName("item\$iv\$iv", scopes)).isEqualTo("item\$iv\$iv") + assertThat(kotlinDisplayName("x\\3\\1", scopes)).isEqualTo("x\\3\\1") + assertThat(kotlinDisplayName("\\3", scopes)).isEqualTo("\\3") + } + @Test fun `an inlined lambda argument is hidden, not treated as library code`() { // $i$a$ scopes a lambda the user wrote, inlined into the user's own class, so it is noise in