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 @@ -52,7 +52,8 @@ public static JavaCompilerService forFile(@NonNull File file) {
@Nullable
public static JavaCompilerService forFile(@NonNull Path file) {
final ModuleProject module = IProjectManager.getInstance().findModuleForFile(file, false);
return module == null ? null : get(module, file);
final ArtifactScope scope = module == null ? null : module.artifactScopeOf(file);
return scope == null ? null : getInstance().forModule(module, scope);
}

/** The compiler for {@code module}'s main sources. Use {@link #get(ModuleProject, Path)} for a file that may be a test. */
Expand All @@ -67,10 +68,16 @@ public static JavaCompilerService get(@NonNull ModuleProject module, @NonNull Fi
return get(module, file.toPath());
}

/** The compiler for the scope of {@code module} that holds {@code file}. */
/**
* The compiler for the scope of {@code module} that holds {@code file}, or the no-module compiler when {@code file} is outside every source directory of the selected variant; callers that would analyze such a file must check {@link ModuleProject#artifactScopeOf(Path)} first.
*/
@NonNull
public static JavaCompilerService get(@NonNull ModuleProject module, @NonNull Path file) {
return JavaCompilerProvider.getInstance().forModule(module, module.artifactScopeOf(file));
final ArtifactScope scope = module.artifactScopeOf(file);
if (scope == null) {
return JavaCompilerService.NO_MODULE_COMPILER;
}
return JavaCompilerProvider.getInstance().forModule(module, scope);
}

public static JavaCompilerProvider getInstance() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -251,7 +251,7 @@ class JavaLanguageServer : ILanguageServer {

override fun complete(params: CompletionParams?): CompletionResult {
val compiler = getCompiler(params!!.file)
if (!settings.completionsEnabled() || !completionProvider.canComplete(params.file)) {
if (!settings.completionsEnabled() || !completionProvider.canComplete(params.file) || isOutsideSelectedVariant(params.file)) {
return CompletionResult.EMPTY
}

Expand All @@ -274,7 +274,7 @@ class JavaLanguageServer : ILanguageServer {

override suspend fun findReferences(params: ReferenceParams): ReferenceResult {
val compiler = getCompiler(params.file)
return if (!settings.referencesEnabled()) {
return if (!settings.referencesEnabled() || isOutsideSelectedVariant(params.file)) {
ReferenceResult(emptyList())
} else {
ReferenceProvider(compiler, params.cancelChecker).findReferences(params)
Expand All @@ -283,7 +283,7 @@ class JavaLanguageServer : ILanguageServer {

override suspend fun findDefinition(params: DefinitionParams): DefinitionResult {
val compiler = getCompiler(params.file)
return if (!settings.definitionsEnabled()) {
return if (!settings.definitionsEnabled() || isOutsideSelectedVariant(params.file)) {
DefinitionResult(emptyList())
} else {
DefinitionProvider(compiler, settings, params.cancelChecker).findDefinition(params)
Expand All @@ -301,7 +301,7 @@ class JavaLanguageServer : ILanguageServer {

override suspend fun signatureHelp(params: SignatureHelpParams): SignatureHelp {
val compiler = getCompiler(params.file)
return if (!settings.signatureHelpEnabled()) {
return if (!settings.signatureHelpEnabled() || isOutsideSelectedVariant(params.file)) {
SignatureHelp(emptyList(), -1, -1)
} else {
SignatureProvider(compiler, params.cancelChecker).signatureHelp(params)
Expand Down Expand Up @@ -334,6 +334,10 @@ class JavaLanguageServer : ILanguageServer {
}
}

/** Whether [file] is in a module but not compiled by its selected variant, so it gets no analysis. */
private fun isOutsideSelectedVariant(file: Path): Boolean =
ProjectManagerImpl.getInstance().workspace?.isOutsideSelectedVariant(file) == true

@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
fun getCompiler(file: Path?): JavaCompilerService {
if (!DocumentUtils.isJavaFile(file)) {
Expand Down Expand Up @@ -368,8 +372,8 @@ class JavaLanguageServer : ILanguageServer {
val module =
getInstance()
.findModuleForFile(event.changedFile)
if (module != null) {
val changedScope = module.artifactScopeOf(event.changedFile)
val changedScope = module?.artifactScopeOf(event.changedFile)
if (module != null && changedScope != null) {
JavaCompilerProvider.getInstance().forModule(module, changedScope).onDocumentChange(event)
// Scopes that compile against the changed one (tests against main or fixtures) are stale now.
JavaCompilerProvider.getInstance().invalidateScopesSeeing(module, changedScope)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ abstract class BaseJavaCodeAction : EditorActionItem {
val module = IProjectManager.getInstance().findModuleForFile(file, false)

visible = isJava
enabled = isJava && module != null
enabled = isJava && module != null && module.artifactScopeOf(file) != null
}

fun performCodeAction(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,9 @@ class JavaDiagnosticProvider {
val module =
IProjectManager.getInstance().findModuleForFile(file, false)
?: return DiagnosticResult.NO_UPDATE
val compiler = JavaCompilerService(module, module.artifactScopeOf(file))
// Outside the selected variant: clear what an earlier variant reported, analyze nothing.
val scope = module.artifactScopeOf(file) ?: return DiagnosticResult(file, ArrayList())
Comment thread
itsaky-adfa marked this conversation as resolved.
Resolved
val compiler = JavaCompilerService(module, scope)

abortIfCancelled()

Expand Down
Original file line number Diff line number Diff line change
@@ -1,22 +1,25 @@
package com.itsaky.androidide.lsp.java

import com.google.common.truth.Truth.assertThat
import com.itsaky.androidide.eventbus.events.editor.DocumentOpenEvent
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 com.itsaky.androidide.utils.FileProvider
import kotlinx.coroutines.runBlocking
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import kotlin.io.path.readText

/**
* 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.
* release one, and a release-only source gets no analysis.
*/
@RunWith(RobolectricTestRunner::class)
class VariantSourceSetsTest {
Expand Down Expand Up @@ -67,4 +70,15 @@ class VariantSourceSetsTest {
assertThat(files.filterNot { "/src/debug/java/" in it }).isEmpty()
}
}

@Test
fun `a source of a variant that is not selected gets no diagnostics`() {
val releaseUser =
FileProvider
.testProjectRoot()
.resolve("app/src/release/java/com/itsaky/test/app/variant/ReleaseUser.java")
JavaLSPTest.dispatchEvent(DocumentOpenEvent(releaseUser, releaseUser.readText(), 0))

assertThat(runBlocking { JavaLSPTest.server.analyze(releaseUser) }.diagnostics).isEmpty()
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -229,6 +229,13 @@ class SourceFileManagerTestScopesTest {
private fun junitClasses(manager: SourceFileManager) =
manager.list(StandardLocation.CLASS_PATH, "org.junit", setOf(JavaFileObject.Kind.CLASS), false).toList()

@Test
fun `req 7 - a file outside every source set of the selected variant gets no compiler`() {
val other = source(temp.newFolder("app", "src", "release", "java"), "ReleaseOnly")

withAndroidJar { assertThat(JavaCompilerProvider.forFile(other)).isNull() }
}

/** Runs [block] with an android.jar set, as a compiler needs one, and drops the compilers it made. */
private fun withAndroidJar(block: () -> Unit) {
val previousAndroidJar = Environment.ANDROID_JAR
Expand Down Expand Up @@ -316,7 +323,9 @@ class SourceFileManagerTestScopesTest {
AndroidModels.AndroidProject
.newBuilder()
.setProjectType(AndroidModels.ProjectType.ApplicationProject)
.setMainSourceSet(
.addAllSourceSetDirPaths(
listOf(mainDir, unitDir, deviceDir, sharedDir, File(projectDir, "src/release/java")).map { it.path },
).setMainSourceSet(
AndroidModels.SourceSetContainer
.newBuilder()
.putSourceProviders(ArtifactScope.Main.key, provider(mainDir))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -382,6 +382,11 @@ class KotlinLanguageServer : ILanguageServer {
return DiagnosticResult.NO_UPDATE
}

// Outside the selected variant: clear what an earlier variant reported, analyze nothing.
if (ProjectManagerImpl.getInstance().workspace?.isOutsideSelectedVariant(file) == true) {
return DiagnosticResult(file, ArrayList())
}

return compiler
?.compilationEnvironmentForKotlinPath(file)
?.diagnosticsFor(file, createJobCancelChecker())
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package com.itsaky.androidide.lsp.kotlin.compiler

import com.itsaky.androidide.lsp.api.ILanguageClient
import com.itsaky.androidide.projects.IProjectManager
import com.itsaky.androidide.utils.DocumentUtils
import org.jetbrains.kotlin.com.intellij.openapi.vfs.StandardFileSystems
import org.jetbrains.kotlin.com.intellij.openapi.vfs.VirtualFileManager
Expand Down Expand Up @@ -66,10 +67,12 @@ internal class Compiler(
/**
* The environment for [file], or null when there is none. A `.kts` has no environment yet;
* this returns null for it rather than letting the kind-based overload's
* [UnsupportedOperationException] escape into an LSP request on an open build script.
* [UnsupportedOperationException] escape into an LSP request on an open build script. A file
* its module's selected variant does not compile has none either, so it gets no analysis.
*/
fun compilationEnvironmentFor(file: Path): CompilationEnvironment? {
if (!DocumentUtils.isKotlinFile(file)) return null
if (IProjectManager.getInstance().workspace?.isOutsideSelectedVariant(file) == true) return null
return compilationEnvironmentForKotlinPath(file)
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -133,6 +133,10 @@ private fun ModuleProject.testModuleLayout(
nonMainScopes()
.filter { it != scope && scope.sees(it) && hasScopeModule(it) }
.map { testModulePath(path, it) }
val otherModulesFixtures =
getTestFixturesModuleProjects(scope)
.filter { it.hasScopeModule(ArtifactScope.TestFixtures) }
.map { testModulePath(it.path, ArtifactScope.TestFixtures) }
// Scope-only project dependencies must be source modules: the scope's classpath leaves out their jars.
val scopeOnlyModules = getCompileModuleProjects(scope).map { it.path }

Expand All @@ -141,7 +145,7 @@ private fun ModuleProject.testModuleLayout(
name = "$name (${scope.displayName()})",
sourceRoots = sourceRoots,
classpath = getCompileClasspaths(scope, excludeSourceGeneratedClassPath = true).mapTo(LinkedHashSet()) { it.toPath() },
moduleDependencies = (listOf(path) + ownSeenScopes + main.moduleDependencies + scopeOnlyModules).distinct(),
moduleDependencies = (listOf(path) + ownSeenScopes + otherModulesFixtures + main.moduleDependencies + scopeOnlyModules).distinct(),
friends = listOf(path),
)
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,12 +35,13 @@ class VariantSourceSetsTest : KtLspTest() {

private lateinit var use: Path
private lateinit var completion: Path
private lateinit var releaseConfig: 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)
releaseConfig = write(baseDir, "src/release/kotlin/p/VariantConfig.kt", RELEASE_CONFIG)
return variantLayout(baseDir, listOf("debug", "release"), selected = "debug")
}

Expand Down Expand Up @@ -88,6 +89,20 @@ class VariantSourceSetsTest : KtLspTest() {
assertThat(labels).doesNotContain("releaseOnly")
}

@Test
fun `a source of a variant that is not selected gets no diagnostics`() {
val server = KotlinLanguageServer()
try {
val result = runBlocking { server.analyze(releaseConfig) }

// Cleared for this file, not merely "no update": an earlier variant's errors must go away.
assertThat(result.file).isEqualTo(releaseConfig)
assertThat(result.diagnostics).isEmpty()
} finally {
server.shutdown()
}
}

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"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -187,6 +187,34 @@ class CollectKtModulesTest : KtLspTest() {
assertThat(sourceModules.single { it.id == ":app" }.directRegularDependencies).doesNotContain(fixtures)
}

@Test
fun `req 10 - a unit test module depends on another module's test fixtures module`() {
val sourceModules =
collect(
listOf(
AndroidModule(
gradleProject(
":lib",
bootClassPath = tempJar("android.jar"),
testFixtures = TestSources(listOf(tempDir("lib/src/testFixtures/java"))),
),
),
AndroidModule(
gradleProject(
":app",
unitTests = TestSources(listOf(tempDir("app/src/test/java")), fixtureProjects = listOf(":lib")),
androidTests = TestSources(listOf(tempDir("app/src/androidTest/java"))),
),
),
),
)

val libFixtures = sourceModules.single { it.id == ":lib[testFixtures]" }
assertThat(sourceModules.single { it.id == ":app[unitTest]" }.directRegularDependencies).contains(libFixtures)
assertThat(sourceModules.single { it.id == ":app[androidTest]" }.directRegularDependencies).doesNotContain(libFixtures)
assertThat(sourceModules.single { it.id == ":app" }.directRegularDependencies).doesNotContain(libFixtures)
}

private fun tempDir(name: String): Path =
lspTestRule.tempDir.root
.toPath()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -81,11 +81,15 @@ internal fun gradleProject(
}.build()
}

/** A test source set: its source [dirs], and the [jars] and [projects] only its tests compile against. */
/**
* A test source set: its source [dirs], and the [jars] and [projects] only its tests compile
* against; [fixtureProjects] are projects whose test fixtures they compile against.
*/
internal data class TestSources(
val dirs: List<Path>,
val jars: List<Path> = emptyList(),
val projects: List<String> = emptyList(),
val fixtureProjects: List<String> = emptyList(),
)

private fun TestSources.sourceProvider(): AndroidModels.SourceProvider =
Expand All @@ -112,8 +116,8 @@ private fun TestSources.addJarsTo(variantDeps: AndroidModels.VariantDependencies
.build(),
)
}
for (projectPath in projects) {
val key = "project$projectPath"
for ((projectPath, fixtures) in projects.map { it to false } + fixtureProjects.map { it to true }) {
val key = if (fixtures) "project$projectPath:testFixtures" else "project$projectPath"
graph.addRoot(graph.nodeCount)
graph.addNode(AndroidModels.GraphNode.newBuilder().setKeyId(graph.keyCount))
graph.addKey(key)
Expand All @@ -127,7 +131,8 @@ private fun TestSources.addJarsTo(variantDeps: AndroidModels.VariantDependencies
AndroidModels.ProjectInfo
.newBuilder()
.setBuildId(":")
.setProjectPath(projectPath),
.setProjectPath(projectPath)
.setIsTestFixtures(fixtures),
).build(),
)
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,8 @@ internal fun variantLayout(
AndroidModels.SourceSetContainer
.newBuilder()
.putSourceProviders(ArtifactScope.Main.key, kotlinProvider(mainKotlin)),
).addAllVariant(variantKotlin.map { (name, kotlinDir) -> variant(name, kotlinDir) })
).addAllSourceSetDirPaths((listOf(mainKotlin) + variantKotlin.values).map { it.pathString })
.addAllVariant(variantKotlin.map { (name, kotlinDir) -> variant(name, kotlinDir) })
.setConfiguredVariantName(selected)
.setVariantDependencies(dependingOn(stdlib)),
).build()
Expand Down
9 changes: 9 additions & 0 deletions subprojects/project-models/src/main/proto/android.proto
Original file line number Diff line number Diff line change
Expand Up @@ -152,6 +152,10 @@ message ProjectInfo {

// The project path.
string projectPath = 2;

// Whether the dependency is on the project's test fixtures (testFixtures(project(":lib")))
// rather than on the project itself.
bool isTestFixtures = 3;
}

// An Android library.
Expand Down Expand Up @@ -336,4 +340,9 @@ message AndroidProject {

// The compiler settings for Kotlin sources.
optional KotlinCompilerSettings kotlinCompilerSettings = 11;

// The Java and Kotlin dirs of every source set AGP knows for this module: every component of the
// default config, every build type and flavor, and every variant's own and multi-flavor layers.
// A file in one of these that the selected variant does not compile gets no analysis.
repeated string sourceSetDirPaths = 12;
}
Loading
Loading