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..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 @@ -15,29 +15,42 @@ 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) {} + + /** + * 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 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..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 @@ -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() + // 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: {}, stopForSet={}, stopForEvent={}", + event, + stopForSet, + stopForEvent, + ) + + stopForSet = stopForSet || stopForEvent + } + + if (!stopForSet) { + 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) + + /** + * @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 + } +} 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 22f81c280f..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 @@ -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 @@ -89,8 +91,20 @@ internal class JavaDebugAdapter : "jdk.*", "com.sun.*", "sun.*", + "kotlin.*", + "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]. */ @@ -450,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() @@ -517,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, @@ -554,7 +586,7 @@ internal class JavaDebugAdapter : ) } - override fun stepEvent(e: StepEvent) { + override fun stepEvent(e: StepEvent): Boolean { logger.debug("stepEvent: {}", e) e.virtualMachine().checkIsCurrentVm() @@ -562,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( @@ -570,6 +606,68 @@ 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. 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". + * + * 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( + vm: VirtualMachine, + e: StepEvent, + location: Location, + thread: ThreadReference, + ): Boolean { + if ((e.request() as? StepRequest)?.depth() == StepRequest.STEP_INTO) { + return false + } + + 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_ALL, + countFilter = 1, + ) + + req.putProperty(INLINE_STEP_BUDGET, taken + 1) + req.enable() + return true } override fun vmDisconnectEvent(e: VMDisconnectEvent) { 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..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 @@ -9,6 +9,11 @@ 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.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 import com.sun.jdi.Method import com.sun.jdi.ObjectCollectedException @@ -28,8 +33,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.sourceNameInKotlinOrNull() ?: "", + val lineNumber: Long = location.lineNumberInKotlin().toLong(), ) : LspStackFrame { companion object { private val logger = LoggerFactory.getLogger(JavaStackFrame::class.java) @@ -68,24 +73,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( @@ -97,19 +105,26 @@ 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) return@mapNotNull null } + if (isSyntheticKotlinLocal(variable.name())) { + return@mapNotNull null + } + try { JavaLocalVariable.forVariable( thread = thread, stackFrame = this@JavaStackFrame, variable = variable, - value = frame.getValue(variable), + value = getValue(variable), + name = kotlinDisplayName(variable.name(), lambdaScopes), ) } catch (e: VMDisconnectedException) { throw e @@ -164,7 +179,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}") + } } } } 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..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 @@ -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 @@ -29,6 +30,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 @@ -195,7 +197,9 @@ 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 } } @@ -228,10 +232,16 @@ internal abstract class AbstractJavaVariable( return evaluationContext.evaluate(thread) { refType .allFields() - .associateWith { field -> - if (field.isStatic) refType.getValue(field) else ref.getValue(field) - }.map { (field, value) -> - JavaFieldVariable(thread, ref, refType, 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 + } catch (err: Throwable) { + logger.error("Failed to create variable wrapper for field {}", field.name(), err) + null + } }.toSet() } ?: emptySet() } @@ -268,17 +278,34 @@ 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, - refType: ReferenceType, private val field: Field, value: Value?, ) : AbstractJavaVariable( thread = thread, name = field.name(), typeName = field.typeName(), - type = refType, + type = fieldType(ref, field), value = value, ) { companion object { @@ -287,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) { @@ -320,16 +354,35 @@ 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, protected val variable: LocalVariable, value: Value?, + name: String, ) : AbstractJavaVariable( thread = thread, - name = variable.name(), + name = name, typeName = variable.typeName(), - type = if (variable is ObjectReference) variable.referenceType() else variable.type(), + type = localType(stackFrame, variable), value = value, ) { companion object { @@ -340,10 +393,11 @@ internal open class JavaLocalVariable( stackFrame: JavaStackFrame, variable: LocalVariable, value: Value?, + name: String, ): JavaLocalVariable<*> = - when (variable.type()) { - is PrimitiveType -> JavaPrimitiveVariable(thread, stackFrame, variable, value) - else -> JavaLocalVariable(thread, stackFrame, variable, value) + when (localType(stackFrame, variable)) { + is PrimitiveType -> JavaPrimitiveVariable(thread, stackFrame, variable, value, name) + else -> JavaLocalVariable(thread, stackFrame, variable, value, name) } } @@ -452,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 new file mode 100644 index 0000000000..852530d971 --- /dev/null +++ b/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/debug/utils/KotlinLocals.kt @@ -0,0 +1,86 @@ +package com.itsaky.androidide.lsp.java.debug.utils + +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 +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, + * unlike the other names here. + */ +private const val INLINE_MARKER_PREFIX = "\$i\$" + +private val SUSPEND_MACHINE_LOCALS = + setOf( + 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 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, 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. + * + * 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 `$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 = + name.startsWith(INLINE_MARKER_PREFIX) || + 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) + +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/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 ad929705d3..aaa8d71717 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 @@ -42,8 +42,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) @@ -84,6 +83,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) @@ -104,7 +113,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 cf9fb6e228..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 @@ -4,14 +4,19 @@ 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 +import org.jetbrains.kotlin.codegen.inline.SourceMapper 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 val FAKE_SOURCE_NAME = SourceMapper.FAKE_FILE_NAME val ReferenceType.isKotlinType: Boolean get() = try { - availableStrata().contains(KOTLIN_STRATUM) + availableStrata().contains(KOTLIN_STRATA_NAME) } catch (err: AbsentInformationException) { false } catch (err: ObjectCollectedException) { @@ -50,6 +55,89 @@ 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 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_STRATA_NAME).takeIf { it > 0 } ?: lineNumberInSource() + +fun Location.sourceNameInKotlinOrNull(): String? = + try { + 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 = + 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 kotlinSourceName != javaSourceName || kotlinLine != javaLine +} + /** * 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 new file mode 100644 index 0000000000..a8924ae6b0 --- /dev/null +++ b/lsp/java/src/test/java/com/itsaky/androidide/lsp/java/debug/KotlinLocalsTest.kt @@ -0,0 +1,161 @@ +/* + * 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.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() + assertThat(isSyntheticKotlinLocal("\$i\$a\$-map-Foo")).isTrue() + 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() + 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 `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 `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 + 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 `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 + // the variables list but says nothing about whose code is executing. + assertThat(isSyntheticKotlinLocal("\$i\$a\$-forEach-MainActivity")).isTrue() + } +} 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() + } +} 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/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..4e4f573b3c --- /dev/null +++ b/testing/resources/kotlin-debug-fixture/README.md @@ -0,0 +1,117 @@ +# 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. 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 + +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 | `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 | 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. 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. `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 + +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 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 +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. + +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 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 +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.