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 @@ -10,6 +10,7 @@ import org.jetbrains.kotlin.analysis.api.platform.projectStructure.KotlinProject
import org.jetbrains.kotlin.analysis.api.platform.projectStructure.KotlinProjectStructureProviderBase
import org.jetbrains.kotlin.analysis.api.projectStructure.KaModule
import org.jetbrains.kotlin.analysis.api.projectStructure.KaNotUnderContentRootModule
import org.jetbrains.kotlin.analysis.api.projectStructure.copyOrigin
import org.jetbrains.kotlin.analysis.low.level.api.fir.util.originalKtFile
import org.jetbrains.kotlin.cli.jvm.index.JavaRoot
import org.jetbrains.kotlin.com.intellij.mock.MockProject
Expand All @@ -21,12 +22,12 @@ import java.nio.file.Paths
import java.util.concurrent.ConcurrentHashMap
import kotlin.io.path.pathString

internal class ProjectStructureProvider : KtLspService, KotlinProjectStructureProviderBase() {

internal class ProjectStructureProvider :
KotlinProjectStructureProviderBase(),
KtLspService {
companion object {
fun getInstance(project: Project): ProjectStructureProvider {
return KotlinProjectStructureProvider.getInstance(project) as ProjectStructureProvider
}
fun getInstance(project: Project): ProjectStructureProvider =
KotlinProjectStructureProvider.getInstance(project) as ProjectStructureProvider
}

private lateinit var modules: List<KtModule>
Expand All @@ -35,7 +36,10 @@ internal class ProjectStructureProvider : KtLspService, KotlinProjectStructurePr
private val inMemoryVfToModule = ConcurrentHashMap<VirtualFile, KaModule>()
private val pathToInMemoryVf = ConcurrentHashMap<String, VirtualFile>()

fun registerInMemoryFile(sourcePath: String, vf: VirtualFile) {
fun registerInMemoryFile(
sourcePath: String,
vf: VirtualFile,
) {
pathToInMemoryVf.remove(sourcePath)?.let { inMemoryVfToModule.remove(it) }

val module = findModuleForSourceId(sourcePath) ?: return
Expand All @@ -61,30 +65,38 @@ internal class ProjectStructureProvider : KtLspService, KotlinProjectStructurePr
project: MockProject,
index: KtSymbolIndex,
modules: List<KtModule>,
libraryRoots: List<JavaRoot>
libraryRoots: List<JavaRoot>,
) {
this.modules = modules
this.project = project
}

override fun getModule(
element: PsiElement,
useSiteModule: KaModule?
useSiteModule: KaModule?,
): KaModule = getModuleImpl(element, useSiteModule)

private fun getModuleImpl(
element: PsiElement,
useSiteModule: KaModule?
useSiteModule: KaModule?,
): KaModule {
val virtualFile = element.containingFile?.virtualFile
?: return notUnderContentRootModuleWithoutPsiFile
// A copy in its original's source module makes FIR see every declaration twice; give it a dangling module.
val containingFile = element.containingFile
if (containingFile is KtFile && containingFile.copyOrigin != null) {
computeSpecialModule(containingFile)?.let { return it }
}

val virtualFile =
containingFile?.virtualFile
?: return notUnderContentRootModuleWithoutPsiFile

// Fast path: in-memory file registered by onFileContentChanged.
inMemoryVfToModule[virtualFile]?.let { return it }

val backingFilePath = (element.containingFile as? KtFile)?.let {
it.backingFilePath ?: it.originalKtFile?.backingFilePath
}
val backingFilePath =
(element.containingFile as? KtFile)?.let {
it.backingFilePath ?: it.originalKtFile?.backingFilePath
}

if (backingFilePath != null) {
findModuleForSourceId(backingFilePath.pathString)?.let { return it }
Expand Down Expand Up @@ -148,14 +160,12 @@ internal class ProjectStructureProvider : KtLspService, KotlinProjectStructurePr
}

@OptIn(KaPlatformInterface::class)
override fun getNotUnderContentRootModule(project: Project): KaNotUnderContentRootModule {
return notUnderContentRootModuleWithoutPsiFile
}
override fun getNotUnderContentRootModule(project: Project): KaNotUnderContentRootModule = notUnderContentRootModuleWithoutPsiFile

private fun searchVirtualFileInModule(
vf: VirtualFile,
module: KaModule,
visited: MutableSet<KaModule>
visited: MutableSet<KaModule>,
): KaModule? {
if (visited.contains(module)) return null
if (module.contentScope.contains(vf)) return module
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
package com.itsaky.androidide.lsp.kotlin.compiler.index

import com.google.common.truth.Truth.assertThat
import com.itsaky.androidide.eventbus.events.editor.ChangeType
import com.itsaky.androidide.eventbus.events.editor.DocumentChangeEvent
import com.itsaky.androidide.eventbus.events.editor.DocumentCloseEvent
import com.itsaky.androidide.eventbus.events.editor.DocumentOpenEvent
import com.itsaky.androidide.lsp.kotlin.compiler.modules.AnalysisPriority
import com.itsaky.androidide.lsp.kotlin.fixtures.KtLspTest
import com.itsaky.androidide.models.Range
import com.itsaky.androidide.projects.FileManager
import org.jetbrains.kotlin.analysis.api.components.KaDiagnosticCheckerFilter
import org.jetbrains.kotlin.com.intellij.psi.util.PsiTreeUtil
import org.jetbrains.kotlin.psi.KtElement
import org.junit.After
import org.junit.Test
import java.nio.file.Path

/**
* Typing inside a function body must not make the enclosing class a redeclaration of itself.
*
* Reproduces GitHub issue #2152: open a file, let diagnostics run, type one space inside an empty
* function body, and the next diagnostics run reports `Redeclaration: class LocalC : Any` across the
* whole class.
*/
internal class InBodyEditRedeclarationTest : KtLspTest() {
override val enableParserEventSystem = true

private val openedPaths = mutableListOf<Path>()

@After
fun closeDocs() {
openedPaths.forEach { FileManager.onDocumentClose(DocumentCloseEvent(it)) }
openedPaths.clear()
}

private fun localC(bodyLine: String) = "package p\n\nclass LocalC {\n fun ori() {\n$bodyLine\n }\n}\n"

private val original = localC(" ")

private val withSpaceInBody = localC(" ")

private fun diagnosticsFor(path: Path): List<String> =
env.ktSymbolIndex.withLiveKtFile(path) { live ->
live.analyzing(AnalysisPriority.DIAGNOSTICS, noopCancelChecker()) { ktFile ->
ktFile
.collectDiagnostics(KaDiagnosticCheckerFilter.EXTENDED_AND_COMMON_CHECKERS)
.map { "${it.factoryName}: ${it.defaultMessage}" }
}
}!!

/** What a completion request does with the buffer: analyse a placeholder copy and resolve the caret's scope. */
private fun completeAt(
path: Path,
offset: Int,
) {
val buffer = FileManager.getDocumentContents(path)
val withPlaceholder = buffer.substring(0, offset) + "KT_COMPLETION_PLACEHOLDER" + buffer.substring(offset)
env.ktSymbolIndex.withLiveKtFile(path) { live ->
live.analyzingVariant(path.fileName.toString(), withPlaceholder, AnalysisPriority.INTERACTIVE, noopCancelChecker()) { variant ->
val position = PsiTreeUtil.getParentOfType(variant.findElementAt(offset), KtElement::class.java)!!
variant.scopeContext(position).scopes.size
}
}
}

@Test
fun `typing a space inside a function body reports no redeclaration`() {
createSourceFile("LocalC.kt", original)
val path = env.sourceRoots.first().resolve("LocalC.kt")
FileManager.onDocumentOpen(DocumentOpenEvent(path, original, 1))
openedPaths.add(path)
assertThat(diagnosticsFor(path)).isEmpty()

FileManager.onDocumentContentChange(
DocumentChangeEvent(path, " ", withSpaceInBody, 2, ChangeType.INSERT, 1, Range.NONE),
)
completeAt(path, withSpaceInBody.indexOf("ori() {\n") + "ori() {\n ".length)

assertThat(diagnosticsFor(path)).isEmpty()
}
}
Loading