Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
28 commits
Select commit Hold shift + click to select a range
1b069cb
fix: add ability to re-write class name references in desugar plugin
itsaky-adfa Mar 19, 2026
a70fd66
feat: integrate Kotlin analysis API
itsaky-adfa Mar 19, 2026
4ca1e97
Merge branch 'stage' into fix/ADFA-3366-include-analysis-api-as-depen…
itsaky-adfa Mar 19, 2026
43286a6
fix: update kotlin-android to latest version
itsaky-adfa Mar 23, 2026
f1fe62f
fix: remove UnsafeImpl
itsaky-adfa Mar 25, 2026
6e6d8b3
fix: update kotlin-android to latest version
itsaky-adfa Mar 25, 2026
b208658
fix: replace usages of Unsafe with UnsafeImpl
itsaky-adfa Mar 24, 2026
c844ad2
fix: make Kotlin LSP no-op
itsaky-adfa Mar 23, 2026
58db2cb
feat: configure K2 standalone session when setting up LSP
itsaky-adfa Mar 24, 2026
bf7acd1
fix: JvmTarget resolution fails for input "21"
itsaky-adfa Mar 24, 2026
dc62a51
fix: do not early-init VirtualFileSystem
itsaky-adfa Mar 24, 2026
4b1c8e4
fix: remove replaceClass desugar instruction for Unsafe
itsaky-adfa Mar 25, 2026
b14f6ee
fix: ensure boot class path is added as dependency to Android modules
itsaky-adfa Mar 26, 2026
54ca7a9
feat: add diagnostic provider for Kotlin
itsaky-adfa Mar 26, 2026
6e4d458
fix: remove unnecessary log statement
itsaky-adfa Mar 26, 2026
5d841a3
fix: update to latest kotlin-android release
itsaky-adfa Mar 26, 2026
4b7b0f2
fix: always re-initialize K2 session on setupWithProject
itsaky-adfa Mar 26, 2026
e2f137a
fix: diagnostics are always collected from the on-disk file
itsaky-adfa Mar 26, 2026
09fc9ea
feat: add the ability to incrementally invalidate source roots on pro…
itsaky-adfa Mar 30, 2026
dd3d519
fix: dispatch build-related events from GradleBuildService
itsaky-adfa Mar 31, 2026
d6defa6
feat: introduct KtFileManager
itsaky-adfa Mar 31, 2026
1586b8f
fix: remove unused onSourcesChanged func
itsaky-adfa Apr 16, 2026
85807ca
fix: remove IncrementalModificationTracker
itsaky-adfa Apr 16, 2026
abecf1a
fix: remove unused Gradle build events
itsaky-adfa Apr 16, 2026
68e316a
Merge branch 'stage' into feat/ADFA-3320-session-source-files-invalid…
itsaky-adfa Apr 18, 2026
4988c26
Merge branch 'stage' into feat/ADFA-3320-session-source-files-invalid…
itsaky-adfa Apr 20, 2026
d54e63a
Merge branch 'feat/ADFA-3320-session-source-files-invalidation' into …
itsaky-adfa Apr 20, 2026
6d858b3
Merge branch 'stage' into feat/ADFA-3320-KtFileManager
itsaky-adfa Apr 20, 2026
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
@@ -0,0 +1,12 @@
package com.itsaky.androidide.lsp.kotlin

import java.nio.file.Path

