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 @@ -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

/**
Expand All @@ -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<Location> {
// 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<Location> =
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("<init>")) inBatch.enclosingElement.simpleName else inBatch.simpleName
listOf(FindHelper.location(task, path, name))
}
}
Original file line number Diff line number Diff line change
@@ -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()
}
}
}
Original file line number Diff line number Diff line change
@@ -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")
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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<JvmSymbolIndex>

protected abstract fun createServiceRegistrars(): List<AnalysisApiSimpleServiceRegistrar>

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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<JvmSymbolIndex>
get() = listOfNotNull(sourceIndex, generatedIndex, libraryIndex)

var languageClient: ILanguageClient?
get() = _languageClient
Expand Down Expand Up @@ -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)
}
Expand All @@ -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 {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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

/**
Expand Down Expand Up @@ -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,
Expand All @@ -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
}
Expand All @@ -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<File>): Set<Path> = dirs.filter { it.isDirectory }.mapTo(LinkedHashSet()) { it.toPath() }
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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 ->
Expand Down Expand Up @@ -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<CompletionItem>) {
if (ctx.partial.isBlank()) {
logger.warn("cannot complete for blank partial candidate")
Expand Down Expand Up @@ -422,7 +422,7 @@ private fun KaSession.collectScopeCompletions(to: MutableList<CompletionItem>) {
collectKeywordCompletions(to)
}

context(env: CompilationEnvironment, ctx: AnalysisContext)
context(env: AbstractCompilationEnvironment, ctx: AnalysisContext)
private fun KaSession.collectUnimportedSymbols(to: MutableList<CompletionItem>) {
val currentPackage =
ctx.ktElement.containingKtFile.packageDirective
Expand Down Expand Up @@ -450,12 +450,7 @@ private fun KaSession.collectUnimportedSymbols(to: MutableList<CompletionItem>)
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,
Expand Down
Loading
Loading