From b13f988cba3854c405c2f380e75c92e026be054b Mon Sep 17 00:00:00 2001 From: Akash Yadav Date: Tue, 17 Nov 2026 00:07:40 +0530 Subject: [PATCH 1/2] style: spotless reformat, no functional change --- .../lsp/kotlin/fixtures/TestKtSourceModule.kt | 36 +- .../utils/SymbolVisibilityCheckerTest.kt | 331 +++++++++--------- 2 files changed, 183 insertions(+), 184 deletions(-) diff --git a/lsp/kotlin/src/test/java/com/itsaky/androidide/lsp/kotlin/fixtures/TestKtSourceModule.kt b/lsp/kotlin/src/test/java/com/itsaky/androidide/lsp/kotlin/fixtures/TestKtSourceModule.kt index ceddcf33a3..89cf91e305 100644 --- a/lsp/kotlin/src/test/java/com/itsaky/androidide/lsp/kotlin/fixtures/TestKtSourceModule.kt +++ b/lsp/kotlin/src/test/java/com/itsaky/androidide/lsp/kotlin/fixtures/TestKtSourceModule.kt @@ -19,24 +19,24 @@ import java.nio.file.Path @OptIn(KaPlatformInterface::class, KaExperimentalApi::class) internal class TestKtSourceModule( - project: Project, - override val name: String, - roots: Set, - dependencies: List = emptyList(), - languageVersion: LanguageVersion = DEFAULT_LANGUAGE_VERSION, - jvmTarget: JvmTarget = DEFAULT_JVM_TARGET, -) : KaSourceModule, AbstractSourceModule(project, dependencies) { + project: Project, + override val name: String, + roots: Set, + dependencies: List = emptyList(), + languageVersion: LanguageVersion = DEFAULT_LANGUAGE_VERSION, + jvmTarget: JvmTarget = DEFAULT_JVM_TARGET, +) : AbstractSourceModule(project, dependencies), + KaSourceModule { + override val id: String = name + override val contentRoots: Set = roots + override val moduleDescription: String = "test:$name" - override val id: String = name - override val contentRoots: Set = roots - override val moduleDescription: String = "test:$name" + override val languageVersionSettings: LanguageVersionSettings = + LanguageVersionSettingsImpl( + languageVersion = languageVersion, + apiVersion = ApiVersion.createByLanguageVersion(languageVersion), + ) - override val languageVersionSettings: LanguageVersionSettings = - LanguageVersionSettingsImpl( - languageVersion = languageVersion, - apiVersion = ApiVersion.createByLanguageVersion(languageVersion), - ) - - override val targetPlatform: TargetPlatform = - JvmPlatforms.jvmPlatformByTargetVersion(jvmTarget) + override val targetPlatform: TargetPlatform = + JvmPlatforms.jvmPlatformByTargetVersion(jvmTarget) } diff --git a/lsp/kotlin/src/test/java/com/itsaky/androidide/lsp/kotlin/utils/SymbolVisibilityCheckerTest.kt b/lsp/kotlin/src/test/java/com/itsaky/androidide/lsp/kotlin/utils/SymbolVisibilityCheckerTest.kt index c6fe6721a6..6b8aa1728e 100644 --- a/lsp/kotlin/src/test/java/com/itsaky/androidide/lsp/kotlin/utils/SymbolVisibilityCheckerTest.kt +++ b/lsp/kotlin/src/test/java/com/itsaky/androidide/lsp/kotlin/utils/SymbolVisibilityCheckerTest.kt @@ -21,170 +21,169 @@ import org.junit.runners.JUnit4 */ @RunWith(JUnit4::class) class SymbolVisibilityCheckerTest { - - // Use relaxed mocks so that no stubs are required for unused methods - private val structureProvider = mockk(relaxed = true) - private val checker = SymbolVisibilityChecker(structureProvider) - - // Two distinct modules - private val moduleA: KaModule = mockk(relaxed = true) - private val moduleB: KaModule = mockk(relaxed = true) - - private fun symbol( - visibility: JvmVisibility, - pkg: String = "com.example", - sourceId: String = "jar-a", - ) = JvmSymbol( - key = "com/example/Foo", - sourceId = sourceId, - name = "com/example/Foo", - shortName = "Foo", - packageName = pkg, - kind = JvmSymbolKind.CLASS, - language = JvmSourceLanguage.KOTLIN, - visibility = visibility, - data = JvmClassInfo(), - ) - - @Test - fun `PUBLIC symbol is always visible regardless of module`() { - assertThat( - checker.isDeclarationVisible( - symbol(JvmVisibility.PUBLIC), - useSiteModule = moduleA, - declaringModule = moduleB, - useSitePackage = "other.pkg", - ) - ).isTrue() - } - - @Test - fun `PUBLIC symbol is visible even with null useSitePackage`() { - assertThat( - checker.isDeclarationVisible( - symbol(JvmVisibility.PUBLIC), - useSiteModule = moduleA, - declaringModule = moduleB, - useSitePackage = null, - ) - ).isTrue() - } - - @Test - fun `PRIVATE symbol is never visible`() { - assertThat( - checker.isDeclarationVisible( - symbol(JvmVisibility.PRIVATE), - useSiteModule = moduleA, - declaringModule = moduleB, - ) - ).isFalse() - } - - @Test - fun `PRIVATE symbol is not visible even from same module`() { - assertThat( - checker.isDeclarationVisible( - symbol(JvmVisibility.PRIVATE), - useSiteModule = moduleA, - declaringModule = moduleA, // same module - ) - ).isFalse() - } - - @Test - fun `INTERNAL symbol is visible from same module`() { - assertThat( - checker.isDeclarationVisible( - symbol(JvmVisibility.INTERNAL), - useSiteModule = moduleA, - declaringModule = moduleA, - ) - ).isTrue() - } - - @Test - fun `INTERNAL symbol is not visible from different module`() { - assertThat( - checker.isDeclarationVisible( - symbol(JvmVisibility.INTERNAL), - useSiteModule = moduleA, - declaringModule = moduleB, - ) - ).isFalse() - } - - @Test - fun `PACKAGE_PRIVATE symbol is visible within same package`() { - assertThat( - checker.isDeclarationVisible( - symbol(JvmVisibility.PACKAGE_PRIVATE, pkg = "com.example"), - useSiteModule = moduleA, - declaringModule = moduleB, - useSitePackage = "com.example", - ) - ).isTrue() - } - - @Test - fun `PACKAGE_PRIVATE symbol is not visible from different package`() { - assertThat( - checker.isDeclarationVisible( - symbol(JvmVisibility.PACKAGE_PRIVATE, pkg = "com.example"), - useSiteModule = moduleA, - declaringModule = moduleB, - useSitePackage = "org.other", - ) - ).isFalse() - } - - @Test - fun `PACKAGE_PRIVATE symbol is not visible when useSitePackage is null`() { - assertThat( - checker.isDeclarationVisible( - symbol(JvmVisibility.PACKAGE_PRIVATE, pkg = "com.example"), - useSiteModule = moduleA, - declaringModule = moduleB, - useSitePackage = null, - ) - ).isFalse() - } - - @Test - fun `PROTECTED symbol is visible within same package`() { - assertThat( - checker.isDeclarationVisible( - symbol(JvmVisibility.PROTECTED, pkg = "com.example"), - useSiteModule = moduleA, - declaringModule = moduleB, - useSitePackage = "com.example", - ) - ).isTrue() - } - - @Test - fun `PROTECTED symbol is visible as assumed descendant across packages`() { - // isDescendant is hardcoded to true in the current implementation - assertThat( - checker.isDeclarationVisible( - symbol(JvmVisibility.PROTECTED, pkg = "com.example"), - useSiteModule = moduleA, - declaringModule = moduleB, - useSitePackage = "different.pkg", - ) - ).isTrue() - } - - @Test - fun `PROTECTED symbol is visible with null useSitePackage due to descendant assumption`() { - // isSamePackage=false but isDescendant=true → visible - assertThat( - checker.isDeclarationVisible( - symbol(JvmVisibility.PROTECTED, pkg = "com.example"), - useSiteModule = moduleA, - declaringModule = moduleB, - useSitePackage = null, - ) - ).isTrue() - } + // Use relaxed mocks so that no stubs are required for unused methods + private val structureProvider = mockk(relaxed = true) + private val checker = SymbolVisibilityChecker(structureProvider) + + // Two distinct modules + private val moduleA: KaModule = mockk(relaxed = true) + private val moduleB: KaModule = mockk(relaxed = true) + + private fun symbol( + visibility: JvmVisibility, + pkg: String = "com.example", + sourceId: String = "jar-a", + ) = JvmSymbol( + key = "com/example/Foo", + sourceId = sourceId, + name = "com/example/Foo", + shortName = "Foo", + packageName = pkg, + kind = JvmSymbolKind.CLASS, + language = JvmSourceLanguage.KOTLIN, + visibility = visibility, + data = JvmClassInfo(), + ) + + @Test + fun `PUBLIC symbol is always visible regardless of module`() { + assertThat( + checker.isDeclarationVisible( + symbol(JvmVisibility.PUBLIC), + useSiteModule = moduleA, + declaringModule = moduleB, + useSitePackage = "other.pkg", + ), + ).isTrue() + } + + @Test + fun `PUBLIC symbol is visible even with null useSitePackage`() { + assertThat( + checker.isDeclarationVisible( + symbol(JvmVisibility.PUBLIC), + useSiteModule = moduleA, + declaringModule = moduleB, + useSitePackage = null, + ), + ).isTrue() + } + + @Test + fun `PRIVATE symbol is never visible`() { + assertThat( + checker.isDeclarationVisible( + symbol(JvmVisibility.PRIVATE), + useSiteModule = moduleA, + declaringModule = moduleB, + ), + ).isFalse() + } + + @Test + fun `PRIVATE symbol is not visible even from same module`() { + assertThat( + checker.isDeclarationVisible( + symbol(JvmVisibility.PRIVATE), + useSiteModule = moduleA, + declaringModule = moduleA, // same module + ), + ).isFalse() + } + + @Test + fun `INTERNAL symbol is visible from same module`() { + assertThat( + checker.isDeclarationVisible( + symbol(JvmVisibility.INTERNAL), + useSiteModule = moduleA, + declaringModule = moduleA, + ), + ).isTrue() + } + + @Test + fun `INTERNAL symbol is not visible from different module`() { + assertThat( + checker.isDeclarationVisible( + symbol(JvmVisibility.INTERNAL), + useSiteModule = moduleA, + declaringModule = moduleB, + ), + ).isFalse() + } + + @Test + fun `PACKAGE_PRIVATE symbol is visible within same package`() { + assertThat( + checker.isDeclarationVisible( + symbol(JvmVisibility.PACKAGE_PRIVATE, pkg = "com.example"), + useSiteModule = moduleA, + declaringModule = moduleB, + useSitePackage = "com.example", + ), + ).isTrue() + } + + @Test + fun `PACKAGE_PRIVATE symbol is not visible from different package`() { + assertThat( + checker.isDeclarationVisible( + symbol(JvmVisibility.PACKAGE_PRIVATE, pkg = "com.example"), + useSiteModule = moduleA, + declaringModule = moduleB, + useSitePackage = "org.other", + ), + ).isFalse() + } + + @Test + fun `PACKAGE_PRIVATE symbol is not visible when useSitePackage is null`() { + assertThat( + checker.isDeclarationVisible( + symbol(JvmVisibility.PACKAGE_PRIVATE, pkg = "com.example"), + useSiteModule = moduleA, + declaringModule = moduleB, + useSitePackage = null, + ), + ).isFalse() + } + + @Test + fun `PROTECTED symbol is visible within same package`() { + assertThat( + checker.isDeclarationVisible( + symbol(JvmVisibility.PROTECTED, pkg = "com.example"), + useSiteModule = moduleA, + declaringModule = moduleB, + useSitePackage = "com.example", + ), + ).isTrue() + } + + @Test + fun `PROTECTED symbol is visible as assumed descendant across packages`() { + // isDescendant is hardcoded to true in the current implementation + assertThat( + checker.isDeclarationVisible( + symbol(JvmVisibility.PROTECTED, pkg = "com.example"), + useSiteModule = moduleA, + declaringModule = moduleB, + useSitePackage = "different.pkg", + ), + ).isTrue() + } + + @Test + fun `PROTECTED symbol is visible with null useSitePackage due to descendant assumption`() { + // isSamePackage=false but isDescendant=true → visible + assertThat( + checker.isDeclarationVisible( + symbol(JvmVisibility.PROTECTED, pkg = "com.example"), + useSiteModule = moduleA, + declaringModule = moduleB, + useSitePackage = null, + ), + ).isTrue() + } } From 3c7474dc4cdce558d9465d94ddf80ef4e9384aae Mon Sep 17 00:00:00 2001 From: Akash Yadav Date: Tue, 17 Nov 2026 00:07:40 +0530 Subject: [PATCH 2/2] feat(lsp): give Kotlin test sources their own modules --- docs/features/kotlin-find-usages.md | 13 +- .../lsp/kotlin/compiler/KotlinModuleLayout.kt | 70 +++++++++-- .../lsp/kotlin/compiler/WorkspaceExts.kt | 7 +- .../kotlin/compiler/modules/KtSourceModule.kt | 10 +- .../lsp/kotlin/navigation/FindUsages.kt | 22 +++- .../kotlin/utils/SymbolVisibilityChecker.kt | 17 ++- .../kotlin/compiler/CollectKtModulesTest.kt | 112 ++++++++++++++++++ .../kotlin/compiler/KotlinModuleLayoutTest.kt | 9 ++ .../kotlin/fixtures/GradleProjectFixtures.kt | 80 ++++++++++++- .../kotlin/fixtures/KtLspTestEnvironment.kt | 1 + .../lsp/kotlin/fixtures/TestKtSourceModule.kt | 1 + .../kotlin/fixtures/TestSourceModuleSpec.kt | 3 + .../kotlin/navigation/TestSourceScopesTest.kt | 91 ++++++++++++++ .../utils/SymbolVisibilityCheckerTest.kt | 17 +++ 14 files changed, 424 insertions(+), 29 deletions(-) create mode 100644 lsp/kotlin/src/test/java/com/itsaky/androidide/lsp/kotlin/navigation/TestSourceScopesTest.kt diff --git a/docs/features/kotlin-find-usages.md b/docs/features/kotlin-find-usages.md index 67a23f9489..d527d6af43 100644 --- a/docs/features/kotlin-find-usages.md +++ b/docs/features/kotlin-find-usages.md @@ -52,7 +52,7 @@ The **target** may be a Java-source declaration. A caret on a Kotlin reference t - **`.java` files as search targets.** Kotlin declarations *are* visible to Java PSI as light classes here (`symbol-light-classes.xml` registers `KotlinAsJavaSupport`, and `JavaElementFinder` is registered), but nothing in the repo exercises Java PSI *resolution*, and the Java server has its own find-references. Kotlin call sites of a Java declaration work; Java call sites of a Kotlin declaration are not searched. - **Usages reachable only through a subclass.** See R3 and Non-goals. - **Binary symbols.** As with go-to-definition: no decompiler, and `showLocations` can only open a real file. A search from a reference to `listOf` finds nothing. -- **Test sources.** Not a choice made here - `AndroidModule.getSourceDirectories()` returns `mainSourceSet` only, so `src/test/**` and `src/androidTest/**` are not content roots for *any* Kotlin LSP feature. +- **Test sources.** Covered since ADFA-7115: `src/test/**` and `src/androidTest/**` are their own source modules, each a dependent and friend of its main module, so a search from main reaches them like any other dependent. ## Requirements @@ -88,16 +88,16 @@ The walk goes **up** only. Usages reachable solely through a subclass (`Base.foo | local val/var, parameter, local fun, local class, loop variable | containing file | | `private` top-level declaration | containing file (Kotlin private top-level is file-private) | | `private` class/object member | containing file | -| `internal` | the target's module | +| `internal` | every match-set member's module + its friends (the test modules over it) | | `protected`, `public`, default | every match-set member's module + its transitive dependents (`KotlinModuleDependentsProvider.getTransitiveDependents`) | The ticket's three resolution scopes fall out of this one code path rather than being three implementations. Cheap cases stay cheap: a search on a local variable never leaves the open file. -The last row unions **every match-set member's** module, not just the target's, because R3's up-walk and R4's dependents pull in opposite directions. With `Base` in `lib` and `Derived` in `app`, a `base.paint()` call written in `lib` is a usage of `Derived.paint` - but `lib` is a *dependency* of `app`, not a dependent, so the target's own module and dependents would never look at it. Library supers are already out of the match set, so the union cannot escape the workspace. The first three rows need no union: `private` cannot override, and this project model has no friend modules, so `internal` cannot be overridden across one. +The last row unions **every match-set member's** module, not just the target's, because R3's up-walk and R4's dependents pull in opposite directions. With `Base` in `lib` and `Derived` in `app`, a `base.paint()` call written in `lib` is a usage of `Derived.paint` - but `lib` is a *dependency* of `app`, not a dependent, so the target's own module and dependents would never look at it. Library supers are already out of the match set, so the union cannot escape the workspace. The `internal` row unions for the same reason: a test module may override main's `internal open` member, and calls written against main's declaration are usages of that override. The first three rows need no union: `private` cannot override. The first three rows need the declaration's path. The file the user is editing is a live `KtFile` built from the editor buffer, whose `virtualFile` is a non-physical `LightVirtualFile`, so the path comes from `backingFilePath` first and the VFS only as a fallback - go-to-definition's derivation. A target that still has no path cannot be confined to one file, but it is still unreferenceable outside its own module, so it falls back to the `internal` row rather than to the last one. -`internal` needs no widening for test sources. There is no test module to widen to - `KotlinModuleLayout.toKtModules` builds one `KtSourceModule` per Gradle module from `mainSourceSet` only, and `directFriendDependencies` is empty everywhere. +`internal` widens to friends only. `KotlinModuleLayout` gives each Gradle module a main `KtSourceModule` plus one per test source set (`:app[unitTest]`, `:app[androidTest]`), each listing main in `directFriendDependencies`. Main is nobody's friend, so an `internal` declaration in a test module stays in that module. **R5 - Candidate discovery.** Two tiers, because find usages is run *while* editing and unsaved text must not be invisible: @@ -172,12 +172,11 @@ Preemption is not cancellation, and the two must not share a handler. Both unwin - **Rename / safe-delete**, or anything that edits the usages found. - **Usages via subclasses** (the down-walk). Blocked on `DirectInheritorsProvider.computeIndex()` being cached; filed separately. - **Searching `.java` files** for usages of a Kotlin declaration. Filed separately. -- **Usages in test source sets.** Filed separately, as an LSP-wide content-root gap. - **Implicit call sites as results** (see Scope). - **KDoc `[link]`s as results.** Only `KtSimpleNameExpression`s are examined (R5). Go-to-definition navigates *from* a KDoc link, so this is an asymmetry, but a bounded one. - **Library-source usages**, via decompilation or `-sources.jar`. - **Categorising results** (imports vs calls vs type references) - the panel has no grouping beyond file. -- **A partiality signal.** `ReferenceResult` is shared with the Java and XML servers and has no field for it, and `showLocations` has no header slot; the same caveat already applies silently to test sources. +- **A partiality signal.** `ReferenceResult` is shared with the Java and XML servers and has no field for it, and `showLocations` has no header slot. - **A gesture trigger.** Editor-wide UX change that would apply to Java too. ## Acceptance criteria @@ -188,7 +187,7 @@ Preemption is not cancellation, and the two must not share a handler. Both unwin 4. Inter-module: usages in a dependent module are listed. 5. Invoked from a **reference** rather than a declaration, the result is the same set. 6. A `private` top-level declaration reports no usages from another file, even when that file contains a same-named unrelated declaration. -7. An `internal` declaration reports usages within its module only. +7. An `internal` declaration reports usages within its module and that module's test sources only. 8. A local variable's usages are confined to its file. 9. `Foo()` is reported as a usage of `class Foo`. 10. An `import` of the target is reported as a usage. 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 587bb4a91c..b9b2621044 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 @@ -3,6 +3,7 @@ package com.itsaky.androidide.lsp.kotlin.compiler import com.itsaky.androidide.projects.api.AndroidModule 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.nio.file.Path @@ -14,8 +15,9 @@ import java.nio.file.Path * classpaths are sets because the project model does not keep their order. * * @property bootClassPaths Boot classpath jars of every Android module, existing ones only, in order. - * @property libraries Every module's compile classpath, existing jars only. - * @property modules One entry per source module, in workspace order. + * @property libraries Every module's compile and test compile classpaths, existing jars only. + * @property modules One entry per source module, in workspace order, each Gradle module's main + * sources followed by its test sources. */ internal data class KotlinModuleLayout( val bootClassPaths: List, @@ -26,12 +28,15 @@ internal data class KotlinModuleLayout( /** * One source module of a [KotlinModuleLayout]. * - * @property path The Gradle project path, which identifies the module. + * @property path Identifies the module: the Gradle project path for main sources, with a + * scope suffix for other scopes' sources (see [testModulePath]). * @property sourceRoots The module's source directories. * @property classpath The compile classpath without generated sources. - * @property moduleDependencies Gradle paths of the modules this one compiles against. + * @property moduleDependencies Paths of the modules this one compiles against. * @property apiVersion The Kotlin API version, or null when the module has no Java or Android project. * @property jvmTarget The Kotlin JVM target, or null when the module has no Java or Android project. + * @property friends Paths of the modules whose `internal` declarations this one may use: a test + * module's main module. */ internal data class SourceModuleLayout( val path: String, @@ -41,8 +46,15 @@ internal data class SourceModuleLayout( val moduleDependencies: List, val apiVersion: String?, val jvmTarget: String?, + val friends: List = emptyList(), ) +/** The [SourceModuleLayout.path] of the [scope] module of the Gradle module at [path]. */ +internal fun testModulePath( + path: String, + scope: ArtifactScope, +): String = "$path[${scope.moduleSuffix}]" + /** * Returns the [KotlinModuleLayout] of this workspace. Reads the file system, so not on the main thread. * @@ -65,17 +77,24 @@ internal fun Workspace.kotlinModuleLayout(): KotlinModuleLayout { val libraries = moduleProjects - .flatMap { it.getCompileClasspaths() } - .filter { it.exists() } + .flatMap { module -> + module.getCompileClasspaths() + module.nonMainScopes().flatMap { module.getCompileClasspaths(it) } + }.filter { it.exists() } .mapTo(LinkedHashSet()) { it.toPath() } return KotlinModuleLayout( bootClassPaths = bootClassPaths, libraries = libraries, - modules = moduleProjects.map { it.sourceModuleLayout() }, + modules = + moduleProjects.flatMap { module -> + val main = module.sourceModuleLayout() + listOf(main) + module.nonMainScopes().mapNotNull { module.testModuleLayout(main, it) } + }, ) } +private fun ModuleProject.nonMainScopes() = getArtifactScopes().filter { it != ArtifactScope.Main } + private fun ModuleProject.sourceModuleLayout(): SourceModuleLayout { val kotlinSettings = when { @@ -94,3 +113,40 @@ private fun ModuleProject.sourceModuleLayout(): SourceModuleLayout { jvmTarget = kotlinSettings?.jvmTarget, ) } + +/** + * The [scope] module layered over [main], or null when none of its source dirs exists. It is + * main's friend, so it may use `internal` declarations, and compiles against main, everything main + * does, the scopes it sees and its own scope-only modules. No two test modules depend on each other. + */ +private fun ModuleProject.testModuleLayout( + main: SourceModuleLayout, + scope: ArtifactScope, +): SourceModuleLayout? { + val sourceRoots = getSourceDirectories(scope).mapTo(LinkedHashSet()) { it.toPath() } + if (sourceRoots.isEmpty()) { + return null + } + + val ownSeenScopes = + nonMainScopes() + .filter { it != scope && scope.sees(it) && hasScopeModule(it) } + .map { testModulePath(path, it) } + // Scope-only project dependencies must be source modules: the scope's classpath leaves out their jars. + val scopeOnlyModules = getCompileModuleProjects(scope).map { it.path } + + return main.copy( + path = testModulePath(path, scope), + name = "$name (${scope.displayName()})", + sourceRoots = sourceRoots, + classpath = getCompileClasspaths(scope, excludeSourceGeneratedClassPath = true).mapTo(LinkedHashSet()) { it.toPath() }, + moduleDependencies = (listOf(path) + ownSeenScopes + main.moduleDependencies + scopeOnlyModules).distinct(), + friends = listOf(path), + ) +} + +/** 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() + +/** `unitTest` -> `unit test`. */ +private fun ArtifactScope.displayName(): String = moduleSuffix.replace(Regex("[A-Z]")) { " " + it.value.lowercase() } diff --git a/lsp/kotlin/src/main/java/com/itsaky/androidide/lsp/kotlin/compiler/WorkspaceExts.kt b/lsp/kotlin/src/main/java/com/itsaky/androidide/lsp/kotlin/compiler/WorkspaceExts.kt index b27e8bc63f..f9841591e3 100644 --- a/lsp/kotlin/src/main/java/com/itsaky/androidide/lsp/kotlin/compiler/WorkspaceExts.kt +++ b/lsp/kotlin/src/main/java/com/itsaky/androidide/lsp/kotlin/compiler/WorkspaceExts.kt @@ -13,7 +13,7 @@ import kotlin.io.path.pathString private val logger = LoggerFactory.getLogger("WorkspaceExts") -/** Builds the analysis modules this layout describes, one per source module. */ +/** Builds the analysis modules this layout describes, one per source module, test modules included. */ internal fun KotlinModuleLayout.toKtModules( project: Project, appEnv: CoreApplicationEnvironment, @@ -66,6 +66,11 @@ internal fun KotlinModuleLayout.toKtModules( .filterNot { it in modulesInProgress } .mapNotNull { layoutsByPath[it] } .forEach { dep -> addDependency(getOrCreateModule(dep)) } + + // A friend is always a module dependency too, so it is built by now. + moduleLayout.friends + .mapNotNull { sourceModules[it] } + .forEach { addFriend(it) } } modulesInProgress -= moduleLayout.path diff --git a/lsp/kotlin/src/main/java/com/itsaky/androidide/lsp/kotlin/compiler/modules/KtSourceModule.kt b/lsp/kotlin/src/main/java/com/itsaky/androidide/lsp/kotlin/compiler/modules/KtSourceModule.kt index bd618baf4a..c4fbba9c0d 100644 --- a/lsp/kotlin/src/main/java/com/itsaky/androidide/lsp/kotlin/compiler/modules/KtSourceModule.kt +++ b/lsp/kotlin/src/main/java/com/itsaky/androidide/lsp/kotlin/compiler/modules/KtSourceModule.kt @@ -22,6 +22,7 @@ internal class KtSourceModule( project: Project, val layout: SourceModuleLayout, directRegularDependencies: List, + override val directFriendDependencies: List, ) : AbstractSourceModule(project, directRegularDependencies), KaSourceModule { companion object { @@ -36,11 +37,18 @@ internal class KtSourceModule( // A set: a jar on both the boot and compile classpath is one shared module (ADFA-6381). private val dependencies = linkedSetOf() + private val friends = linkedSetOf() + fun addDependency(dep: KtModule) { dependencies.add(dep) } - fun build(): KtSourceModule = KtSourceModule(project, layout, dependencies.toList()) + /** Lets this module use [friend]'s `internal` declarations, as a test module does its main module's. */ + fun addFriend(friend: KtModule) { + friends.add(friend) + } + + fun build(): KtSourceModule = KtSourceModule(project, layout, dependencies.toList(), friends.toList()) } override val id: String diff --git a/lsp/kotlin/src/main/java/com/itsaky/androidide/lsp/kotlin/navigation/FindUsages.kt b/lsp/kotlin/src/main/java/com/itsaky/androidide/lsp/kotlin/navigation/FindUsages.kt index a4ec1bac93..d6ca65a024 100644 --- a/lsp/kotlin/src/main/java/com/itsaky/androidide/lsp/kotlin/navigation/FindUsages.kt +++ b/lsp/kotlin/src/main/java/com/itsaky/androidide/lsp/kotlin/navigation/FindUsages.kt @@ -318,14 +318,26 @@ private fun KaSession.scopeOf( val module = moduleOf(declaration) ?: return fileOnly ?: UsageSearchScope.Modules(sourceModules()) - // internal is module-wide, and there is no associated test module to widen to: this project model - // builds one module per Gradle module from the main source set only. A file-confined target with no - // derivable path lands here too - it cannot be narrowed to one file, but it is still unreferenceable - // outside its own module, so it must not fall through to the dependents below. - if (fileConfined || symbol.visibility == KaSymbolVisibility.INTERNAL) { + // A file-confined target with no derivable path cannot be narrowed to one file, but it is still + // unreferenceable outside its own module, so it must not fall through to the dependents below. + if (fileConfined) { return UsageSearchScope.Modules(listOf(module)) } + // internal reaches its own module and that module's friends: the test modules layered over a main + // module. An internal override in a test module answers calls written against main's declaration + // (R3), so every match-set member's module is a root, as below. + if (symbol.visibility == KaSymbolVisibility.INTERNAL) { + val roots = LinkedHashSet() + roots.add(module) + for (member in matchSet) { + val memberDeclaration = member.sourcePsiSafe() ?: continue + moduleOf(memberDeclaration)?.let(roots::add) + } + val friends = sourceModules().filter { candidate -> candidate.directFriendDependencies.any { it in roots } } + return UsageSearchScope.Modules((roots + friends).toList()) + } + // Anything more visible can be referenced from any module that depends on this one. Dependents, // not all modules: a module that cannot see the declaration cannot reference it. // diff --git a/lsp/kotlin/src/main/java/com/itsaky/androidide/lsp/kotlin/utils/SymbolVisibilityChecker.kt b/lsp/kotlin/src/main/java/com/itsaky/androidide/lsp/kotlin/utils/SymbolVisibilityChecker.kt index 69c4c612c2..d26e29f61c 100644 --- a/lsp/kotlin/src/main/java/com/itsaky/androidide/lsp/kotlin/utils/SymbolVisibilityChecker.kt +++ b/lsp/kotlin/src/main/java/com/itsaky/androidide/lsp/kotlin/utils/SymbolVisibilityChecker.kt @@ -24,8 +24,9 @@ internal class SymbolVisibilityChecker( useSiteModule: KaModule, useSitePackage: String? = null, ): Boolean { - val declaringModule = structureProvider.findModuleForSourceId(symbol.sourceId) - ?: return false + val declaringModule = + structureProvider.findModuleForSourceId(symbol.sourceId) + ?: return false if (!isReachable(useSiteModule, declaringModule)) return false if (!arePlatformCompatible(useSiteModule, declaringModule)) return false @@ -34,7 +35,10 @@ internal class SymbolVisibilityChecker( return true } - fun isReachable(useSiteModule: KaModule, declaringModule: KaModule): Boolean { + fun isReachable( + useSiteModule: KaModule, + declaringModule: KaModule, + ): Boolean { if (useSiteModule == declaringModule) return true if (moduleVisibilityCache[useSiteModule]?.contains(declaringModule) == true) return true @@ -54,7 +58,10 @@ internal class SymbolVisibilityChecker( return false } - fun arePlatformCompatible(useSiteModule: KaModule, declaringModule: KaModule): Boolean { + fun arePlatformCompatible( + useSiteModule: KaModule, + declaringModule: KaModule, + ): Boolean { val usePlatform = useSiteModule.targetPlatform val declPlatform = declaringModule.targetPlatform @@ -84,7 +91,7 @@ internal class SymbolVisibilityChecker( return when (symbol.visibility) { JvmVisibility.PUBLIC -> true JvmVisibility.PRIVATE -> false - JvmVisibility.INTERNAL -> useSiteModule == declaringModule + JvmVisibility.INTERNAL -> useSiteModule == declaringModule || declaringModule in useSiteModule.directFriendDependencies JvmVisibility.PROTECTED -> isSamePackage || isDescendant JvmVisibility.PACKAGE_PRIVATE -> isSamePackage } diff --git a/lsp/kotlin/src/test/java/com/itsaky/androidide/lsp/kotlin/compiler/CollectKtModulesTest.kt b/lsp/kotlin/src/test/java/com/itsaky/androidide/lsp/kotlin/compiler/CollectKtModulesTest.kt index fab042ad16..7afa3b192d 100644 --- a/lsp/kotlin/src/test/java/com/itsaky/androidide/lsp/kotlin/compiler/CollectKtModulesTest.kt +++ b/lsp/kotlin/src/test/java/com/itsaky/androidide/lsp/kotlin/compiler/CollectKtModulesTest.kt @@ -4,6 +4,7 @@ import com.google.common.truth.Truth.assertThat import com.itsaky.androidide.lsp.kotlin.compiler.modules.KtLibraryModule import com.itsaky.androidide.lsp.kotlin.compiler.modules.KtSourceModule import com.itsaky.androidide.lsp.kotlin.fixtures.KtLspTest +import com.itsaky.androidide.lsp.kotlin.fixtures.TestSources import com.itsaky.androidide.lsp.kotlin.fixtures.gradleProject import com.itsaky.androidide.projects.ProjectManagerImpl import com.itsaky.androidide.projects.api.AndroidModule @@ -81,6 +82,117 @@ class CollectKtModulesTest : KtLspTest() { assertThat(sourceModules.single { it.id == ":j" }.libraryDeps(androidJar)).hasSize(1) } + @Test + fun `each test source set is its own module over main`() { + val junit = tempJar("junit.jar") + val espresso = tempJar("espresso.jar") + val sourceModules = + collect( + listOf( + AndroidModule( + gradleProject( + ":app", + unitTests = TestSources(listOf(tempDir("app/src/test/java")), listOf(junit)), + androidTests = TestSources(listOf(tempDir("app/src/androidTest/java")), listOf(espresso)), + ), + ), + ), + ) + + val main = sourceModules.single { it.id == ":app" } + val unit = sourceModules.single { it.id == ":app[unitTest]" } + val device = sourceModules.single { it.id == ":app[androidTest]" } + + assertThat(main.contentRoots).containsNoneIn(unit.contentRoots + device.contentRoots) + for (test in listOf(unit, device)) { + assertThat(test.directRegularDependencies).contains(main) + assertThat(test.directFriendDependencies).containsExactly(main) + } + assertThat(main.directFriendDependencies).isEmpty() + + // The scopes are isolated: neither test module, nor main, sees the other's sources or jars. + assertThat(unit.directRegularDependencies).doesNotContain(device) + assertThat(device.directRegularDependencies).doesNotContain(unit) + assertThat(unit.libraryDeps(junit)).hasSize(1) + assertThat(unit.libraryDeps(espresso)).isEmpty() + assertThat(device.libraryDeps(espresso)).hasSize(1) + assertThat(device.libraryDeps(junit)).isEmpty() + assertThat(main.libraryDeps(junit) + main.libraryDeps(espresso)).isEmpty() + } + + @Test + fun `a test module also depends on what main depends on`() { + val sourceModules = + collect( + listOf( + AndroidModule(gradleProject(":lib", bootClassPath = tempJar("android.jar"))), + AndroidModule( + gradleProject( + ":app", + projectDeps = listOf(":lib"), + unitTests = TestSources(listOf(tempDir("app/src/test/java"))), + ), + ), + ), + ) + + val lib = sourceModules.single { it.id == ":lib" } + val unit = sourceModules.single { it.id == ":app[unitTest]" } + assertThat(unit.directRegularDependencies).contains(lib) + // lib's internals stay hidden: only the test module's own main module is a friend. + assertThat(unit.directFriendDependencies.map { it.id }).containsExactly(":app") + } + + @Test + fun `a test-only project dependency is a source module of that test scope only`() { + val sourceModules = + collect( + listOf( + AndroidModule(gradleProject(":lib", bootClassPath = tempJar("android.jar"))), + AndroidModule( + gradleProject( + ":app", + unitTests = TestSources(listOf(tempDir("app/src/test/java")), projects = listOf(":lib")), + androidTests = TestSources(listOf(tempDir("app/src/androidTest/java"))), + ), + ), + ), + ) + + val lib = sourceModules.single { it.id == ":lib" } + assertThat(sourceModules.single { it.id == ":app[unitTest]" }.directRegularDependencies).contains(lib) + assertThat(sourceModules.single { it.id == ":app[androidTest]" }.directRegularDependencies).doesNotContain(lib) + assertThat(sourceModules.single { it.id == ":app" }.directRegularDependencies).doesNotContain(lib) + } + + @Test + fun `req 5 - a test module depends on the module's test fixtures module but not the reverse`() { + val sourceModules = + collect( + listOf( + AndroidModule( + gradleProject( + ":app", + unitTests = TestSources(listOf(tempDir("app/src/test/java"))), + testFixtures = TestSources(listOf(tempDir("app/src/testFixtures/java"))), + ), + ), + ), + ) + + val fixtures = sourceModules.single { it.id == ":app[testFixtures]" } + val unit = sourceModules.single { it.id == ":app[unitTest]" } + assertThat(unit.directRegularDependencies).contains(fixtures) + assertThat(fixtures.directRegularDependencies).doesNotContain(unit) + assertThat(sourceModules.single { it.id == ":app" }.directRegularDependencies).doesNotContain(fixtures) + } + + private fun tempDir(name: String): Path = + lspTestRule.tempDir.root + .toPath() + .resolve(name) + .also { it.toFile().mkdirs() } + private fun tempJar(name: String): Path = lspTestRule.tempDir.root .toPath() 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 7c7ed9749b..3a634a6c64 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 @@ -1,7 +1,9 @@ package com.itsaky.androidide.lsp.kotlin.compiler import com.google.common.truth.Truth.assertThat +import com.itsaky.androidide.lsp.kotlin.fixtures.TestSources import com.itsaky.androidide.lsp.kotlin.fixtures.gradleProject +import com.itsaky.androidide.projects.api.AndroidModule import com.itsaky.androidide.projects.api.GradleProject import com.itsaky.androidide.projects.api.JavaModule import com.itsaky.androidide.projects.api.Workspace @@ -53,6 +55,13 @@ class KotlinModuleLayoutTest { assertThat(layoutOf(jvmTarget = "17")).isNotEqualTo(layoutOf(jvmTarget = "11")) } + private fun layoutWithUnitTests(dir: Path): KotlinModuleLayout = + Workspace( + rootProject = GradleProject(gradleProject(":")), + subProjects = listOf(AndroidModule(gradleProject(":app", unitTests = TestSources(listOf(dir))))), + syncIssues = emptyList(), + ).kotlinModuleLayout() + private fun tempJar(name: String): Path = tempDir.root .toPath() diff --git a/lsp/kotlin/src/test/java/com/itsaky/androidide/lsp/kotlin/fixtures/GradleProjectFixtures.kt b/lsp/kotlin/src/test/java/com/itsaky/androidide/lsp/kotlin/fixtures/GradleProjectFixtures.kt index 35475e8ee6..058ed62c61 100644 --- a/lsp/kotlin/src/test/java/com/itsaky/androidide/lsp/kotlin/fixtures/GradleProjectFixtures.kt +++ b/lsp/kotlin/src/test/java/com/itsaky/androidide/lsp/kotlin/fixtures/GradleProjectFixtures.kt @@ -13,7 +13,9 @@ import kotlin.io.path.pathString * Builds a minimal Gradle project model at [path], an Android library when [bootClassPath] or * [projectDeps] is set, a Java project with [compileJars] on its compile classpath (in order) otherwise. * - * [projectDeps] are Gradle paths of the projects the Android library compiles against. + * [projectDeps] are Gradle paths of the projects the Android library compiles against. [unitTests], + * [androidTests] and [testFixtures], when set, give the Android library that source set with those + * jars on its own compile classpath. */ internal fun gradleProject( path: String, @@ -21,6 +23,9 @@ internal fun gradleProject( compileJars: List = emptyList(), jvmTarget: String? = null, projectDeps: List = emptyList(), + unitTests: TestSources? = null, + androidTests: TestSources? = null, + testFixtures: TestSources? = null, ): GradleModels.GradleProject { val dir = "/tmp/collect-kt-modules${path.replace(':', '/')}" return GradleModels.GradleProject @@ -31,13 +36,26 @@ internal fun gradleProject( .setBuildDirPath("$dir/build") .setBuildScriptPath("$dir/build.gradle") .apply { - if (bootClassPath != null || projectDeps.isNotEmpty()) { + val scoped = + listOfNotNull( + unitTests?.let { ArtifactScope.UNIT_TEST to it }, + androidTests?.let { ArtifactScope.ANDROID_TEST to it }, + testFixtures?.let { ArtifactScope.TestFixtures to it }, + ) + if (bootClassPath != null || projectDeps.isNotEmpty() || scoped.isNotEmpty()) { + val variantDeps = projectDependencies(projectDeps).toBuilder() + val sourceSet = AndroidModels.SourceSetContainer.newBuilder() + for ((scope, sources) in scoped) { + sourceSet.putSourceProviders(scope.key, sources.sourceProvider()) + variantDeps.putArtifacts(scope.key, sources.addJarsTo(variantDeps)) + } setAndroidProject( AndroidModels.AndroidProject .newBuilder() .setProjectType(AndroidModels.ProjectType.LibraryProject) .apply { bootClassPath?.let { addBootClassPaths(it.pathString) } } - .setVariantDependencies(projectDependencies(projectDeps)), + .apply { if (scoped.isNotEmpty()) setMainSourceSet(sourceSet) } + .setVariantDependencies(variantDeps), ) } if (compileJars.isNotEmpty() || jvmTarget != null) { @@ -63,6 +81,62 @@ internal fun gradleProject( }.build() } +/** A test source set: its source [dirs], and the [jars] and [projects] only its tests compile against. */ +internal data class TestSources( + val dirs: List, + val jars: List = emptyList(), + val projects: List = emptyList(), +) + +private fun TestSources.sourceProvider(): AndroidModels.SourceProvider = + AndroidModels.SourceProvider + .newBuilder() + .addAllJavaDirs(dirs.map { it.pathString }) + .build() + +/** Registers [TestSources.jars] as libraries of [variantDeps] and returns a graph with one root per jar. */ +private fun TestSources.addJarsTo(variantDeps: AndroidModels.VariantDependencies.Builder): AndroidModels.ArtifactDependencies { + val graph = AndroidModels.DependencyGraph.newBuilder() + for (jar in jars) { + val key = "jar:${jar.pathString}" + graph.addRoot(graph.nodeCount) + graph.addNode(AndroidModels.GraphNode.newBuilder().setKeyId(graph.keyCount)) + graph.addKey(key) + variantDeps.putLibraries( + key, + AndroidModels.Library + .newBuilder() + .setKey(key) + .setType(AndroidModels.LibraryType.ExternalJavaLibrary) + .setArtifactPath(jar.pathString) + .build(), + ) + } + for (projectPath in projects) { + val key = "project$projectPath" + graph.addRoot(graph.nodeCount) + graph.addNode(AndroidModels.GraphNode.newBuilder().setKeyId(graph.keyCount)) + graph.addKey(key) + variantDeps.putLibraries( + key, + AndroidModels.Library + .newBuilder() + .setKey(key) + .setType(AndroidModels.LibraryType.Project) + .setProjectInfo( + AndroidModels.ProjectInfo + .newBuilder() + .setBuildId(":") + .setProjectPath(projectPath), + ).build(), + ) + } + return AndroidModels.ArtifactDependencies + .newBuilder() + .setCompileGraph(graph) + .build() +} + /** Encodes [projectPaths] as root `Project` libraries of the main artifact's compile graph, as the tooling layer does. */ private fun projectDependencies(projectPaths: List): AndroidModels.VariantDependencies { val graph = AndroidModels.DependencyGraph.newBuilder() 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 eebbc340f1..bd39655ad6 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 @@ -208,6 +208,7 @@ internal class KtLspTestEnvironment( name = spec.name, roots = setOf(checkNotNull(rootByModule[name])), dependencies = libraryDeps + spec.dependsOn.map { checkNotNull(built[it]) }, + directFriendDependencies = spec.friends.map { checkNotNull(built[it]) { "Friend '$it' must be in dependsOn" } }, languageVersion = languageVersion, ) } diff --git a/lsp/kotlin/src/test/java/com/itsaky/androidide/lsp/kotlin/fixtures/TestKtSourceModule.kt b/lsp/kotlin/src/test/java/com/itsaky/androidide/lsp/kotlin/fixtures/TestKtSourceModule.kt index 89cf91e305..60217ee6d2 100644 --- a/lsp/kotlin/src/test/java/com/itsaky/androidide/lsp/kotlin/fixtures/TestKtSourceModule.kt +++ b/lsp/kotlin/src/test/java/com/itsaky/androidide/lsp/kotlin/fixtures/TestKtSourceModule.kt @@ -23,6 +23,7 @@ internal class TestKtSourceModule( override val name: String, roots: Set, dependencies: List = emptyList(), + override val directFriendDependencies: List = emptyList(), languageVersion: LanguageVersion = DEFAULT_LANGUAGE_VERSION, jvmTarget: JvmTarget = DEFAULT_JVM_TARGET, ) : AbstractSourceModule(project, dependencies), diff --git a/lsp/kotlin/src/test/java/com/itsaky/androidide/lsp/kotlin/fixtures/TestSourceModuleSpec.kt b/lsp/kotlin/src/test/java/com/itsaky/androidide/lsp/kotlin/fixtures/TestSourceModuleSpec.kt index 4f6abb999c..4ddb56f77c 100644 --- a/lsp/kotlin/src/test/java/com/itsaky/androidide/lsp/kotlin/fixtures/TestSourceModuleSpec.kt +++ b/lsp/kotlin/src/test/java/com/itsaky/androidide/lsp/kotlin/fixtures/TestSourceModuleSpec.kt @@ -7,9 +7,12 @@ package com.itsaky.androidide.lsp.kotlin.fixtures * @param dirName Directory created for this module's source root, under the test's temp folder. * @param dependsOn Names of other source modules this one depends on. Empty means it sees only * the JDK, the stdlib and any extra jars. + * @param friends Names of modules whose `internal` declarations this one may use, as a test module + * uses its main module's. Each must also be in [dependsOn]. */ internal data class TestSourceModuleSpec( val name: String, val dirName: String = name, val dependsOn: List = emptyList(), + val friends: List = emptyList(), ) diff --git a/lsp/kotlin/src/test/java/com/itsaky/androidide/lsp/kotlin/navigation/TestSourceScopesTest.kt b/lsp/kotlin/src/test/java/com/itsaky/androidide/lsp/kotlin/navigation/TestSourceScopesTest.kt new file mode 100644 index 0000000000..b39769d79e --- /dev/null +++ b/lsp/kotlin/src/test/java/com/itsaky/androidide/lsp/kotlin/navigation/TestSourceScopesTest.kt @@ -0,0 +1,91 @@ +package com.itsaky.androidide.lsp.kotlin.navigation + +import com.google.common.truth.Truth.assertThat +import com.itsaky.androidide.lsp.kotlin.fixtures.KtLspTest +import com.itsaky.androidide.lsp.kotlin.fixtures.TestSourceModuleSpec +import com.itsaky.androidide.lsp.models.ReferenceParams +import com.itsaky.androidide.models.Position +import com.itsaky.androidide.progress.ICancelChecker +import kotlinx.coroutines.runBlocking +import org.jetbrains.kotlin.analysis.api.components.KaDiagnosticCheckerFilter +import org.jetbrains.kotlin.psi.KtFile +import org.junit.Test +import java.nio.file.Path + +/** + * Test sources are modules layered over main (ADFA-7115): each sees main, `internal` included, and + * find usages from main reaches them, while main and the other test scope see none of their code. + */ +class TestSourceScopesTest : KtLspTest() { + override val moduleSpecs = + listOf( + TestSourceModuleSpec("main"), + TestSourceModuleSpec("unitTest", dependsOn = listOf("main"), friends = listOf("main")), + TestSourceModuleSpec("androidTest", dependsOn = listOf("main"), friends = listOf("main")), + ) + + @Test + fun `find usages of a main declaration reaches both test scopes`() { + val main = "package p\n\nfun shared() {}\n" + val mainPath = path(createSourceFile("main", "p/Shared.kt", main)) + val unit = path(createSourceFile("unitTest", "p/UnitUse.kt", "package p\n\nfun u() { shared() }\n")) + val device = path(createSourceFile("androidTest", "p/DeviceUse.kt", "package p\n\nfun d() { shared() }\n")) + + val usages = usagesAt(mainPath, main.indexOf("shared")) + + assertThat(usages.map { it.first }).containsExactly(unit, device) + } + + @Test + fun `find usages of an internal main declaration reaches its test modules`() { + val main = "package p\n\ninternal fun helper() {}\n" + val mainPath = path(createSourceFile("main", "p/Helper.kt", main)) + val unit = path(createSourceFile("unitTest", "p/UnitHelperUse.kt", "package p\n\nfun u() { helper() }\n")) + + val usages = usagesAt(mainPath, main.indexOf("helper")) + + assertThat(usages.map { it.first }).containsExactly(unit) + } + + @Test + fun `a test file may use an internal main declaration`() { + createSourceFile("main", "p/Internal.kt", "package p\n\ninternal fun helper(): Int = 1\n") + val test = createSourceFile("unitTest", "p/UsesInternal.kt", "package p\n\nfun t(): Int = helper()\n") + + assertThat(diagnostics(test)).isEmpty() + } + + @Test + fun `a unit test cannot see android test code`() { + createSourceFile("androidTest", "p/DeviceOnly.kt", "package p\n\nclass DeviceOnly\n") + val unit = createSourceFile("unitTest", "p/UsesDevice.kt", "package p\n\nval d = DeviceOnly()\n") + + assertThat(diagnostics(unit)).contains("UNRESOLVED_REFERENCE") + } + + @Test + fun `main cannot see test code`() { + createSourceFile("unitTest", "p/UnitOnly.kt", "package p\n\nclass UnitOnly\n") + val main = createSourceFile("main", "p/UsesUnit.kt", "package p\n\nval u = UnitOnly()\n") + + assertThat(diagnostics(main)).contains("UNRESOLVED_REFERENCE") + } + + private fun path(file: KtFile): Path = Path.of(file.virtualFile.path) + + private fun diagnostics(file: KtFile): List = + analyzeMaybeDanglingForTest(file) { + file.collectDiagnostics(KaDiagnosticCheckerFilter.EXTENDED_AND_COMMON_CHECKERS).map { it.factoryName } + } + + /** Usages for a caret at [offset] in [file], as (path, startOffset) pairs. */ + private fun usagesAt( + file: Path, + offset: Int, + ): List> = + runBlocking { + context(env) { + findUsagesAt(ReferenceParams(file, Position(0, 0, offset), true, ICancelChecker.NOOP)) + }.locations.map { it.file to it.range.start.index } + } +} diff --git a/lsp/kotlin/src/test/java/com/itsaky/androidide/lsp/kotlin/utils/SymbolVisibilityCheckerTest.kt b/lsp/kotlin/src/test/java/com/itsaky/androidide/lsp/kotlin/utils/SymbolVisibilityCheckerTest.kt index 6b8aa1728e..ba9f5e4890 100644 --- a/lsp/kotlin/src/test/java/com/itsaky/androidide/lsp/kotlin/utils/SymbolVisibilityCheckerTest.kt +++ b/lsp/kotlin/src/test/java/com/itsaky/androidide/lsp/kotlin/utils/SymbolVisibilityCheckerTest.kt @@ -2,6 +2,7 @@ package com.itsaky.androidide.lsp.kotlin.utils import com.google.common.truth.Truth.assertThat import com.itsaky.androidide.lsp.kotlin.compiler.services.ProjectStructureProvider +import io.mockk.every import io.mockk.mockk import org.appdevforall.codeonthego.indexing.jvm.JvmClassInfo import org.appdevforall.codeonthego.indexing.jvm.JvmSourceLanguage @@ -113,6 +114,22 @@ class SymbolVisibilityCheckerTest { ).isFalse() } + @Test + fun `INTERNAL symbol is visible from a friend module`() { + // A test module is its main module's friend (ADFA-7115). + val testModule: KaModule = + mockk(relaxed = true) { + every { directFriendDependencies } returns listOf(moduleA) + } + assertThat( + checker.isDeclarationVisible( + symbol(JvmVisibility.INTERNAL), + useSiteModule = testModule, + declaringModule = moduleA, + ), + ).isTrue() + } + @Test fun `PACKAGE_PRIVATE symbol is visible within same package`() { assertThat(