Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,8 @@ internal class IndexWorker(
private val fileIndex: KtFileMetadataIndex,
private val sourceIndex: JvmSymbolIndex,
private val scope: CoroutineScope,
/** [KtSymbolIndex.resolvesTo]. */
private val resolvesTo: (Path, KtFile) -> Boolean,
) {
companion object {
private val logger = LoggerFactory.getLogger(IndexWorker::class.java)
Expand Down Expand Up @@ -59,7 +61,7 @@ internal class IndexWorker(
logger.debug("Indexing modified file: {}", path)
try {
// Not counted in sourceIndexCount: this runs on another coroutine, and an edit is not part of a pass.
indexSourceFile(project, ktFile, fileIndex, sourceIndex, cancelChecker)
indexSourceFile(project, ktFile, fileIndex, sourceIndex, cancelChecker, resolvesTo)
} catch (e: AnalysisPreemptedException) {
// Preempted by higher-priority analysis; re-queue so the edit still gets indexed.
logger.debug("Indexing of modified file {} preempted; re-queueing", path)
Expand Down Expand Up @@ -270,6 +272,7 @@ internal class IndexWorker(
// A real (cancellable) checker so the scheduler can preempt this pass
// in favour of completion/diagnostics.
cancelChecker = ICancelChecker.Default(),
resolvesTo = resolvesTo,
)
}
if (wrote) IndexOutcome.INDEXED else IndexOutcome.SKIPPED
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,7 @@ internal class KtSymbolIndex(
fileIndex = fileIndex,
sourceIndex = sourceIndex,
scope = scope,
resolvesTo = ::resolvesTo,
)

private val scanningWorker =
Expand Down Expand Up @@ -553,6 +554,16 @@ internal class KtSymbolIndex(
.mapNotNull { Paths.get(it).toVirtualFileOrNull() }
.toList()

/**
* Whether FIR resolves [path] to [ktFile]. Non-blocking and never refreshes, so the indexer can ask
* under `project.read` without queueing more indexing.
*/
@OptIn(ResolutionSideKtFileAccess::class)
internal fun resolvesTo(
path: Path,
ktFile: KtFile,
): Boolean = getKtFile(path) === ktFile

/** [getKtFile] for [vf], keyed by the path it maps to. */
@ResolutionSideKtFileAccess
internal fun getKtFile(vf: VirtualFile): KtFile? = getKtFile(vf.toNioPath(), vf)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@ import org.jetbrains.kotlin.utils.exceptions.KotlinExceptionWithAttachments
import org.slf4j.LoggerFactory
import java.io.FileNotFoundException
import java.nio.file.NoSuchFileException
import java.nio.file.Path
import java.time.Instant
import kotlin.io.path.pathString

Expand All @@ -78,6 +79,23 @@ internal fun Throwable.isMissingClasspathFile(): Boolean =
.take(32)
.any { it is NoSuchFileException || it is FileNotFoundException }

/**
* This resolver's answer, or null when it throws: e.g. the path's last refresh failed, so its future
* completed exceptionally. Callers run outside any catch on a scope with no exception handler.
*/
private fun ((Path, KtFile) -> Boolean).orNull(
path: Path,
ktFile: KtFile,
): Boolean? =
try {
invoke(path, ktFile)
} catch (e: CancellationException) {
throw e
} catch (e: Throwable) {
logger.warn("Could not tell which instance FIR resolves {} to", path, e)
null
}

internal fun KtFile.toMetadata(
project: Project,
isIndexed: Boolean = false,
Expand All @@ -102,7 +120,9 @@ internal fun KtFile.toMetadata(
* Indexes [ktFile]'s declarations into [symbolsIndex] and records it in [fileIndex].
*
* Returns true only when it wrote the file's symbols; false when the file was unchanged, could not
* be analyzed, or an index was closed.
* be analyzed, is not the instance FIR resolves its path to, or an index was closed.
*
* [resolvesTo] tells whether FIR resolves a path to a given instance. It must not block or refresh.
*/
@OptIn(UnpinnedAnalysis::class)
internal suspend fun indexSourceFile(
Expand All @@ -111,6 +131,7 @@ internal suspend fun indexSourceFile(
fileIndex: KtFileMetadataIndex,
symbolsIndex: JvmSymbolIndex,
cancelChecker: ICancelChecker,
resolvesTo: (Path, KtFile) -> Boolean,
): Boolean {
// Indexing runs at the lowest priority, yielding to completion and diagnostics. Wrapping the checker
// lets the scheduler preempt an in-progress pass; the preemption surfaces as AnalysisPreemptedException
Expand All @@ -127,7 +148,17 @@ internal suspend fun indexSourceFile(
val newFile =
project.read {
if (project.isDisposed) return@read null
ktFile.toMetadata(project, isIndexed = true)
val metadata = ktFile.toMetadata(project, isIndexed = true)
/*
* FIR resolves an open path to its newest parse, so analysing any other instance (the disk copy
* on a full pass, or an edit's superseded parse) finds no FIR for its declarations (ADFA-5763).
* Skip it: the refresh that produced the newer instance queued that instance's own pass.
*/
if (resolvesTo.orNull(Path.of(metadata.filePath), ktFile) != true) {
logger.debug("Skipping {}: FIR resolves its path to another instance", metadata.filePath)
return@read null
}
metadata
} ?: return false
val existingFile = fileIndex.get(newFile.filePath)
checker.abortIfCancelled()
Expand Down Expand Up @@ -163,7 +194,7 @@ internal suspend fun indexSourceFile(
object : KtTreeVisitorVoid() {
override fun visitDeclaration(dcl: KtDeclaration) {
checker.abortIfCancelled()
val symbol = with(session) { analyzeDeclaration(newFile.filePath, dcl) }
val symbol = with(session) { analyzeDeclaration(newFile.filePath, dcl, resolvesTo) }
checker.abortIfCancelled()
symbol?.let { list.add(it) }
super.visitDeclaration(dcl)
Expand Down Expand Up @@ -195,6 +226,7 @@ internal suspend fun indexSourceFile(
private fun KaSession.analyzeDeclaration(
filePath: String,
dcl: KtDeclaration,
resolvesTo: (Path, KtFile) -> Boolean,
): JvmSymbol? {
dcl.name ?: return null
return runCatching {
Expand All @@ -216,6 +248,8 @@ private fun KaSession.analyzeDeclaration(
Sentry.captureException(err) { scope ->
scope.apply {
setExtra("fpth", filePath)
// False means the instance was superseded mid-pass; true means the failure has another cause.
setTag("instanceMatches", resolvesTo.orNull(Path.of(filePath), dcl.containingKtFile)?.toString() ?: "unknown")
setExtra("dcl", dcl.name)
setExtra("dcl.dbg", dcl.getDebugText())
setExtra(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ class IndexWorkerDisposalTest : KtLspTest() {
fileIndex = fileIndex(),
sourceIndex = jvmIndex(),
scope = CoroutineScope(Dispatchers.Default + SupervisorJob()),
resolvesTo = env.ktSymbolIndex::resolvesTo,
)

/*
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
package com.itsaky.androidide.lsp.kotlin.compiler.index

import com.google.common.truth.Truth.assertThat
import com.itsaky.androidide.eventbus.events.editor.DocumentCloseEvent
import com.itsaky.androidide.eventbus.events.editor.DocumentOpenEvent
import com.itsaky.androidide.lsp.kotlin.fixtures.KtLspTest
import com.itsaky.androidide.projects.FileManager
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.withTimeout
import org.appdevforall.codeonthego.indexing.InMemoryIndex
import org.appdevforall.codeonthego.indexing.jvm.JvmSymbolDescriptor
import org.appdevforall.codeonthego.indexing.jvm.JvmSymbolIndex
import org.appdevforall.codeonthego.indexing.jvm.KtFileMetadataDescriptor
import org.appdevforall.codeonthego.indexing.jvm.KtFileMetadataIndex
import org.appdevforall.codeonthego.indexing.util.BackgroundIndexer
import org.junit.After
import org.junit.Test
import java.nio.file.Path

/**
* A full pass over an open file must not analyse PsiManager's disk copy: FIR resolves the path to the
* live buffer's parse, so the disk copy's declarations have no FIR ("No fir element was found",
* ADFA-5763). The refresh that made the live parse queues its own index pass.
*/
internal class IndexWorkerOpenFileTest : KtLspTest() {
override val enableParserEventSystem = true

private var openedPath: Path? = null

@After
fun closeDoc() {
openedPath?.let { FileManager.onDocumentClose(DocumentCloseEvent(it)) }
}

@Test
fun `a full pass skips the disk copy of an open file`(): Unit =
runBlocking {
val onDisk = "package p\n\nfun onDisk() = 0\n"
val vf = createSourceFile("Main.kt", onDisk).virtualFile
val path = env.sourceRoots.first().resolve("Main.kt")
FileManager.onDocumentOpen(DocumentOpenEvent(path, "$onDisk\nfun onlyInBuffer() = 1\n", 1))
openedPath = path
env.ktSymbolIndex.refreshCurrentKtFile(path)

val backing = InMemoryIndex(JvmSymbolDescriptor)
val sourceIndex =
object : JvmSymbolIndex(backing, BackgroundIndexer(backing)) {
override fun visibleSourceIds(): Collection<String>? = null
}
val worker =
IndexWorker(
project = env.project,
queue = WorkerQueue(),
fileIndex = KtFileMetadataIndex(InMemoryIndex(KtFileMetadataDescriptor)),
sourceIndex = sourceIndex,
scope = CoroutineScope(Dispatchers.Default + SupervisorJob()),
resolvesTo = env.ktSymbolIndex::resolvesTo,
)

worker.submitCommand(IndexCommand.IndexSourceFile(vf))
worker.submitCommand(IndexCommand.Stop)
withTimeout(10_000) { worker.start() }

assertThat(sourceIndex.findByPrefix("").map { it.shortName }.toList()).isEmpty()
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,7 @@ class IndexWorkerPhaseLifecycleTest {
fileIndex = fileIndex,
sourceIndex = sourceIndex,
scope = CoroutineScope(Dispatchers.Default + SupervisorJob()),
resolvesTo = { _, _ -> true },
)
}

Expand Down Expand Up @@ -203,7 +204,7 @@ class IndexWorkerPhaseLifecycleTest {
mockPsiManager(ktFile = mockk())
mockkStatic("com.itsaky.androidide.lsp.kotlin.compiler.index.SourceFileIndexerKt")
var attempts = 0
coEvery { indexSourceFile(any(), any(), any(), any(), any()) } answers {
coEvery { indexSourceFile(any(), any(), any(), any(), any(), any()) } answers {
if (++attempts == 1) throw AnalysisPreemptedException()
sink.events += "indexed retry"
true
Expand Down Expand Up @@ -237,7 +238,7 @@ class IndexWorkerPhaseLifecycleTest {
runBlocking {
Memprof.sink = sink
mockkStatic("com.itsaky.androidide.lsp.kotlin.compiler.index.SourceFileIndexerKt")
coEvery { indexSourceFile(any(), any(), any(), any(), any()) } answers {
coEvery { indexSourceFile(any(), any(), any(), any(), any(), any()) } answers {
sink.events += "indexed edit"
true
}
Expand Down Expand Up @@ -267,7 +268,7 @@ class IndexWorkerPhaseLifecycleTest {
Memprof.sink = sink
mockPsiManager(ktFile = mockk())
mockkStatic("com.itsaky.androidide.lsp.kotlin.compiler.index.SourceFileIndexerKt")
coEvery { indexSourceFile(any(), any(), any(), any(), any()) } returns false
coEvery { indexSourceFile(any(), any(), any(), any(), any(), any()) } returns false
val worker = worker()

worker.submitCommand(IndexCommand.SourceScanningStarted(pass = 1))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import com.google.common.truth.Truth.assertThat
import com.itsaky.androidide.lsp.kotlin.fixtures.KtLspTest
import com.itsaky.androidide.progress.ICancelChecker
import io.mockk.mockk
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.runBlocking
import org.appdevforall.codeonthego.indexing.InMemoryIndex
import org.appdevforall.codeonthego.indexing.api.Index
Expand All @@ -13,6 +14,7 @@ import org.appdevforall.codeonthego.indexing.jvm.JvmSymbolIndex
import org.appdevforall.codeonthego.indexing.jvm.KtFileMetadataDescriptor
import org.appdevforall.codeonthego.indexing.jvm.KtFileMetadataIndex
import org.appdevforall.codeonthego.indexing.util.BackgroundIndexer
import org.jetbrains.kotlin.psi.KtFile
import org.junit.Test
import java.io.FileNotFoundException
import java.nio.file.NoSuchFileException
Expand All @@ -27,6 +29,12 @@ class SourceFileIndexerTest : KtLspTest() {

private fun buildFileIndex() = KtFileMetadataIndex(InMemoryIndex(KtFileMetadataDescriptor))

private suspend fun index(
file: KtFile,
fileIndex: KtFileMetadataIndex,
symbolsIndex: JvmSymbolIndex,
) = indexSourceFile(env.project, file, fileIndex, symbolsIndex, ICancelChecker.NOOP, env.ktSymbolIndex::resolvesTo)

@Test
fun `indexer ignores local property inside function body`(): Unit =
runBlocking {
Expand All @@ -52,7 +60,7 @@ class SourceFileIndexerTest : KtLspTest() {

val symbolsIndex = buildSymbolIndex()

indexSourceFile(env.project, file, mockk(relaxed = true), symbolsIndex, ICancelChecker.NOOP)
index(file, mockk(relaxed = true), symbolsIndex)

val names = symbolsIndex.findByPrefix("").map { it.shortName }.toSet()
assertThat(names).containsExactly("doWork", "fetchStatus")
Expand All @@ -74,7 +82,7 @@ class SourceFileIndexerTest : KtLspTest() {

val symbolsIndex = buildSymbolIndex()

indexSourceFile(env.project, file, mockk(relaxed = true), symbolsIndex, ICancelChecker.NOOP)
index(file, mockk(relaxed = true), symbolsIndex)

val names = symbolsIndex.findByPrefix("").map { it.shortName }.toSet()
assertThat(names).containsExactly("outer")
Expand All @@ -94,7 +102,7 @@ class SourceFileIndexerTest : KtLspTest() {

val symbolsIndex = buildSymbolIndex()

indexSourceFile(env.project, file, mockk(relaxed = true), symbolsIndex, ICancelChecker.NOOP)
index(file, mockk(relaxed = true), symbolsIndex)

val names = symbolsIndex.findByPrefix("").map { it.shortName }.toSet()
assertThat(names).containsExactly("globalConfig", "compute")
Expand All @@ -105,7 +113,7 @@ class SourceFileIndexerTest : KtLspTest() {
runBlocking {
val file = createSourceFile("Fresh.kt", "fun fresh() = 0")

val wrote = indexSourceFile(env.project, file, buildFileIndex(), buildSymbolIndex(), ICancelChecker.NOOP)
val wrote = index(file, buildFileIndex(), buildSymbolIndex())

assertThat(wrote).isTrue()
}
Expand All @@ -116,9 +124,9 @@ class SourceFileIndexerTest : KtLspTest() {
val file = createSourceFile("Unchanged.kt", "fun unchanged() = 0")
val fileIndex = buildFileIndex()
val symbolsIndex = buildSymbolIndex()
indexSourceFile(env.project, file, fileIndex, symbolsIndex, ICancelChecker.NOOP)
index(file, fileIndex, symbolsIndex)

val wrote = indexSourceFile(env.project, file, fileIndex, symbolsIndex, ICancelChecker.NOOP)
val wrote = index(file, fileIndex, symbolsIndex)

assertThat(wrote).isFalse()
}
Expand All @@ -136,9 +144,34 @@ class SourceFileIndexerTest : KtLspTest() {
override fun visibleSourceIds(): Collection<String>? = null
}

val wrote = indexSourceFile(env.project, file, buildFileIndex(), symbolsIndex, ICancelChecker.NOOP)
val wrote = index(file, buildFileIndex(), symbolsIndex)

assertThat(wrote).isFalse()
}

@Test
fun `a throwing resolver skips the file instead of escaping`(): Unit =
runBlocking {
val file = createSourceFile("Throws.kt", "fun throws() = 0")
val symbolsIndex = buildSymbolIndex()

val wrote =
indexSourceFile(env.project, file, buildFileIndex(), symbolsIndex, ICancelChecker.NOOP) { _, _ ->
throw IllegalStateException("refresh failed")
}

assertThat(wrote).isFalse()
assertThat(symbolsIndex.findByPrefix("").toList()).isEmpty()
}

@Test(expected = CancellationException::class)
fun `a cancelled resolver still cancels the pass`(): Unit =
runBlocking {
val file = createSourceFile("Cancelled.kt", "fun cancelled() = 0")

indexSourceFile(env.project, file, buildFileIndex(), buildSymbolIndex(), ICancelChecker.NOOP) { _, _ ->
throw CancellationException("cancelled")
}
}

@Test
Expand Down
Loading