interface FileEventConsumer {

fun onFileOpened(path: Path, content: String)
fun onFileClosed(path: Path)

fun onFileContentChanged(path: Path, content: String)
fun onFileSaved(path: Path)
}
Original file line number Diff line number Diff line change
Expand Up @@ -22,13 +22,14 @@ import com.itsaky.androidide.app.configuration.IJdkDistributionProvider
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.eventbus.events.editor.DocumentSaveEvent
import com.itsaky.androidide.eventbus.events.editor.DocumentSelectedEvent
import com.itsaky.androidide.lsp.api.ILanguageClient
import com.itsaky.androidide.lsp.api.ILanguageServer
import com.itsaky.androidide.lsp.api.IServerSettings
import com.itsaky.androidide.lsp.kotlin.compiler.Compiler
import com.itsaky.androidide.lsp.kotlin.compiler.KotlinProjectModel
import com.itsaky.androidide.lsp.kotlin.diagnostic.KotlinDiagnosticProvider
import com.itsaky.androidide.lsp.kotlin.diagnostic.collectDiagnosticsFor
import com.itsaky.androidide.lsp.models.CompletionParams
import com.itsaky.androidide.lsp.models.CompletionResult
import com.itsaky.androidide.lsp.models.DefinitionParams
Expand Down Expand Up @@ -76,7 +77,6 @@ class KotlinLanguageServer : ILanguageServer {
CoroutineScope(SupervisorJob() + CoroutineName(KotlinLanguageServer::class.simpleName!!))
private var projectModel: KotlinProjectModel? = null
private var compiler: Compiler? = null
private var diagnosticProvider: KotlinDiagnosticProvider? = null
private var analyzeJob: Job? = null

override val serverId: String = SERVER_ID
Expand Down Expand Up @@ -106,7 +106,6 @@ class KotlinLanguageServer : ILanguageServer {
override fun shutdown() {
EventBus.getDefault().unregister(this)
scope.cancel("LSP is being shut down")
diagnosticProvider?.close()
compiler?.close()
initialized = false
}
Expand Down Expand Up @@ -150,7 +149,6 @@ class KotlinLanguageServer : ILanguageServer {
)

this.compiler = compiler
this.diagnosticProvider = KotlinDiagnosticProvider(compiler, scope)
} else {
logger.info("Updating project model")

Expand Down Expand Up @@ -221,7 +219,7 @@ class KotlinLanguageServer : ILanguageServer {
return DiagnosticResult.NO_UPDATE
}

return diagnosticProvider?.analyze(file)
return compiler?.compilationEnvironmentFor(file)?.collectDiagnosticsFor(file)
?: DiagnosticResult.NO_UPDATE
}

Expand All @@ -232,6 +230,11 @@ class KotlinLanguageServer : ILanguageServer {
return
}

compiler?.compilationEnvironmentFor(event.openedFile)?.apply {
val content = FileManager.getDocumentContents(event.openedFile)
fileManager.onFileOpened(event.openedFile, content)
}

selectedFile = event.openedFile
debouncingAnalyze()
}
Expand Down Expand Up @@ -262,6 +265,13 @@ class KotlinLanguageServer : ILanguageServer {
if (!DocumentUtils.isKotlinFile(event.changedFile)) {
return
}

compiler?.compilationEnvironmentFor(event.changedFile)?.apply {
val content = FileManager.getDocumentContents(event.changedFile)
logger.info("Notifying KtFileManager for file {} with contents {}", event.changedFile, content)
Comment thread
itsaky-adfa marked this conversation as resolved.
fileManager.onFileContentChanged(event.changedFile, content)
}

debouncingAnalyze()
}

Expand All @@ -272,13 +282,29 @@ class KotlinLanguageServer : ILanguageServer {
return
}

diagnosticProvider?.clearTimestamp(event.closedFile)
compiler?.compilationEnvironmentFor(event.closedFile)?.apply {
fileManager.onFileClosed(event.closedFile)
fileManager.clearAnalyzeTimestampOf(event.closedFile)
}

if (FileManager.getActiveDocumentCount() == 0) {
selectedFile = null
analyzeJob?.cancel("No active files")
}
}

@Subscribe(threadMode = ThreadMode.ASYNC)
Comment thread
itsaky-adfa marked this conversation as resolved.
@Suppress("unused")
fun onDocumentSaved(event: DocumentSaveEvent) {
if (!DocumentUtils.isKotlinFile(event.savedFile)) {
return
}

compiler?.compilationEnvironmentFor(event.savedFile)?.apply {
fileManager.onFileSaved(event.savedFile)
}
}

