From 8a4f3ade2c790f939db546367b22e34e9f0f6205 Mon Sep 17 00:00:00 2001 From: Akash Yadav Date: Tue, 17 Nov 2026 00:07:40 +0530 Subject: [PATCH] feat(lsp): analyze the source sets of the selected variant Also fixes Java go-to-definition into another file after a completion: the reused javac context keeps a class an earlier request compiled without its tree, so RemoteDefinitionProvider now compiles the declaring file with the current one. The variant definition test depends on it. --- .../definition/RemoteDefinitionProvider.kt | 44 ++++--- .../lsp/java/VariantSourceSetsTest.kt | 70 +++++++++++ .../DefinitionAfterCompletionTest.kt | 40 +++++++ .../lsp/kotlin/KotlinLanguageServer.kt | 5 +- .../AbstractCompilationEnvironment.kt | 9 ++ .../kotlin/compiler/CompilationEnvironment.kt | 40 ++++++- .../lsp/kotlin/compiler/KotlinModuleLayout.kt | 13 +- .../kotlin/completion/KotlinCompletions.kt | 19 ++- .../diagnostic/KotlinDiagnosticProvider.kt | 43 ++++--- .../signaturehelp/KotlinSignatureHelp.kt | 4 +- .../lsp/kotlin/utils/ContextResolver.kt | 108 +++++++++++------ .../lsp/kotlin/VariantSourceSetsTest.kt | 101 ++++++++++++++++ .../kotlin/compiler/KotlinModuleLayoutTest.kt | 10 ++ .../lsp/kotlin/fixtures/KtLspTest.kt | 10 +- .../kotlin/fixtures/KtLspTestEnvironment.kt | 39 +++++- .../lsp/kotlin/fixtures/KtLspTestRule.kt | 4 + .../kotlin/fixtures/VariantProjectFixtures.kt | 113 ++++++++++++++++++ .../androidide/projects/api/AndroidModule.kt | 9 +- .../projects/api/ArtifactScopeSourcesTest.kt | 82 +++++++++++++ .../test/app/variant/VariantConfig.java | 5 + .../CompletesMainActivity_template.java | 7 ++ .../ReferencesMainActivity_template.java | 5 + .../variants/VariantDefinition_template.java | 7 ++ .../variants/VariantMembers_template.java | 9 ++ .../variants/VariantUse_template.java | 8 ++ .../test/app/variant/VariantConfig.java | 5 + 26 files changed, 709 insertions(+), 100 deletions(-) create mode 100644 lsp/java/src/test/java/com/itsaky/androidide/lsp/java/VariantSourceSetsTest.kt create mode 100644 lsp/java/src/test/java/com/itsaky/androidide/lsp/java/providers/DefinitionAfterCompletionTest.kt create mode 100644 lsp/kotlin/src/test/java/com/itsaky/androidide/lsp/kotlin/VariantSourceSetsTest.kt create mode 100644 lsp/kotlin/src/test/java/com/itsaky/androidide/lsp/kotlin/fixtures/VariantProjectFixtures.kt create mode 100644 testing/resources/test-project/app/src/debug/java/com/itsaky/test/app/variant/VariantConfig.java create mode 100644 testing/resources/test-project/app/src/main/resources/definition/CompletesMainActivity_template.java create mode 100644 testing/resources/test-project/app/src/main/resources/definition/ReferencesMainActivity_template.java create mode 100644 testing/resources/test-project/app/src/main/resources/variants/VariantDefinition_template.java create mode 100644 testing/resources/test-project/app/src/main/resources/variants/VariantMembers_template.java create mode 100644 testing/resources/test-project/app/src/main/resources/variants/VariantUse_template.java create mode 100644 testing/resources/test-project/app/src/release/java/com/itsaky/test/app/variant/VariantConfig.java diff --git a/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/providers/definition/RemoteDefinitionProvider.kt b/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/providers/definition/RemoteDefinitionProvider.kt index da9a574de7..671e10d331 100644 --- a/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/providers/definition/RemoteDefinitionProvider.kt +++ b/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/providers/definition/RemoteDefinitionProvider.kt @@ -19,11 +19,15 @@ package com.itsaky.androidide.lsp.java.providers.definition import com.itsaky.androidide.lsp.api.IServerSettings import com.itsaky.androidide.lsp.java.compiler.JavaCompilerService +import com.itsaky.androidide.lsp.java.compiler.SourceFileObject +import com.itsaky.androidide.lsp.java.utils.FindHelper +import com.itsaky.androidide.lsp.java.utils.NavigationHelper import com.itsaky.androidide.models.Location import com.itsaky.androidide.models.Position import com.itsaky.androidide.progress.ICancelChecker import jdkx.lang.model.element.Element import jdkx.tools.JavaFileObject +import openjdk.source.util.Trees import java.nio.file.Path /** @@ -32,24 +36,30 @@ import java.nio.file.Path * @author Akash Yadav */ class RemoteDefinitionProvider( - position: Position, - completingFile: Path, - compiler: JavaCompilerService, - settings: IServerSettings, cancelChecker: ICancelChecker, + position: Position, + completingFile: Path, + compiler: JavaCompilerService, + settings: IServerSettings, + cancelChecker: ICancelChecker, ) : IJavaDefinitionProvider(position, completingFile, compiler, settings, cancelChecker) { + private lateinit var otherFile: JavaFileObject - private lateinit var otherFile: JavaFileObject + fun setOtherFile(jfo: JavaFileObject): RemoteDefinitionProvider { + this.otherFile = jfo + return this + } - fun setOtherFile(jfo: JavaFileObject): RemoteDefinitionProvider { - this.otherFile = jfo - return this - } - - override fun doFindDefinition(element: Element): List { -// val task = compiler.compile(listOf(SourceFileObject(file), otherFile)) - val provider = LocalDefinitionProvider(position, file, compiler, settings, this) - return provider.findDefinition(element) -// return provider -// .findDefinition(task.get { NavigationHelper.findElement(it, file, line, column) }) - } + // The compiler reuses one javac context: a class an earlier request compiled stays known without its + // tree, so the declaration only has a path when its file is compiled together with this one. + override fun doFindDefinition(element: Element): List = + compiler.compile(listOf(SourceFileObject(file), otherFile)).get { task -> + val inBatch = NavigationHelper.findElement(task, file, line, column, this) ?: return@get emptyList() + val path = Trees.instance(task.task).getPath(inBatch) + if (path == null) { + log.error("TreePath of element is null. Cannot find definition. Element is {}", inBatch) + return@get emptyList() + } + val name = if (inBatch.simpleName.contentEquals("")) inBatch.enclosingElement.simpleName else inBatch.simpleName + listOf(FindHelper.location(task, path, name)) + } } diff --git a/lsp/java/src/test/java/com/itsaky/androidide/lsp/java/VariantSourceSetsTest.kt b/lsp/java/src/test/java/com/itsaky/androidide/lsp/java/VariantSourceSetsTest.kt new file mode 100644 index 0000000000..1e754083d1 --- /dev/null +++ b/lsp/java/src/test/java/com/itsaky/androidide/lsp/java/VariantSourceSetsTest.kt @@ -0,0 +1,70 @@ +package com.itsaky.androidide.lsp.java + +import com.google.common.truth.Truth.assertThat +import com.itsaky.androidide.lsp.models.CompletionParams +import com.itsaky.androidide.lsp.models.DefinitionParams +import com.itsaky.androidide.lsp.models.DiagnosticSeverity +import com.itsaky.androidide.models.Position +import com.itsaky.androidide.progress.ICancelChecker +import com.itsaky.androidide.projects.util.findAppModule +import kotlinx.coroutines.runBlocking +import org.junit.Before +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner + +/** + * The test project's app has `VariantConfig` in both `src/debug` and `src/release`, each with its own + * field. Synced with `debug` selected, every Java feature must see the debug copy and never the + * release one. + */ +@RunWith(RobolectricTestRunner::class) +class VariantSourceSetsTest { + @Before + fun setup() { + JavaLSPTest.setup() + assertThat(findAppModule()?.getSelectedVariant()?.name).isEqualTo("debug") + } + + @Test + fun `completion offers the selected variant's members and not another variant's`() { + JavaLSPTest.apply { + openFile("variants/VariantMembers") + + val labels = + server + .complete(CompletionParams(cursorPosition(), file!!, ICancelChecker.NOOP).apply { prefix = "" }) + .items + .map { it.ideLabel.toString() } + + assertThat(labels).contains("DEBUG_ONLY_FIELD") + assertThat(labels).doesNotContain("RELEASE_ONLY_FIELD") + } + } + + @Test + fun `diagnostics resolve the selected variant's sources and flag another variant's`() { + JavaLSPTest.apply { + openFile("variants/VariantUse") + + val errors = runBlocking { server.analyze(file!!) }.diagnostics.filter { it.severity == DiagnosticSeverity.ERROR } + + // Line 6 reads RELEASE_ONLY_FIELD; line 5 reads DEBUG_ONLY_FIELD and must resolve. + assertThat(errors.map { it.range.start.line }.distinct()).containsExactly(6) + } + } + + @Test + fun `definition goes to the selected variant's copy of a class`() { + JavaLSPTest.apply { + openFile("variants/VariantDefinition") + + // On `VariantConfig` in `String d = VariantConfig.DEBUG_ONLY_FIELD;` + val params = DefinitionParams(file!!, Position(5, 18), ICancelChecker.NOOP) + val files = runBlocking { server.findDefinition(params) }.locations.map { it.file.toString() } + + assertThat(files).isNotEmpty() + assertThat(files.filterNot { "/src/debug/java/" in it }).isEmpty() + } + } +} diff --git a/lsp/java/src/test/java/com/itsaky/androidide/lsp/java/providers/DefinitionAfterCompletionTest.kt b/lsp/java/src/test/java/com/itsaky/androidide/lsp/java/providers/DefinitionAfterCompletionTest.kt new file mode 100644 index 0000000000..506fec13ed --- /dev/null +++ b/lsp/java/src/test/java/com/itsaky/androidide/lsp/java/providers/DefinitionAfterCompletionTest.kt @@ -0,0 +1,40 @@ +package com.itsaky.androidide.lsp.java.providers + +import com.google.common.truth.Truth.assertThat +import com.itsaky.androidide.lsp.java.JavaLSPTest +import com.itsaky.androidide.lsp.models.CompletionParams +import com.itsaky.androidide.lsp.models.DefinitionParams +import com.itsaky.androidide.models.Position +import com.itsaky.androidide.progress.ICancelChecker +import kotlinx.coroutines.runBlocking +import org.junit.Before +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner + +/** + * The compiler reuses one javac context, so a class an earlier request compiled is already known + * when a later request asks for its declaration in another file. + */ +@RunWith(RobolectricTestRunner::class) +class DefinitionAfterCompletionTest { + @Before + fun setup() { + JavaLSPTest.setup() + } + + @Test + fun `definition finds a class in another file that an earlier completion compiled`() { + JavaLSPTest.apply { + openFile("definition/CompletesMainActivity") + server.complete(CompletionParams(cursorPosition(), file!!, ICancelChecker.NOOP).apply { prefix = "" }) + + openFile("definition/ReferencesMainActivity") + // On `MainActivity` in `MainActivity activity;` + val params = DefinitionParams(file!!, Position(3, 6), ICancelChecker.NOOP) + val files = runBlocking { server.findDefinition(params) }.locations.map { it.file.fileName.toString() } + + assertThat(files).containsExactly("MainActivity.java") + } + } +} diff --git a/lsp/kotlin/src/main/java/com/itsaky/androidide/lsp/kotlin/KotlinLanguageServer.kt b/lsp/kotlin/src/main/java/com/itsaky/androidide/lsp/kotlin/KotlinLanguageServer.kt index 0eeacae22f..02c1a84b4f 100644 --- a/lsp/kotlin/src/main/java/com/itsaky/androidide/lsp/kotlin/KotlinLanguageServer.kt +++ b/lsp/kotlin/src/main/java/com/itsaky/androidide/lsp/kotlin/KotlinLanguageServer.kt @@ -38,7 +38,6 @@ import com.itsaky.androidide.lsp.kotlin.compiler.KotlinProjectModel import com.itsaky.androidide.lsp.kotlin.compiler.kotlinModuleLayout import com.itsaky.androidide.lsp.kotlin.completion.KotlinSnippetRepository import com.itsaky.androidide.lsp.kotlin.completion.codeComplete -import com.itsaky.androidide.lsp.kotlin.diagnostic.collectDiagnosticsFor import com.itsaky.androidide.lsp.kotlin.format.KotlinCodeFormatter import com.itsaky.androidide.lsp.kotlin.navigation.findDefinitionAt import com.itsaky.androidide.lsp.kotlin.navigation.findUsagesAt @@ -384,8 +383,8 @@ class KotlinLanguageServer : ILanguageServer { } return compiler - ?.compilationEnvironmentFor(file) - ?.let { context(it) { collectDiagnosticsFor(file, createJobCancelChecker()) } } + ?.compilationEnvironmentForKotlinPath(file) + ?.diagnosticsFor(file, createJobCancelChecker()) ?: DiagnosticResult.NO_UPDATE } diff --git a/lsp/kotlin/src/main/java/com/itsaky/androidide/lsp/kotlin/compiler/AbstractCompilationEnvironment.kt b/lsp/kotlin/src/main/java/com/itsaky/androidide/lsp/kotlin/compiler/AbstractCompilationEnvironment.kt index fb7dd401c5..f17a2265d9 100644 --- a/lsp/kotlin/src/main/java/com/itsaky/androidide/lsp/kotlin/compiler/AbstractCompilationEnvironment.kt +++ b/lsp/kotlin/src/main/java/com/itsaky/androidide/lsp/kotlin/compiler/AbstractCompilationEnvironment.kt @@ -15,10 +15,12 @@ import com.itsaky.androidide.lsp.kotlin.compiler.services.ResolutionScopeProvide import com.itsaky.androidide.lsp.kotlin.compiler.services.WriteAccessGuard import com.itsaky.androidide.lsp.kotlin.compiler.services.latestLanguageVersionSettings import com.itsaky.androidide.lsp.kotlin.compiler.util.SLF4JLogger +import com.itsaky.androidide.lsp.kotlin.utils.SymbolVisibilityChecker import com.itsaky.androidide.lsp.kotlin.utils.toVirtualFileOrNull import com.itsaky.androidide.progress.ICancelChecker import kotlinx.coroutines.runBlocking import kotlinx.coroutines.withTimeoutOrNull +import org.appdevforall.codeonthego.indexing.jvm.JvmSymbolIndex import org.jetbrains.kotlin.K1Deprecation import org.jetbrains.kotlin.analysis.api.KaImplementationDetail import org.jetbrains.kotlin.analysis.api.platform.analysisMessageBus @@ -151,6 +153,13 @@ internal abstract class AbstractCompilationEnvironment( val psiManager: PsiManager get() = PsiManager.getInstance(project) + val symbolVisibilityChecker: SymbolVisibilityChecker by lazy { + SymbolVisibilityChecker(ProjectStructureProvider.getInstance(project)) + } + + /** The indexes completion searches for symbols to offer with an import, in that order: source first. */ + abstract val unimportedSymbolIndexes: List + protected abstract fun createServiceRegistrars(): List /** diff --git a/lsp/kotlin/src/main/java/com/itsaky/androidide/lsp/kotlin/compiler/CompilationEnvironment.kt b/lsp/kotlin/src/main/java/com/itsaky/androidide/lsp/kotlin/compiler/CompilationEnvironment.kt index b48032b191..574d75e720 100644 --- a/lsp/kotlin/src/main/java/com/itsaky/androidide/lsp/kotlin/compiler/CompilationEnvironment.kt +++ b/lsp/kotlin/src/main/java/com/itsaky/androidide/lsp/kotlin/compiler/CompilationEnvironment.kt @@ -9,10 +9,11 @@ import com.itsaky.androidide.lsp.kotlin.compiler.modules.asFlatSequence import com.itsaky.androidide.lsp.kotlin.compiler.modules.backingFilePath import com.itsaky.androidide.lsp.kotlin.compiler.registrar.AnalysisApiServiceProviders import com.itsaky.androidide.lsp.kotlin.compiler.registrar.LspAnalysisApiServiceRegistrar -import com.itsaky.androidide.lsp.kotlin.compiler.services.ProjectStructureProvider import com.itsaky.androidide.lsp.kotlin.compiler.services.ResolutionScopeProvider +import com.itsaky.androidide.lsp.kotlin.diagnostic.DiagnosticsOutcome import com.itsaky.androidide.lsp.kotlin.diagnostic.collectDiagnosticsFor -import com.itsaky.androidide.lsp.kotlin.utils.SymbolVisibilityChecker +import com.itsaky.androidide.lsp.models.DiagnosticResult +import com.itsaky.androidide.progress.ICancelChecker import com.itsaky.androidide.projects.FileManager import com.itsaky.androidide.utils.KeyedDebouncingAction import io.sentry.Sentry @@ -122,9 +123,10 @@ internal class CompilationEnvironment( val generatedIndex: JvmSymbolIndex? get() = ktProject.generatedIndex - val symbolVisibilityChecker: SymbolVisibilityChecker by lazy { - SymbolVisibilityChecker(ProjectStructureProvider.getInstance(project)) - } + // Source first, library last: one shared cap across the indexes means whichever is queried last + // loses when the cap binds, and a project symbol is likelier to be the one being reached for. + override val unimportedSymbolIndexes: List + get() = listOfNotNull(sourceIndex, generatedIndex, libraryIndex) var languageClient: ILanguageClient? get() = _languageClient @@ -198,7 +200,7 @@ internal class CompilationEnvironment( debounceDuration = DEFAULT_FILE_MOD_EVENT_DEBOUNCE_DURATION, ) { path, cancelChecker -> try { - val result = collectDiagnosticsFor(path, cancelChecker) + val result = diagnosticsFor(path, cancelChecker) withContext(Dispatchers.Main.immediate) { languageClient?.publishDiagnostics(result) } @@ -220,6 +222,32 @@ internal class CompilationEnvironment( } } + /** The diagnostics of [path]; a run the document superseded is scheduled again and reports nothing. */ + fun diagnosticsFor( + path: Path, + cancelChecker: ICancelChecker, + ): DiagnosticResult = + when (val outcome = collectDiagnosticsFor(path, cancelChecker)) { + is DiagnosticsOutcome.Collected -> { + outcome.result + } + + DiagnosticsOutcome.Superseded -> { + /* + * On the debounced path this is a self-send: this runs as fileAnalyzer's own action, so the + * send reads to the worker as a newer key and cancels the run it came from. Deliberate - the + * reschedule still lands, and the only casualty is the NO_UPDATE publish, which had nothing + * to say anyway. Reached from KotlinLanguageServer.analyze() instead, it is a plain reschedule. + */ + fileAnalyzer.schedule(path) + DiagnosticResult.NO_UPDATE + } + + DiagnosticsOutcome.Unavailable -> { + DiagnosticResult.NO_UPDATE + } + } + fun refreshSources() { Sentry.addBreadcrumb("refreshSources (env=$name, modules=${modules.size})") project.writeUnlessDisposed { diff --git a/lsp/kotlin/src/main/java/com/itsaky/androidide/lsp/kotlin/compiler/KotlinModuleLayout.kt b/lsp/kotlin/src/main/java/com/itsaky/androidide/lsp/kotlin/compiler/KotlinModuleLayout.kt index b9b2621044..3ad73a8fc3 100644 --- a/lsp/kotlin/src/main/java/com/itsaky/androidide/lsp/kotlin/compiler/KotlinModuleLayout.kt +++ b/lsp/kotlin/src/main/java/com/itsaky/androidide/lsp/kotlin/compiler/KotlinModuleLayout.kt @@ -5,6 +5,7 @@ import com.itsaky.androidide.projects.api.ModuleProject import com.itsaky.androidide.projects.api.Workspace import com.itsaky.androidide.projects.models.ArtifactScope import com.itsaky.androidide.projects.models.bootClassPaths +import java.io.File import java.nio.file.Path /** @@ -106,7 +107,7 @@ private fun ModuleProject.sourceModuleLayout(): SourceModuleLayout { return SourceModuleLayout( path = path, name = name, - sourceRoots = getSourceDirectories().mapTo(LinkedHashSet()) { it.toPath() }, + sourceRoots = existingRoots(getSourceDirectories()), classpath = getCompileClasspaths(excludeSourceGeneratedClassPath = true).mapTo(LinkedHashSet()) { it.toPath() }, moduleDependencies = getCompileModuleProjects().map { it.path }, apiVersion = kotlinSettings?.apiVersion, @@ -123,7 +124,7 @@ private fun ModuleProject.testModuleLayout( main: SourceModuleLayout, scope: ArtifactScope, ): SourceModuleLayout? { - val sourceRoots = getSourceDirectories(scope).mapTo(LinkedHashSet()) { it.toPath() } + val sourceRoots = existingRoots(getSourceDirectories(scope)) if (sourceRoots.isEmpty()) { return null } @@ -145,8 +146,12 @@ private fun ModuleProject.testModuleLayout( ) } -/** Whether [scope] gets a source module: [testModuleLayout] makes one only when it has source dirs. */ -private fun ModuleProject.hasScopeModule(scope: ArtifactScope): Boolean = getSourceDirectories(scope).isNotEmpty() +/** Whether [scope] gets a source module: [testModuleLayout] makes one only for existing dirs. */ +private fun ModuleProject.hasScopeModule(scope: ArtifactScope): Boolean = existingRoots(getSourceDirectories(scope)).isNotEmpty() /** `unitTest` -> `unit test`. */ private fun ArtifactScope.displayName(): String = moduleSuffix.replace(Regex("[A-Z]")) { " " + it.value.lowercase() } + +// The analysis session drops a root that does not exist when it is built, so a dir created later +// (src/debug/java, most variant layers) must change the layout for the next sync to rebuild it. +private fun existingRoots(dirs: Set): Set = dirs.filter { it.isDirectory }.mapTo(LinkedHashSet()) { it.toPath() } diff --git a/lsp/kotlin/src/main/java/com/itsaky/androidide/lsp/kotlin/completion/KotlinCompletions.kt b/lsp/kotlin/src/main/java/com/itsaky/androidide/lsp/kotlin/completion/KotlinCompletions.kt index bf257190c7..48e25aed39 100644 --- a/lsp/kotlin/src/main/java/com/itsaky/androidide/lsp/kotlin/completion/KotlinCompletions.kt +++ b/lsp/kotlin/src/main/java/com/itsaky/androidide/lsp/kotlin/completion/KotlinCompletions.kt @@ -4,7 +4,7 @@ package com.itsaky.androidide.lsp.kotlin.completion import com.itsaky.androidide.lookup.Lookup import com.itsaky.androidide.lsp.api.describeSnippet -import com.itsaky.androidide.lsp.kotlin.compiler.CompilationEnvironment +import com.itsaky.androidide.lsp.kotlin.compiler.AbstractCompilationEnvironment import com.itsaky.androidide.lsp.kotlin.compiler.modules.AnalysisPreemptedException import com.itsaky.androidide.lsp.kotlin.compiler.modules.AnalysisPriority import com.itsaky.androidide.lsp.kotlin.compiler.modules.ScheduledCancelChecker @@ -130,11 +130,11 @@ private fun Throwable.isCancellation(): Boolean = isAnalysisCancellation() || th /** * Provide code completion for the given completion parameters. * - * @param CompilationEnvironment The compilation environment to use for the code completion. + * @param env The compilation environment to use for the code completion. * @param params The completion parameters. * @return The completion result. */ -context(env: CompilationEnvironment) +context(env: AbstractCompilationEnvironment) internal fun codeComplete(params: CompletionParams): CompletionResult { return try { doComplete(params) @@ -189,7 +189,7 @@ internal fun completionRequestBuffer(params: CompletionParams): CompletionReques * is never preempted by lower-priority work, but is superseded (cancelled and discarded) by a newer * completion request as the user keeps typing. */ -context(env: CompilationEnvironment) +context(env: AbstractCompilationEnvironment) internal fun doComplete(params: CompletionParams): CompletionResult { val result = env.ktSymbolIndex.withLiveKtFile(params.file) { live -> @@ -376,7 +376,7 @@ private fun KaSession.collectExtensionFunctions( to += toCompletionItems(extensionSymbols) } -context(env: CompilationEnvironment, ctx: AnalysisContext) +context(env: AbstractCompilationEnvironment, ctx: AnalysisContext) private fun KaSession.collectScopeCompletions(to: MutableList) { if (ctx.partial.isBlank()) { logger.warn("cannot complete for blank partial candidate") @@ -422,7 +422,7 @@ private fun KaSession.collectScopeCompletions(to: MutableList) { collectKeywordCompletions(to) } -context(env: CompilationEnvironment, ctx: AnalysisContext) +context(env: AbstractCompilationEnvironment, ctx: AnalysisContext) private fun KaSession.collectUnimportedSymbols(to: MutableList) { val currentPackage = ctx.ktElement.containingKtFile.packageDirective @@ -450,12 +450,7 @@ private fun KaSession.collectUnimportedSymbols(to: MutableList) return true } - /* - * Source first, library last. One shared cap across the indexes means whichever is queried last - * loses when the cap binds, and a symbol from the user's own project is likelier to be the one - * they are reaching for than one from a dependency. - */ - val indexes = listOfNotNull(env.sourceIndex, env.generatedIndex, env.libraryIndex) + val indexes = env.unimportedSymbolIndexes collectUnimportedSymbolMatches( indexes = indexes, diff --git a/lsp/kotlin/src/main/java/com/itsaky/androidide/lsp/kotlin/diagnostic/KotlinDiagnosticProvider.kt b/lsp/kotlin/src/main/java/com/itsaky/androidide/lsp/kotlin/diagnostic/KotlinDiagnosticProvider.kt index d74cec13f9..1637d04332 100644 --- a/lsp/kotlin/src/main/java/com/itsaky/androidide/lsp/kotlin/diagnostic/KotlinDiagnosticProvider.kt +++ b/lsp/kotlin/src/main/java/com/itsaky/androidide/lsp/kotlin/diagnostic/KotlinDiagnosticProvider.kt @@ -1,6 +1,6 @@ package com.itsaky.androidide.lsp.kotlin.diagnostic -import com.itsaky.androidide.lsp.kotlin.compiler.CompilationEnvironment +import com.itsaky.androidide.lsp.kotlin.compiler.AbstractCompilationEnvironment import com.itsaky.androidide.lsp.kotlin.compiler.modules.AnalysisPriority import com.itsaky.androidide.lsp.kotlin.compiler.modules.ScheduledCancelChecker import com.itsaky.androidide.lsp.kotlin.utils.toRange @@ -24,7 +24,7 @@ import java.nio.file.Path private val logger = LoggerFactory.getLogger("KotlinDiagnosticProvider") internal data class KotlinDiagnosticExtra( - val compilationEnv: CompilationEnvironment, + val compilationEnv: AbstractCompilationEnvironment, val action: ActionT, ) @@ -42,11 +42,25 @@ internal sealed interface DiagnosticAction { data object NullSafetyFix : DiagnosticAction } -context(env: CompilationEnvironment) +/** What one diagnostics run for a file produced. */ +internal sealed interface DiagnosticsOutcome { + /** The diagnostics of the file's current text. */ + data class Collected( + val result: DiagnosticResult, + ) : DiagnosticsOutcome + + /** The document changed while the run was in progress, so its diagnostics describe replaced text. */ + data object Superseded : DiagnosticsOutcome + + /** The file could not be analyzed: it is not accessible, or analysis failed. */ + data object Unavailable : DiagnosticsOutcome +} + +context(env: AbstractCompilationEnvironment) internal fun collectDiagnosticsFor( file: Path, cancelChecker: ICancelChecker, -): DiagnosticResult { +): DiagnosticsOutcome { try { logger.info("analyzing file: {}", file) return doAnalyze(file, cancelChecker) @@ -56,16 +70,16 @@ internal fun collectDiagnosticsFor( throw err } logger.error("an error occurred analyzing file: {}", file, err) - return DiagnosticResult.NO_UPDATE + return DiagnosticsOutcome.Unavailable } } @OptIn(KaExperimentalApi::class) -context(env: CompilationEnvironment) +context(env: AbstractCompilationEnvironment) private fun doAnalyze( file: Path, cancelChecker: ICancelChecker, -): DiagnosticResult { +): DiagnosticsOutcome { /* * Diagnostics yield to completion but preempt indexing. The wrapped checker turns a scheduler * preemption into an AnalysisPreemptedException, which CompilationEnvironment's fileAnalyzer catches @@ -142,22 +156,15 @@ private fun doAnalyze( } if (result != null) { - return result + return DiagnosticsOutcome.Collected(result) } if (superseded) { logger.debug("dropping superseded diagnostics for {}", file) - /* - * On the debounced path this is a self-send: doAnalyze runs as fileAnalyzer's own action, so the - * send reads to the worker as a newer key and cancels the run it came from. Deliberate - the - * reschedule still lands, and the only casualty is the NO_UPDATE publish below, which had nothing - * to say anyway. Reached from KotlinLanguageServer.analyze() instead, it is a plain reschedule. - */ - env.fileAnalyzer.schedule(file) - } else { - logger.warn("File {} is not accessible", file) + return DiagnosticsOutcome.Superseded } - return DiagnosticResult.NO_UPDATE + logger.warn("File {} is not accessible", file) + return DiagnosticsOutcome.Unavailable } private fun KaDiagnosticWithPsi<*>.toDiagnosticItem(): DiagnosticItem { diff --git a/lsp/kotlin/src/main/java/com/itsaky/androidide/lsp/kotlin/signaturehelp/KotlinSignatureHelp.kt b/lsp/kotlin/src/main/java/com/itsaky/androidide/lsp/kotlin/signaturehelp/KotlinSignatureHelp.kt index c7d40c881f..d37e81b50e 100644 --- a/lsp/kotlin/src/main/java/com/itsaky/androidide/lsp/kotlin/signaturehelp/KotlinSignatureHelp.kt +++ b/lsp/kotlin/src/main/java/com/itsaky/androidide/lsp/kotlin/signaturehelp/KotlinSignatureHelp.kt @@ -1,6 +1,6 @@ package com.itsaky.androidide.lsp.kotlin.signaturehelp -import com.itsaky.androidide.lsp.kotlin.compiler.CompilationEnvironment +import com.itsaky.androidide.lsp.kotlin.compiler.AbstractCompilationEnvironment import com.itsaky.androidide.lsp.kotlin.compiler.modules.AnalysisPreemptedException import com.itsaky.androidide.lsp.kotlin.compiler.modules.AnalysisPriority import com.itsaky.androidide.lsp.kotlin.compiler.modules.ScheduledCancelChecker @@ -84,7 +84,7 @@ private val logger = LoggerFactory.getLogger("KotlinSignatureHelp") * Computes [SignatureHelp] for the request described by [params], using the given * [CompilationEnvironment] to resolve the enclosing call and analyze it. */ -context(env: CompilationEnvironment) +context(env: AbstractCompilationEnvironment) internal suspend fun doSignatureHelp(params: SignatureHelpParams): SignatureHelp { logger.debug("doSignatureHelp requested for file={} position={}", params.file, params.position) diff --git a/lsp/kotlin/src/main/java/com/itsaky/androidide/lsp/kotlin/utils/ContextResolver.kt b/lsp/kotlin/src/main/java/com/itsaky/androidide/lsp/kotlin/utils/ContextResolver.kt index 51318536ab..10b9def6cd 100644 --- a/lsp/kotlin/src/main/java/com/itsaky/androidide/lsp/kotlin/utils/ContextResolver.kt +++ b/lsp/kotlin/src/main/java/com/itsaky/androidide/lsp/kotlin/utils/ContextResolver.kt @@ -1,6 +1,6 @@ package com.itsaky.androidide.lsp.kotlin.utils -import com.itsaky.androidide.lsp.kotlin.compiler.CompilationEnvironment +import com.itsaky.androidide.lsp.kotlin.compiler.AbstractCompilationEnvironment import com.itsaky.androidide.lsp.kotlin.completion.DeclarationContext import com.itsaky.androidide.lsp.kotlin.completion.DeclarationKind import com.itsaky.androidide.lsp.models.MatchLevel @@ -34,7 +34,7 @@ private val logger = LoggerFactory.getLogger("ContextResolver") * Defines context at the cursor position. */ internal data class AnalysisContext( - val env: CompilationEnvironment, + val env: AbstractCompilationEnvironment, val file: Path, val psiElement: PsiElement, val ktFile: KtFile, @@ -60,11 +60,11 @@ internal data class AnalysisContext( * @param partial The partial identifier at the cursor position. */ internal fun KaSession.resolveAnalysisContext( - env: CompilationEnvironment, + env: AbstractCompilationEnvironment, file: Path, ktFile: KtFile, offset: Int, - partial: String + partial: String, ): AnalysisContext? { val psiElement = ktFile.findElementAt(offset) if (psiElement == null) { @@ -84,11 +84,13 @@ internal fun KaSession.resolveAnalysisContext( // The element is typically a KtModifierList, an error node, // or the incomplete declaration itself. val modifierList = ktElement.getParentOfType(strict = false) - val existingModifiers = modifierList - ?.node?.getChildren(MODIFIER_KEYWORDS) - ?.mapNotNull { it.elementType as? KtModifierKeywordToken } - ?.toSet() - ?: emptySet() + val existingModifiers = + modifierList + ?.node + ?.getChildren(MODIFIER_KEYWORDS) + ?.mapNotNull { it.elementType as? KtModifierKeywordToken } + ?.toSet() + ?: emptySet() val declarationKind = resolveDeclarationKind(ktElement) val declarationContext = resolveDeclarationContext(ktElement) @@ -114,23 +116,36 @@ private fun resolveDeclarationContext(element: KtElement): DeclarationContext { when (ancestor) { is KtClassBody -> { return when (val owner = ancestor.parent) { - is KtClass -> when { - owner.isInterface() -> DeclarationContext.INTERFACE_BODY - owner.isEnum() -> DeclarationContext.ENUM_BODY - owner.isAnnotation() -> DeclarationContext.ANNOTATION_BODY - else -> DeclarationContext.CLASS_BODY + is KtClass -> { + when { + owner.isInterface() -> DeclarationContext.INTERFACE_BODY + owner.isEnum() -> DeclarationContext.ENUM_BODY + owner.isAnnotation() -> DeclarationContext.ANNOTATION_BODY + else -> DeclarationContext.CLASS_BODY + } } - is KtObjectDeclaration -> DeclarationContext.OBJECT_BODY - else -> DeclarationContext.CLASS_BODY + is KtObjectDeclaration -> { + DeclarationContext.OBJECT_BODY + } + + else -> { + DeclarationContext.CLASS_BODY + } } } - is KtBlockExpression -> return DeclarationContext.FUNCTION_BODY - is KtFile -> return if (ancestor.isScript()) - DeclarationContext.SCRIPT_TOP_LEVEL - else - DeclarationContext.TOP_LEVEL + is KtBlockExpression -> { + return DeclarationContext.FUNCTION_BODY + } + + is KtFile -> { + return if (ancestor.isScript()) { + DeclarationContext.SCRIPT_TOP_LEVEL + } else { + DeclarationContext.TOP_LEVEL + } + } } } return DeclarationContext.TOP_LEVEL @@ -139,21 +154,46 @@ private fun resolveDeclarationContext(element: KtElement): DeclarationContext { private fun resolveDeclarationKind(element: KtElement): DeclarationKind { // Walk up to the nearest declaration owning this modifier list / position return when (val declaration = element.getNonStrictParentOfType()) { - is KtClass -> when { - declaration.isInterface() -> DeclarationKind.INTERFACE - declaration.isEnum() -> DeclarationKind.ENUM_CLASS - declaration.isAnnotation() -> DeclarationKind.ANNOTATION_CLASS - else -> DeclarationKind.CLASS + is KtClass -> { + when { + declaration.isInterface() -> DeclarationKind.INTERFACE + declaration.isEnum() -> DeclarationKind.ENUM_CLASS + declaration.isAnnotation() -> DeclarationKind.ANNOTATION_CLASS + else -> DeclarationKind.CLASS + } } - is KtObjectDeclaration -> DeclarationKind.OBJECT - is KtNamedFunction -> DeclarationKind.FUN - is KtProperty -> if (declaration.isVar) DeclarationKind.PROPERTY_VAR - else DeclarationKind.PROPERTY_VAL + is KtObjectDeclaration -> { + DeclarationKind.OBJECT + } + + is KtNamedFunction -> { + DeclarationKind.FUN + } - is KtTypeAlias -> DeclarationKind.TYPEALIAS - is KtConstructor<*> -> DeclarationKind.CONSTRUCTOR - null -> DeclarationKind.UNKNOWN // pure modifier list, no keyword yet - else -> DeclarationKind.UNKNOWN + is KtProperty -> { + if (declaration.isVar) { + DeclarationKind.PROPERTY_VAR + } else { + DeclarationKind.PROPERTY_VAL + } + } + + is KtTypeAlias -> { + DeclarationKind.TYPEALIAS + } + + is KtConstructor<*> -> { + DeclarationKind.CONSTRUCTOR + } + + null -> { + DeclarationKind.UNKNOWN + } + + // pure modifier list, no keyword yet + else -> { + DeclarationKind.UNKNOWN + } } } diff --git a/lsp/kotlin/src/test/java/com/itsaky/androidide/lsp/kotlin/VariantSourceSetsTest.kt b/lsp/kotlin/src/test/java/com/itsaky/androidide/lsp/kotlin/VariantSourceSetsTest.kt new file mode 100644 index 0000000000..6e233d46ac --- /dev/null +++ b/lsp/kotlin/src/test/java/com/itsaky/androidide/lsp/kotlin/VariantSourceSetsTest.kt @@ -0,0 +1,101 @@ +package com.itsaky.androidide.lsp.kotlin + +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.compiler.KotlinModuleLayout +import com.itsaky.androidide.lsp.kotlin.completion.doComplete +import com.itsaky.androidide.lsp.kotlin.diagnostic.DiagnosticsOutcome +import com.itsaky.androidide.lsp.kotlin.diagnostic.collectDiagnosticsFor +import com.itsaky.androidide.lsp.kotlin.fixtures.KtLspTest +import com.itsaky.androidide.lsp.kotlin.fixtures.variantLayout +import com.itsaky.androidide.lsp.kotlin.navigation.findDefinitionAt +import com.itsaky.androidide.lsp.models.CompletionParams +import com.itsaky.androidide.lsp.models.DefinitionParams +import com.itsaky.androidide.lsp.models.DiagnosticSeverity +import com.itsaky.androidide.models.Position +import com.itsaky.androidide.progress.ICancelChecker +import com.itsaky.androidide.projects.FileManager +import com.itsaky.androidide.projects.ProjectManagerImpl +import kotlinx.coroutines.runBlocking +import org.junit.After +import org.junit.Test +import java.nio.file.Path +import kotlin.io.path.createParentDirectories +import kotlin.io.path.readText +import kotlin.io.path.writeText + +/** + * `VariantConfig` is declared in both `src/debug` and `src/release`, each with its own property. + * With `debug` selected, Kotlin analysis must see the debug declaration and never the release one. + */ +class VariantSourceSetsTest : KtLspTest() { + // Completion runs on the opened document's live KtFile, which must be physical as in production. + override val enableParserEventSystem = true + + private lateinit var use: Path + private lateinit var completion: Path + + override fun layout(baseDir: Path): KotlinModuleLayout { + use = write(baseDir, "src/main/kotlin/p/Use.kt", USE) + completion = write(baseDir, "src/main/kotlin/p/Complete.kt", "package p\n\nfun c() = VariantConfig.\n") + write(baseDir, "src/debug/kotlin/p/VariantConfig.kt", "package p\n\nobject VariantConfig {\n\tval debugOnly = 1\n}\n") + write(baseDir, "src/release/kotlin/p/VariantConfig.kt", RELEASE_CONFIG) + return variantLayout(baseDir, listOf("debug", "release"), selected = "debug") + } + + @After + fun tearDown() { + FileManager.onDocumentClose(DocumentCloseEvent(completion)) + ProjectManagerImpl.getInstance().workspace = null + } + + @Test + fun `diagnostics resolve the selected variant's sources and flag another variant's`() { + val outcome = context(env) { collectDiagnosticsFor(use, ICancelChecker.NOOP) } + + val errors = (outcome as DiagnosticsOutcome.Collected).result.diagnostics.filter { it.severity == DiagnosticSeverity.ERROR } + + // Line 4 reads releaseOnly; line 2 reads debugOnly and must resolve. + assertThat(errors.map { it.range.start.line }.distinct()).containsExactly(4) + } + + @Test + fun `definition goes to the selected variant's declaration`() { + val offset = use.readText().indexOf("VariantConfig.debugOnly") + 2 + + val files = + runBlocking { context(env) { findDefinitionAt(DefinitionParams(use, Position(0, 0, offset), ICancelChecker.NOOP)) } } + .locations + .map { it.file.toString() } + + assertThat(files).isNotEmpty() + assertThat(files.filterNot { "/src/debug/kotlin/" in it }).isEmpty() + } + + @Test + fun `completion offers the selected variant's members and not another variant's`() { + val text = completion.readText() + FileManager.onDocumentOpen(DocumentOpenEvent(completion, text, 1)) + val offset = text.indexOf("VariantConfig.") + "VariantConfig.".length + + val labels = + context(env) { doComplete(CompletionParams(Position(0, 0, offset), completion, ICancelChecker.NOOP).apply { prefix = "" }) } + .items + .map { it.ideLabel.toString() } + + assertThat(labels).contains("debugOnly") + assertThat(labels).doesNotContain("releaseOnly") + } + + private companion object { + const val RELEASE_CONFIG = "package p\n\nobject VariantConfig {\n\tval releaseOnly = 2\n}\n" + const val USE = "package p\n\nfun d() = VariantConfig.debugOnly\n\nfun r() = VariantConfig.releaseOnly\n" + } + + private fun write( + baseDir: Path, + relativePath: String, + content: String, + ): Path = baseDir.resolve(relativePath).also { it.createParentDirectories().writeText(content) } +} diff --git a/lsp/kotlin/src/test/java/com/itsaky/androidide/lsp/kotlin/compiler/KotlinModuleLayoutTest.kt b/lsp/kotlin/src/test/java/com/itsaky/androidide/lsp/kotlin/compiler/KotlinModuleLayoutTest.kt index 3a634a6c64..f2631e6d0f 100644 --- a/lsp/kotlin/src/test/java/com/itsaky/androidide/lsp/kotlin/compiler/KotlinModuleLayoutTest.kt +++ b/lsp/kotlin/src/test/java/com/itsaky/androidide/lsp/kotlin/compiler/KotlinModuleLayoutTest.kt @@ -55,6 +55,16 @@ class KotlinModuleLayoutTest { assertThat(layoutOf(jvmTarget = "17")).isNotEqualTo(layoutOf(jvmTarget = "11")) } + @Test + fun `a source dir that appears changes the layout`() { + val dir = tempDir.root.toPath().resolve("app/src/test/java") + val before = layoutWithUnitTests(dir) + + dir.toFile().mkdirs() + + assertThat(layoutWithUnitTests(dir)).isNotEqualTo(before) + } + private fun layoutWithUnitTests(dir: Path): KotlinModuleLayout = Workspace( rootProject = GradleProject(gradleProject(":")), diff --git a/lsp/kotlin/src/test/java/com/itsaky/androidide/lsp/kotlin/fixtures/KtLspTest.kt b/lsp/kotlin/src/test/java/com/itsaky/androidide/lsp/kotlin/fixtures/KtLspTest.kt index f341656042..d79350ef70 100644 --- a/lsp/kotlin/src/test/java/com/itsaky/androidide/lsp/kotlin/fixtures/KtLspTest.kt +++ b/lsp/kotlin/src/test/java/com/itsaky/androidide/lsp/kotlin/fixtures/KtLspTest.kt @@ -1,5 +1,6 @@ package com.itsaky.androidide.lsp.kotlin.fixtures +import com.itsaky.androidide.lsp.kotlin.compiler.KotlinModuleLayout import com.itsaky.androidide.lsp.kotlin.compiler.index.toMetadata import com.itsaky.androidide.lsp.kotlin.compiler.modules.AnalysisPriority import com.itsaky.androidide.lsp.kotlin.compiler.modules.ScheduledCancelChecker @@ -16,6 +17,7 @@ import org.jetbrains.kotlin.psi.KtFile import org.junit.Rule import org.junit.runner.RunWith import org.robolectric.RobolectricTestRunner +import java.nio.file.Path /** * Base class for plain JVM unit tests that need a real Kotlin Analysis API environment. @@ -36,9 +38,15 @@ abstract class KtLspTest { */ internal open val enableParserEventSystem: Boolean = false + /** + * The project layout to build the modules from, in place of [moduleSpecs]: write the sources under + * [baseDir], install a workspace and return its layout. Null keeps [moduleSpecs]. + */ + internal open fun layout(baseDir: Path): KotlinModuleLayout? = null + @get:Rule @PublishedApi - internal val lspTestRule = KtLspTestRule({ moduleSpecs }, { enableParserEventSystem }) + internal val lspTestRule = KtLspTestRule({ moduleSpecs }, { enableParserEventSystem }, ::layout) internal val env: KtLspTestEnvironment get() = lspTestRule.env diff --git a/lsp/kotlin/src/test/java/com/itsaky/androidide/lsp/kotlin/fixtures/KtLspTestEnvironment.kt b/lsp/kotlin/src/test/java/com/itsaky/androidide/lsp/kotlin/fixtures/KtLspTestEnvironment.kt index bd39655ad6..05bb639c41 100644 --- a/lsp/kotlin/src/test/java/com/itsaky/androidide/lsp/kotlin/fixtures/KtLspTestEnvironment.kt +++ b/lsp/kotlin/src/test/java/com/itsaky/androidide/lsp/kotlin/fixtures/KtLspTestEnvironment.kt @@ -3,13 +3,17 @@ package com.itsaky.androidide.lsp.kotlin.fixtures import com.itsaky.androidide.lsp.kotlin.compiler.AbstractCompilationEnvironment import com.itsaky.androidide.lsp.kotlin.compiler.CompilationKind import com.itsaky.androidide.lsp.kotlin.compiler.DEFAULT_LANGUAGE_VERSION +import com.itsaky.androidide.lsp.kotlin.compiler.KotlinModuleLayout import com.itsaky.androidide.lsp.kotlin.compiler.index.KtSymbolIndex +import com.itsaky.androidide.lsp.kotlin.compiler.index.toMetadata import com.itsaky.androidide.lsp.kotlin.compiler.modules.KtModule import com.itsaky.androidide.lsp.kotlin.compiler.modules.buildKtLibraryModule import com.itsaky.androidide.lsp.kotlin.compiler.read import com.itsaky.androidide.lsp.kotlin.compiler.registrar.AnalysisApiServiceProviders import com.itsaky.androidide.lsp.kotlin.compiler.registrar.LspAnalysisApiServiceRegistrar import com.itsaky.androidide.lsp.kotlin.compiler.services.AnalysisPermissionOptions +import com.itsaky.androidide.lsp.kotlin.compiler.toKtModules +import kotlinx.coroutines.runBlocking import org.appdevforall.codeonthego.indexing.InMemoryIndex import org.appdevforall.codeonthego.indexing.api.IndexQuery import org.appdevforall.codeonthego.indexing.jvm.JvmSymbol @@ -49,6 +53,9 @@ import org.jetbrains.kotlin.analysis.api.analyze as ktAnalyze * @param extraLibraryJars Additional JARs to add as library modules. * @param languageVersion Kotlin language version; defaults to [DEFAULT_LANGUAGE_VERSION]. * @param jdkRelease JDK release version; defaults to the host JVM's feature version. + * @param layout When set, the modules are built from it the way production builds them, in place of + * [moduleSpecs], and every Kotlin file under its source roots is indexed, as the background indexer + * would. Its source roots must exist already. */ @OptIn(K1Deprecation::class, KaImplementationDetail::class) internal class KtLspTestEnvironment( @@ -63,6 +70,7 @@ internal class KtLspTestEnvironment( // Tests that open a document and drive resolution/ranges through it (the live-document path) // need true to be representative; everything else keeps the historical false. enableParserEventSystem: Boolean = false, + private val layout: KotlinModuleLayout? = null, ) : AbstractCompilationEnvironment( name = "test", kind = CompilationKind.Default, @@ -99,6 +107,7 @@ internal class KtLspTestEnvironment( init { try { initialize(::buildModules, ::buildKtSymbolIndex) + layout?.let(::indexSourceRoots) } catch (failure: Throwable) { /* * A throwing constructor never hands the instance to KtLspTestRule, so its finally has @@ -111,6 +120,10 @@ internal class KtLspTestEnvironment( } } + // The fixture aliases one in-memory index as both source and library. + override val unimportedSymbolIndexes: List + get() = listOf(ktSymbolIndex.sourceIndex, ktSymbolIndex.libraryIndex).distinct() + override fun createServiceRegistrars(): List = listOf( LspAnalysisApiServiceRegistrar( @@ -134,6 +147,8 @@ internal class KtLspTestEnvironment( project: MockProject, applicationEnv: KotlinCoreApplicationEnvironment, ): List { + layout?.let { return it.toKtModules(project, applicationEnv) } + val jdkModule = buildKtLibraryModule(project, applicationEnv) { id = "jdk" @@ -293,6 +308,28 @@ internal class KtLspTestEnvironment( } } + /** The [KtFile] at [path], which must already exist on disk. */ + fun ktFile(path: Path): KtFile { + val vf = localFileSystem.refreshAndFindFileByPath(path.pathString) ?: error("VFS cannot find $path") + return project.read { PsiManager.getInstance(project).findFile(vf) as? KtFile } ?: error("Not a Kotlin file: $path") + } + + private fun indexSourceRoots(layout: KotlinModuleLayout) { + val files = + layout.modules + .flatMap { it.sourceRoots } + .flatMap { root -> + root + .toFile() + .walkTopDown() + .filter { it.isFile && it.extension == "kt" } + .toList() + } + runBlocking { + files.forEach { ktSymbolIndex.fileIndex.upsert(ktFile(it.toPath()).toMetadata(project, isIndexed = false)) } + } + } + /** * Runs [action] inside a [KaSession] for [file], acquiring the project read lock first. */ @@ -355,7 +392,7 @@ private fun findIntellijPluginRoot(): Path { } } -private fun findKotlinStdlibJar(): Path? = +internal fun findKotlinStdlibJar(): Path? = try { val location = KotlinVersion::class.java.protectionDomain diff --git a/lsp/kotlin/src/test/java/com/itsaky/androidide/lsp/kotlin/fixtures/KtLspTestRule.kt b/lsp/kotlin/src/test/java/com/itsaky/androidide/lsp/kotlin/fixtures/KtLspTestRule.kt index 92159a49bf..e5c1ce371b 100644 --- a/lsp/kotlin/src/test/java/com/itsaky/androidide/lsp/kotlin/fixtures/KtLspTestRule.kt +++ b/lsp/kotlin/src/test/java/com/itsaky/androidide/lsp/kotlin/fixtures/KtLspTestRule.kt @@ -1,9 +1,11 @@ package com.itsaky.androidide.lsp.kotlin.fixtures +import com.itsaky.androidide.lsp.kotlin.compiler.KotlinModuleLayout import org.junit.rules.TemporaryFolder import org.junit.rules.TestRule import org.junit.runner.Description import org.junit.runners.model.Statement +import java.nio.file.Path /** * @param moduleSpecs Supplied as a lambda, not a value: JUnit evaluates rules after the test class @@ -17,6 +19,7 @@ internal class KtLspTestRule( listOf(TestSourceModuleSpec("src")) }, private val enableParserEventSystem: () -> Boolean = { false }, + private val layout: (Path) -> KotlinModuleLayout? = { null }, ) : TestRule { val tempDir = TemporaryFolder() lateinit var env: KtLspTestEnvironment @@ -36,6 +39,7 @@ internal class KtLspTestRule( tempDir.root.toPath(), moduleSpecs(), enableParserEventSystem = enableParserEventSystem(), + layout = layout(tempDir.root.toPath()), ) env = environment diff --git a/lsp/kotlin/src/test/java/com/itsaky/androidide/lsp/kotlin/fixtures/VariantProjectFixtures.kt b/lsp/kotlin/src/test/java/com/itsaky/androidide/lsp/kotlin/fixtures/VariantProjectFixtures.kt new file mode 100644 index 0000000000..a338103847 --- /dev/null +++ b/lsp/kotlin/src/test/java/com/itsaky/androidide/lsp/kotlin/fixtures/VariantProjectFixtures.kt @@ -0,0 +1,113 @@ +package com.itsaky.androidide.lsp.kotlin.fixtures + +import com.itsaky.androidide.lsp.kotlin.compiler.KotlinModuleLayout +import com.itsaky.androidide.lsp.kotlin.compiler.kotlinModuleLayout +import com.itsaky.androidide.project.AndroidModels +import com.itsaky.androidide.project.GradleModels +import com.itsaky.androidide.projects.ProjectManagerImpl +import com.itsaky.androidide.projects.models.ArtifactScope +import kotlinx.coroutines.runBlocking +import java.nio.file.Path +import kotlin.io.path.pathString + +/** + * Syncs, through [ProjectManagerImpl.setup] as a real sync does, an Android module at [dir] whose + * `src/main/kotlin` every variant in [variants] layers its own `src//kotlin` over, with + * [selected] configured and the Kotlin stdlib on the compile classpath, and returns the workspace's + * Kotlin layout. Write the sources first: the layout keeps only source dirs that exist. + */ +internal fun variantLayout( + dir: Path, + variants: List, + selected: String, +): KotlinModuleLayout { + val mainKotlin = dir.resolve("src/main/kotlin") + val variantKotlin = variants.associateWith { dir.resolve("src/$it/kotlin") } + val stdlib = checkNotNull(findKotlinStdlibJar()) { "Kotlin stdlib jar not found" } + + val module = + GradleModels.GradleProject + .newBuilder() + .setName("app") + .setPath(":app") + .setProjectDirPath(dir.pathString) + .setBuildDirPath(dir.resolve("build").pathString) + .setBuildScriptPath(dir.resolve("build.gradle").pathString) + .setAndroidProject( + AndroidModels.AndroidProject + .newBuilder() + .setProjectType(AndroidModels.ProjectType.LibraryProject) + .setMainSourceSet( + AndroidModels.SourceSetContainer + .newBuilder() + .putSourceProviders(ArtifactScope.Main.key, kotlinProvider(mainKotlin)), + ).addAllVariant(variantKotlin.map { (name, kotlinDir) -> variant(name, kotlinDir) }) + .setConfiguredVariantName(selected) + .setVariantDependencies(dependingOn(stdlib)), + ).build() + + val build = + GradleModels.GradleBuild + .newBuilder() + .setRootProject( + GradleModels.GradleProject + .newBuilder() + .setName("root") + .setPath(":"), + ).addSubProject(module) + .build() + val manager = ProjectManagerImpl.getInstance() + runBlocking { manager.setup(build) } + return checkNotNull(manager.workspace).kotlinModuleLayout() +} + +private fun kotlinProvider(dir: Path): AndroidModels.SourceProvider = + AndroidModels.SourceProvider + .newBuilder() + .addKotlinDirs(dir.pathString) + .build() + +private fun variant( + name: String, + kotlinDir: Path, +): AndroidModels.AndroidVariant = + AndroidModels.AndroidVariant + .newBuilder() + .setName(name) + .setMainArtifact(AndroidModels.AndroidArtifact.newBuilder().setName("main")) + .putArtifactSources( + ArtifactScope.Main.key, + AndroidModels.VariantArtifactSources + .newBuilder() + .addVariantSourceProviders(kotlinProvider(kotlinDir)) + .build(), + ).build() + +/** Main dependencies of one root library, [jar]. */ +private fun dependingOn(jar: Path): AndroidModels.VariantDependencies { + val key = "jar:${jar.pathString}" + val graph = + AndroidModels.DependencyGraph + .newBuilder() + .addKey(key) + .addNode(AndroidModels.GraphNode.newBuilder().setKeyId(0)) + .addRoot(0) + return AndroidModels.VariantDependencies + .newBuilder() + .setName("main") + .putArtifacts( + ArtifactScope.Main.key, + AndroidModels.ArtifactDependencies + .newBuilder() + .setCompileGraph(graph) + .build(), + ).putLibraries( + key, + AndroidModels.Library + .newBuilder() + .setKey(key) + .setType(AndroidModels.LibraryType.ExternalJavaLibrary) + .setArtifactPath(jar.pathString) + .build(), + ).build() +} diff --git a/subprojects/projects/src/main/java/com/itsaky/androidide/projects/api/AndroidModule.kt b/subprojects/projects/src/main/java/com/itsaky/androidide/projects/api/AndroidModule.kt index 494d82ced7..63568f59ca 100644 --- a/subprojects/projects/src/main/java/com/itsaky/androidide/projects/api/AndroidModule.kt +++ b/subprojects/projects/src/main/java/com/itsaky/androidide/projects/api/AndroidModule.kt @@ -138,10 +138,15 @@ open class AndroidModule( return emptySet() } val provider = defaultSources(scope) ?: return emptySet() + val variant = variantSources(scope) + + // src/, src/, src/ and their test counterparts are compiled + // with the default source set whenever this variant is selected. + val layers = variant?.variantSourceProvidersList.orEmpty().flatMap { it.javaDirs + it.kotlinDirs } // build/generated/**: AIDL, BuildConfig, kapt, KSP and every other generated source - val generated = variantSources(scope)?.generatedSourceFolderPathsList.orEmpty().map(::File) - return (provider.javaDirs + provider.kotlinDirs + generated).toSet() + val generated = variant?.generatedSourceFolderPathsList.orEmpty().map(::File) + return (provider.javaDirs + provider.kotlinDirs + layers + generated).toSet() } override fun getCompileSourceDirectories(): Set { diff --git a/subprojects/projects/src/test/java/com/itsaky/androidide/projects/api/ArtifactScopeSourcesTest.kt b/subprojects/projects/src/test/java/com/itsaky/androidide/projects/api/ArtifactScopeSourcesTest.kt index a6fff0cddc..bd347f5eb5 100644 --- a/subprojects/projects/src/test/java/com/itsaky/androidide/projects/api/ArtifactScopeSourcesTest.kt +++ b/subprojects/projects/src/test/java/com/itsaky/androidide/projects/api/ArtifactScopeSourcesTest.kt @@ -165,6 +165,41 @@ class ArtifactScopeSourcesTest { assertThat(module.getSourceDirectories()).doesNotContain(javaTest) } + @Test + fun `req 1 - main scope includes the selected variant's own source sets`() { + val app = variantApp() + install(app) + select("myStupidVariant") + + assertThat(app.getSourceDirectories()) + .containsAtLeast(File("/p/app/src/myStupidVariant/java"), File("/p/app/src/myStupidVariant/kotlin"), mainJava) + assertThat(app.getSourceDirectories()).doesNotContain(File("/p/app/src/release/java")) + } + + @Test + fun `req 2 - the unit test scope includes the selected variant's test source sets`() { + val app = variantApp() + install(app) + select("myStupidVariant") + + assertThat(app.getSourceDirectories(ArtifactScope.UNIT_TEST)) + .containsAtLeast(unitJava, File("/p/app/src/testMyStupidVariant/java")) + assertThat(app.getSourceDirectories()).doesNotContain(File("/p/app/src/testMyStupidVariant/java")) + } + + @Test + fun `req 6 - switching the selected variant moves main's roots`() { + val app = variantApp() + install(app) + + select("myStupidVariant") + val before = app.getSourceDirectories() + select("release") + + assertThat(app.getSourceDirectories()).contains(File("/p/app/src/release/java")) + assertThat(app.getSourceDirectories()).isNotEqualTo(before) + } + @Test fun `a new test fixtures file is indexed for every scope that sees fixtures`() { val app = app(withTests = true, extraScopes = mapOf(ArtifactScope.TestFixtures to fixturesJava)) @@ -179,6 +214,53 @@ class ArtifactScopeSourcesTest { ) } + private fun select(variant: String) { + ProjectManagerImpl.getInstance().androidBuildVariants = + mapOf(":app" to BuildVariantInfo(":app", listOf("myStupidVariant", "release"), variant)) + } + + /** + * An app with unit tests and two variants, each layering its own `src/` and + * `src/test`; every one of those dirs is a source set dir AGP knows for the module. + */ + private fun variantApp(): AndroidModule { + val base = app(withTests = true) + val project = + base.delegate.androidProject + .toBuilder() + .clearVariant() + .addVariant(layeredVariant("myStupidVariant")) + .addVariant(layeredVariant("release")) + return AndroidModule( + base.delegate + .toBuilder() + .setAndroidProject(project) + .build(), + ) + } + + private fun layeredVariant(name: String): AndroidModels.AndroidVariant { + val capitalized = name.replaceFirstChar(Char::uppercaseChar) + + fun layer(dir: String) = + AndroidModels.VariantArtifactSources + .newBuilder() + .addVariantSourceProviders(provider(File(dir))) + .build() + return AndroidModels.AndroidVariant + .newBuilder() + .setName(name) + .setMainArtifact(AndroidModels.AndroidArtifact.newBuilder().setName("main")) + .putArtifactSources( + ArtifactScope.Main.key, + AndroidModels.VariantArtifactSources + .newBuilder() + .addVariantSourceProviders(provider(File("/p/app/src/$name/java"), File("/p/app/src/$name/kotlin"))) + .build(), + ).putArtifactSources(ArtifactScope.UNIT_TEST.key, layer("/p/app/src/test$capitalized/java")) + .build() + } + /** An app module; [extraScopes] adds scopes with one source dir and main's dependencies. */ private fun app( withTests: Boolean, diff --git a/testing/resources/test-project/app/src/debug/java/com/itsaky/test/app/variant/VariantConfig.java b/testing/resources/test-project/app/src/debug/java/com/itsaky/test/app/variant/VariantConfig.java new file mode 100644 index 0000000000..89ee10d348 --- /dev/null +++ b/testing/resources/test-project/app/src/debug/java/com/itsaky/test/app/variant/VariantConfig.java @@ -0,0 +1,5 @@ +package com.itsaky.test.app.variant; + +public class VariantConfig { + public static final String DEBUG_ONLY_FIELD = "debug"; +} diff --git a/testing/resources/test-project/app/src/main/resources/definition/CompletesMainActivity_template.java b/testing/resources/test-project/app/src/main/resources/definition/CompletesMainActivity_template.java new file mode 100644 index 0000000000..86b0270d95 --- /dev/null +++ b/testing/resources/test-project/app/src/main/resources/definition/CompletesMainActivity_template.java @@ -0,0 +1,7 @@ +package com.itsaky.test.app; + +class CompletesMainActivity { + void use() { + MainActivity.@@cursor@@ + } +} diff --git a/testing/resources/test-project/app/src/main/resources/definition/ReferencesMainActivity_template.java b/testing/resources/test-project/app/src/main/resources/definition/ReferencesMainActivity_template.java new file mode 100644 index 0000000000..7f944bce1c --- /dev/null +++ b/testing/resources/test-project/app/src/main/resources/definition/ReferencesMainActivity_template.java @@ -0,0 +1,5 @@ +package com.itsaky.test.app; + +class ReferencesMainActivity { + MainActivity activity; +} diff --git a/testing/resources/test-project/app/src/main/resources/variants/VariantDefinition_template.java b/testing/resources/test-project/app/src/main/resources/variants/VariantDefinition_template.java new file mode 100644 index 0000000000..b96b124928 --- /dev/null +++ b/testing/resources/test-project/app/src/main/resources/variants/VariantDefinition_template.java @@ -0,0 +1,7 @@ +package com.itsaky.test.app; + +import com.itsaky.test.app.variant.VariantConfig; + +class VariantDefinition { + String d = VariantConfig.DEBUG_ONLY_FIELD; +} diff --git a/testing/resources/test-project/app/src/main/resources/variants/VariantMembers_template.java b/testing/resources/test-project/app/src/main/resources/variants/VariantMembers_template.java new file mode 100644 index 0000000000..59ddb6b444 --- /dev/null +++ b/testing/resources/test-project/app/src/main/resources/variants/VariantMembers_template.java @@ -0,0 +1,9 @@ +package com.itsaky.test.app; + +import com.itsaky.test.app.variant.VariantConfig; + +class VariantMembers { + void use() { + VariantConfig.@@cursor@@ + } +} diff --git a/testing/resources/test-project/app/src/main/resources/variants/VariantUse_template.java b/testing/resources/test-project/app/src/main/resources/variants/VariantUse_template.java new file mode 100644 index 0000000000..4f3091cabb --- /dev/null +++ b/testing/resources/test-project/app/src/main/resources/variants/VariantUse_template.java @@ -0,0 +1,8 @@ +package com.itsaky.test.app; + +import com.itsaky.test.app.variant.VariantConfig; + +class VariantUse { + String d = VariantConfig.DEBUG_ONLY_FIELD; + String r = VariantConfig.RELEASE_ONLY_FIELD; +} diff --git a/testing/resources/test-project/app/src/release/java/com/itsaky/test/app/variant/VariantConfig.java b/testing/resources/test-project/app/src/release/java/com/itsaky/test/app/variant/VariantConfig.java new file mode 100644 index 0000000000..c35738afbe --- /dev/null +++ b/testing/resources/test-project/app/src/release/java/com/itsaky/test/app/variant/VariantConfig.java @@ -0,0 +1,5 @@ +package com.itsaky.test.app.variant; + +public class VariantConfig { + public static final String RELEASE_ONLY_FIELD = "release"; +}