@Subscribe(threadMode = ThreadMode.ASYNC)
@Suppress("unused")
fun onDocumentSelected(event: DocumentSelectedEvent) {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,193 @@
package com.itsaky.androidide.lsp.kotlin

import org.jetbrains.kotlin.analysis.api.KaSession
import org.jetbrains.kotlin.analysis.api.analyze
import org.jetbrains.kotlin.analysis.api.analyzeCopy
import org.jetbrains.kotlin.analysis.api.projectStructure.KaDanglingFileResolutionMode
import org.jetbrains.kotlin.com.intellij.openapi.editor.Document
import org.jetbrains.kotlin.com.intellij.openapi.vfs.StandardFileSystems
import org.jetbrains.kotlin.com.intellij.openapi.vfs.VirtualFileManager
import org.jetbrains.kotlin.com.intellij.psi.PsiDocumentManager
import org.jetbrains.kotlin.com.intellij.psi.PsiManager
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.psi.KtPsiFactory
import org.slf4j.LoggerFactory
import java.nio.file.Path
import java.util.concurrent.ConcurrentHashMap
import kotlin.io.path.name
import kotlin.io.path.pathString
import kotlin.time.Clock
import kotlin.time.Instant

/**
* Manages [KtFile] instances for all open files.
*/
class KtFileManager(
private val psiFactory: KtPsiFactory,
private val psiManager: PsiManager,
private val psiDocumentManager: PsiDocumentManager,
) : FileEventConsumer, AutoCloseable {

companion object {
private val logger = LoggerFactory.getLogger(KtFileManager::class.java)
}

private val entries = ConcurrentHashMap<Path, ManagedFile>()

@ConsistentCopyVisibility
data class ManagedFile @Deprecated("Use ManagedFile.create instead") internal constructor(
val file: Path,
val diskKtFile: KtFile,
@Volatile var inMemoryKtFile: KtFile,
val document: Document,
@Volatile var lastModified: Instant,
@Volatile var isDirty: Boolean,
@Volatile var analyzeTimestamp: Instant,
) {

/**
* Analyze this [ManagedFile] contents.
*
* @param action The analysis action.
*/
fun <R> analyze(action: KaSession.(file: KtFile) -> R): R {
if (diskKtFile === inMemoryKtFile) {
return analyze(useSiteElement = inMemoryKtFile) { action(inMemoryKtFile) }
}

return analyzeCopy(
useSiteElement = inMemoryKtFile,
resolutionMode = KaDanglingFileResolutionMode.PREFER_SELF
) {
action(inMemoryKtFile)
}
}

fun createInMemoryFileWithContent(psiFactory: KtPsiFactory, content: String): KtFile {
val inMemoryFile = psiFactory.createFile(file.name, content)
inMemoryFile.originalFile = diskKtFile
return inMemoryFile
}

companion object {
@Suppress("DEPRECATION")
fun create(
file: Path,
ktFile: KtFile,
document: Document,
inMemoryKtFile: KtFile = ktFile,
lastModified: Instant = Clock.System.now(),
isDirty: Boolean = false,
analyzeTimestamp: Instant = Instant.DISTANT_PAST,
) =
ManagedFile(
file = file,
diskKtFile = ktFile,
inMemoryKtFile = inMemoryKtFile,
document = document,
lastModified = lastModified,
isDirty = isDirty,
analyzeTimestamp = analyzeTimestamp,
)
}
}

override fun onFileOpened(path: Path, content: String) {
logger.debug("onFileOpened: {}", path)

entries[path]?.let { existing ->
logger.info("File is already opened, updating content")
updateDocumentContent(existing, content)
return
}

val ktFile = resolveKtFile(path)

if (ktFile == null) {
logger.warn("Cannot resolve KtFile for: {}", path)
return
}

val document = getOrCreateDocument(ktFile)
if (document == null) {
logger.warn("Cannot obtain Document for: {}", path)
return
}

logger.info("Creating managed file entry")
val entry = ManagedFile.create(
file = path,
ktFile = ktFile,
document = document,
)

entries[path] = entry

updateDocumentContent(entry, content)
logger.debug("File opened and managed: {}", path)
return
}

override fun onFileContentChanged(path: Path, content: String) {
logger.debug("onFileContentChanged: {}", path)
val entry = entries[path] ?: run {
logger.debug("Content changed for unmanaged file: {}. Ignoring.", path)
return
}

updateDocumentContent(entry, content)
}

override fun onFileSaved(path: Path) {
val entry = entries[path] ?: return
entry.isDirty = false

logger.debug("File saved: {}", path)
}

override fun onFileClosed(path: Path) {
entries.remove(path) ?: return
logger.debug("File closed: {}", path)
}

fun getOpenFile(path: Path): ManagedFile? = entries[path]

fun allOpenFiles(): Collection<ManagedFile> =
entries.values.toList()

fun clearAnalyzeTimestampOf(file: Path) {
val managed = getOpenFile(file) ?: return
managed.analyzeTimestamp = Instant.DISTANT_PAST
}

private fun resolveKtFile(path: Path): KtFile? {
val vfs = VirtualFileManager.getInstance()
.getFileSystem(StandardFileSystems.FILE_PROTOCOL)

val virtualFile = vfs.refreshAndFindFileByPath(path.pathString)
Comment thread
itsaky-adfa marked this conversation as resolved.
?: return null

val psiFile = psiManager.findFile(virtualFile)

return psiFile as? KtFile
}

private fun getOrCreateDocument(ktFile: KtFile): Document? {
return psiDocumentManager.getDocument(ktFile)
}

private fun updateDocumentContent(entry: ManagedFile, content: String) {
logger.info("Updating doc content for {}", entry.file)

val normalized = content.replace("\r", "")
if (entry.inMemoryKtFile.text == normalized) return

entry.inMemoryKtFile = entry.createInMemoryFileWithContent(psiFactory, content)
entry.lastModified = Clock.System.now()
entry.isDirty = true
}

override fun close() {
entries.clear()
}
}
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
package com.itsaky.androidide.lsp.kotlin.compiler

import com.itsaky.androidide.lsp.kotlin.FileEventConsumer
import com.itsaky.androidide.lsp.kotlin.KtFileManager
import org.jetbrains.kotlin.analysis.api.KaExperimentalApi
import org.jetbrains.kotlin.analysis.api.platform.declarations.KotlinAnnotationsResolverFactory
import org.jetbrains.kotlin.analysis.api.platform.declarations.KotlinDeclarationProviderFactory
Expand Down Expand Up @@ -61,9 +63,13 @@ class CompilationEnvironment(

var session: StandaloneAnalysisAPISession
private set

var parser: KtPsiFactory
private set

var fileManager: KtFileManager
private set

val psiManager: PsiManager
get() = PsiManager.getInstance(session.project)

Expand Down Expand Up @@ -101,6 +107,7 @@ class CompilationEnvironment(
init {
session = buildSession()
parser = KtPsiFactory(session.project, eventSystemEnabled = enableParserEventSystem)
fileManager = KtFileManager(parser, psiManager, psiDocumentManager)

projectModel.addListener(this)
}
Expand Down Expand Up @@ -225,6 +232,7 @@ class CompilationEnvironment(
}

override fun close() {
fileManager.close()
projectModel.removeListener(this)
disposable.dispose()
}
Expand Down
Loading
Loading