diff --git a/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/JavaCompilerProvider.java b/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/JavaCompilerProvider.java index 106d35bf83..900463b6d0 100644 --- a/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/JavaCompilerProvider.java +++ b/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/JavaCompilerProvider.java @@ -19,16 +19,17 @@ import androidx.annotation.NonNull; import androidx.annotation.Nullable; - import com.itsaky.androidide.lsp.java.compiler.JavaCompilerService; +import com.itsaky.androidide.projects.IProjectManager; import com.itsaky.androidide.projects.api.ModuleProject; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - +import com.itsaky.androidide.projects.models.ArtifactScope; +import java.io.File; +import java.nio.file.Path; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.function.Function; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; /** * Provides {@link JavaCompilerService} instances for different {@link ModuleProject}s. @@ -36,71 +37,111 @@ * @author Akash Yadav */ public class JavaCompilerProvider { - private static final Logger logger = LoggerFactory.getLogger(JavaCompilerProvider.class); - private static JavaCompilerProvider sInstance; - private final Map mCompilers = new ConcurrentHashMap<>(); - - private JavaCompilerProvider() {} - - @NonNull - public static JavaCompilerService get(ModuleProject module) { - return JavaCompilerProvider.getInstance().forModule(module); - } - - public static JavaCompilerProvider getInstance() { - if (sInstance == null) { - sInstance = new JavaCompilerProvider(); - } - - return sInstance; - } - - /** - * Iterate over all available {@link JavaCompilerService} instances to perform given {@code action} - * function and return the result of the function. - * - * @param action The function to consume the {@link JavaCompilerService} instances and produce a result. - * The function can return {@code null} to indicate that no result was produced for the - * provided element. If the function returns a non-null value, the iteration is stopped - * and the non-null result is returned. If the function returns {@code null} for all - * elements, then {@code null} is returned. - * @return The result of the action. - * @param The type of the result produced by the given function. - */ - @Nullable - public synchronized T find(Function action) { - logger.debug("find from {} compiler services", mCompilers.size()); - for (JavaCompilerService service : mCompilers.values()) { - final var result = action.apply(service); - if (result != null) { - return result; - } - } - return null; - } - - @NonNull - public synchronized JavaCompilerService forModule(ModuleProject module) { - // A module instance is set to the compiler only in case the project is initialized or - // this method was called with other module instance. - final JavaCompilerService cached = mCompilers.get(module); - if (cached != null && cached.getModule() != null) { - return cached; - } - - final JavaCompilerService newInstance = new JavaCompilerService(module); - mCompilers.put(module, newInstance); - - return newInstance; - } - - // TODO This currently destroys all the compiler instances - // We must have a method to destroy only the required instance in - // JavaLanguageServer.handleFailure(LSPFailure) - public synchronized void destroy() { - for (final JavaCompilerService compiler : mCompilers.values()) { - compiler.destroy(); - } - mCompilers.clear(); - } + private static final Logger logger = LoggerFactory.getLogger(JavaCompilerProvider.class); + private static JavaCompilerProvider sInstance; + + /** + * The compiler for {@code file}, per {@link #get(ModuleProject, Path)}, or null when no module holds it or it is outside every source directory of its module's selected variant. + */ + @Nullable + public static JavaCompilerService forFile(@NonNull File file) { + return forFile(file.toPath()); + } + + /** See {@link #forFile(File)}. */ + @Nullable + public static JavaCompilerService forFile(@NonNull Path file) { + final ModuleProject module = IProjectManager.getInstance().findModuleForFile(file, false); + return module == null ? null : get(module, file); + } + + /** The compiler for {@code module}'s main sources. Use {@link #get(ModuleProject, Path)} for a file that may be a test. */ + @NonNull + public static JavaCompilerService get(ModuleProject module) { + return JavaCompilerProvider.getInstance().forModule(module, ArtifactScope.Main.INSTANCE); + } + + /** See {@link #get(ModuleProject, Path)}. */ + @NonNull + public static JavaCompilerService get(@NonNull ModuleProject module, @NonNull File file) { + return get(module, file.toPath()); + } + + /** The compiler for the scope of {@code module} that holds {@code file}. */ + @NonNull + public static JavaCompilerService get(@NonNull ModuleProject module, @NonNull Path file) { + return JavaCompilerProvider.getInstance().forModule(module, module.artifactScopeOf(file)); + } + + public static JavaCompilerProvider getInstance() { + if (sInstance == null) { + sInstance = new JavaCompilerProvider(); + } + + return sInstance; + } + + // One compiler per module and test scope: each compiles against its own source path and classpath. + private final Map mCompilers = new ConcurrentHashMap<>(); + + private JavaCompilerProvider() {} + + // TODO This currently destroys all the compiler instances + // We must have a method to destroy only the required instance in + // JavaLanguageServer.handleFailure(LSPFailure) + public synchronized void destroy() { + for (final JavaCompilerService compiler : mCompilers.values()) { + compiler.destroy(); + } + mCompilers.clear(); + } + + /** + * Iterate over all available {@link JavaCompilerService} instances to perform given {@code action} function and return the result of the function. + * + * @param action + * The function to consume the {@link JavaCompilerService} instances and produce a result. The function can return {@code null} to indicate that no result was produced for the provided element. If the function returns a non-null value, the iteration is stopped and the non-null result is returned. If the function returns {@code null} for all elements, then {@code null} is returned. + * @return The result of the action. + * @param + * The type of the result produced by the given function. + */ + @Nullable + public synchronized T find(Function action) { + logger.debug("find from {} compiler services", mCompilers.size()); + for (JavaCompilerService service : mCompilers.values()) { + final var result = action.apply(service); + if (result != null) { + return result; + } + } + return null; + } + + /** The compiler for {@code module}'s {@code scope} sources. */ + @NonNull + public synchronized JavaCompilerService forModule(ModuleProject module, @NonNull ArtifactScope scope) { + // A module instance is set to the compiler only in case the project is initialized or + // this method was called with other module instance. + final Key key = new Key(module, scope); + final JavaCompilerService cached = mCompilers.get(key); + if (cached != null && cached.getModule() != null) { + return cached; + } + + final JavaCompilerService newInstance = new JavaCompilerService(module, scope); + mCompilers.put(key, newInstance); + + return newInstance; + } + + /** Invalidates the cached compiles of {@code module}'s other scopes that read {@code changed}'s sources. */ + public void invalidateScopesSeeing(@NonNull ModuleProject module, @NonNull ArtifactScope changed) { + mCompilers.forEach((key, compiler) -> { + if (key.module() == module && !key.scope().equals(changed) && key.scope().sees(changed)) { + compiler.invalidateCompile(); + } + }); + } + + private record Key(ModuleProject module, @NonNull ArtifactScope scope) {} } diff --git a/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/JavaLanguageServer.kt b/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/JavaLanguageServer.kt index 7666a741d5..2ebef64fac 100644 --- a/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/JavaLanguageServer.kt +++ b/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/JavaLanguageServer.kt @@ -342,7 +342,7 @@ class JavaLanguageServer : ILanguageServer { val module = ProjectManagerImpl.getInstance().findModuleForFile(file!!) ?: return JavaCompilerService.NO_MODULE_COMPILER - return JavaCompilerProvider.get(module) + return JavaCompilerProvider.get(module, file) } private fun startOrRestartAnalyzeTimer() { @@ -369,8 +369,10 @@ class JavaLanguageServer : ILanguageServer { getInstance() .findModuleForFile(event.changedFile) if (module != null) { - val compiler = JavaCompilerProvider.get(module) - compiler.onDocumentChange(event) + val changedScope = module.artifactScopeOf(event.changedFile) + 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) } startOrRestartAnalyzeTimer() } diff --git a/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/actions/BaseJavaCodeAction.kt b/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/actions/BaseJavaCodeAction.kt index 88906a07a5..6b019055a0 100644 --- a/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/actions/BaseJavaCodeAction.kt +++ b/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/actions/BaseJavaCodeAction.kt @@ -110,7 +110,7 @@ abstract class BaseJavaCodeAction : EditorActionItem { requireNotNull(module) { "Cannot get compiler instance. Unable to find module for file: ${requireFile().name}" } - return JavaCompilerProvider.get(module) + return JavaCompilerProvider.get(module, requireFile()) } } diff --git a/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/actions/FieldBasedAction.kt b/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/actions/FieldBasedAction.kt index 5e7ccfc7f1..e191719839 100644 --- a/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/actions/FieldBasedAction.kt +++ b/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/actions/FieldBasedAction.kt @@ -85,7 +85,7 @@ abstract class FieldBasedAction : BaseJavaCodeAction() { val file = data.requirePath() val module = IProjectManager.getInstance().findModuleForFile(file, false) ?: return Any() - return JavaCompilerProvider.get(module).compile(file).get { task -> + return JavaCompilerProvider.get(module, file).compile(file).get { task -> val triple = findFields(task, file, range) val type = triple?.second val fields = triple?.third diff --git a/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/actions/diagnostics/AddImportAction.kt b/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/actions/diagnostics/AddImportAction.kt index 90db5b1c6f..a393e409c3 100644 --- a/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/actions/diagnostics/AddImportAction.kt +++ b/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/actions/diagnostics/AddImportAction.kt @@ -112,7 +112,7 @@ class AddImportAction : BaseJavaCodeAction() { return@withContext ImportCandidates.None(simpleName) } - val compiler = JavaCompilerProvider.get(module) + val compiler = JavaCompilerProvider.get(module, data.requireFile()) val importingPackage = StringSearch.packageName(nioPath) val candidates = compiler.findImportableQualifiedNames(simpleName, importingPackage) @@ -159,7 +159,7 @@ class AddImportAction : BaseJavaCodeAction() { } val client = data.getLanguageClient() ?: return - val compiler = JavaCompilerProvider.get(module) + val compiler = JavaCompilerProvider.get(module, data.requireFile()) val actions = mutableListOf() for (index in result.rewrites.indices) { diff --git a/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/actions/diagnostics/AddThrowsAction.kt b/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/actions/diagnostics/AddThrowsAction.kt index f52e48134b..db8286fda5 100644 --- a/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/actions/diagnostics/AddThrowsAction.kt +++ b/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/actions/diagnostics/AddThrowsAction.kt @@ -1,89 +1,89 @@ -/* - * This file is part of AndroidIDE. - * - * AndroidIDE is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * AndroidIDE is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with AndroidIDE. If not, see . - */ -package com.itsaky.androidide.lsp.java.actions.diagnostics - -import com.itsaky.androidide.actions.ActionData -import com.itsaky.androidide.actions.hasRequiredData -import com.itsaky.androidide.actions.markInvisible -import com.itsaky.androidide.actions.requireFile -import com.itsaky.androidide.actions.requirePath -import com.itsaky.androidide.lsp.java.JavaCompilerProvider -import com.itsaky.androidide.lsp.java.actions.BaseJavaCodeAction -import com.itsaky.androidide.lsp.java.models.DiagnosticCode -import com.itsaky.androidide.lsp.java.rewrite.AddException -import com.itsaky.androidide.lsp.java.utils.CodeActionUtils -import com.itsaky.androidide.lsp.models.DiagnosticItem -import com.itsaky.androidide.projects.IProjectManager -import com.itsaky.androidide.resources.R -import org.slf4j.LoggerFactory - -/** @author Akash Yadav */ -class AddThrowsAction : BaseJavaCodeAction() { - - override val id = "ide.editor.lsp.java.diagnostics.addThrows" - override var label: String = "" - private val diagnosticCode = DiagnosticCode.NOT_THROWN.id - - override val titleTextRes: Int = R.string.action_add_throws - - companion object { - - private val log = LoggerFactory.getLogger(AddThrowsAction::class.java) - } - - override fun prepare(data: ActionData) { - super.prepare(data) - - if (!visible || !data.hasRequiredData(DiagnosticItem::class.java)) { - markInvisible() - return - } - - val diagnostic = data[DiagnosticItem::class.java]!! - if (diagnosticCode != diagnostic.code) { - markInvisible() - return - } - } - - override suspend fun execAction(data: ActionData): Any { - val diagnostic = data[DiagnosticItem::class.java]!! - val compiler = - JavaCompilerProvider.get( - IProjectManager.getInstance().findModuleForFile(data.requireFile(), false) ?: return Any()) - val file = data.requirePath() - return compiler.compile(file).get { task -> - val needsThrow = CodeActionUtils.findMethod(task, diagnostic.range) - val exceptionName = CodeActionUtils.extractExceptionName(diagnostic.message) - return@get AddException( - needsThrow.className, - needsThrow.methodName, - needsThrow.erasedParameterTypes, - exceptionName - ) - } - } - - override fun postExec(data: ActionData, result: Any) { - if (result !is AddException) { - log.warn("Unable to add 'throws' expression") - return - } - - performCodeAction(data, result) - } -} +/* + * This file is part of AndroidIDE. + * + * AndroidIDE is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * AndroidIDE is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with AndroidIDE. If not, see . + */ +package com.itsaky.androidide.lsp.java.actions.diagnostics + +import com.itsaky.androidide.actions.ActionData +import com.itsaky.androidide.actions.hasRequiredData +import com.itsaky.androidide.actions.markInvisible +import com.itsaky.androidide.actions.requireFile +import com.itsaky.androidide.actions.requirePath +import com.itsaky.androidide.lsp.java.JavaCompilerProvider +import com.itsaky.androidide.lsp.java.actions.BaseJavaCodeAction +import com.itsaky.androidide.lsp.java.models.DiagnosticCode +import com.itsaky.androidide.lsp.java.rewrite.AddException +import com.itsaky.androidide.lsp.java.utils.CodeActionUtils +import com.itsaky.androidide.lsp.models.DiagnosticItem +import com.itsaky.androidide.projects.IProjectManager +import com.itsaky.androidide.resources.R +import org.slf4j.LoggerFactory + +/** @author Akash Yadav */ +class AddThrowsAction : BaseJavaCodeAction() { + override val id = "ide.editor.lsp.java.diagnostics.addThrows" + override var label: String = "" + private val diagnosticCode = DiagnosticCode.NOT_THROWN.id + + override val titleTextRes: Int = R.string.action_add_throws + + companion object { + private val log = LoggerFactory.getLogger(AddThrowsAction::class.java) + } + + override fun prepare(data: ActionData) { + super.prepare(data) + + if (!visible || !data.hasRequiredData(DiagnosticItem::class.java)) { + markInvisible() + return + } + + val diagnostic = data[DiagnosticItem::class.java]!! + if (diagnosticCode != diagnostic.code) { + markInvisible() + return + } + } + + override suspend fun execAction(data: ActionData): Any { + val diagnostic = data[DiagnosticItem::class.java]!! + val compiler = + JavaCompilerProvider.forFile(data.requireFile()) ?: return Any() + val file = data.requirePath() + return compiler.compile(file).get { task -> + val needsThrow = CodeActionUtils.findMethod(task, diagnostic.range) + val exceptionName = CodeActionUtils.extractExceptionName(diagnostic.message) + return@get AddException( + needsThrow.className, + needsThrow.methodName, + needsThrow.erasedParameterTypes, + exceptionName, + ) + } + } + + override fun postExec( + data: ActionData, + result: Any, + ) { + if (result !is AddException) { + log.warn("Unable to add 'throws' expression") + return + } + + performCodeAction(data, result) + } +} diff --git a/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/actions/diagnostics/CreateMissingMethodAction.kt b/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/actions/diagnostics/CreateMissingMethodAction.kt index 75181aeac8..12c4a761bf 100644 --- a/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/actions/diagnostics/CreateMissingMethodAction.kt +++ b/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/actions/diagnostics/CreateMissingMethodAction.kt @@ -1,84 +1,84 @@ -/* - * This file is part of AndroidIDE. - * - * AndroidIDE is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * AndroidIDE is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with AndroidIDE. If not, see . - */ -package com.itsaky.androidide.lsp.java.actions.diagnostics - -import com.itsaky.androidide.actions.ActionData -import com.itsaky.androidide.actions.hasRequiredData -import com.itsaky.androidide.actions.markInvisible -import com.itsaky.androidide.actions.requireFile -import com.itsaky.androidide.actions.requirePath -import com.itsaky.androidide.lsp.java.JavaCompilerProvider -import com.itsaky.androidide.lsp.java.actions.BaseJavaCodeAction -import com.itsaky.androidide.lsp.java.models.DiagnosticCode -import com.itsaky.androidide.lsp.java.rewrite.CreateMissingMethod -import com.itsaky.androidide.lsp.java.utils.CodeActionUtils.findPosition -import com.itsaky.androidide.projects.IProjectManager -import com.itsaky.androidide.resources.R -import org.slf4j.LoggerFactory - -/** @author Akash Yadav */ -class CreateMissingMethodAction : BaseJavaCodeAction() { - - override val id: String = "ide.editor.lsp.java.diagnostics.createMissingMethod" - override var label: String = "" - private val diagnosticCode = DiagnosticCode.MISSING_METHOD.id - - override val titleTextRes: Int = R.string.action_create_missing_method - - companion object { - - private val log = LoggerFactory.getLogger(CreateMissingMethodAction::class.java) - } - - override fun prepare(data: ActionData) { - super.prepare(data) - - if ( - !visible || - !data.hasRequiredData(com.itsaky.androidide.lsp.models.DiagnosticItem::class.java) - ) { - markInvisible() - return - } - - val diagnostic = data[com.itsaky.androidide.lsp.models.DiagnosticItem::class.java]!! - if (diagnosticCode != diagnostic.code) { - markInvisible() - return - } - } - - override suspend fun execAction(data: ActionData): Any { - val diagnostic = data[com.itsaky.androidide.lsp.models.DiagnosticItem::class.java]!! - val compiler = - JavaCompilerProvider.get( - IProjectManager.getInstance().findModuleForFile(data.requireFile(), false) ?: return Any()) - val file = data.requirePath() - return compiler.compile(file).get { - CreateMissingMethod(file, findPosition(it, diagnostic.range.start)) - } - } - - override fun postExec(data: ActionData, result: Any) { - if (result !is CreateMissingMethod) { - log.warn("Unable to create missing method") - return - } - - performCodeAction(data, result) - } -} +/* + * This file is part of AndroidIDE. + * + * AndroidIDE is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * AndroidIDE is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with AndroidIDE. If not, see . + */ +package com.itsaky.androidide.lsp.java.actions.diagnostics + +import com.itsaky.androidide.actions.ActionData +import com.itsaky.androidide.actions.hasRequiredData +import com.itsaky.androidide.actions.markInvisible +import com.itsaky.androidide.actions.requireFile +import com.itsaky.androidide.actions.requirePath +import com.itsaky.androidide.lsp.java.JavaCompilerProvider +import com.itsaky.androidide.lsp.java.actions.BaseJavaCodeAction +import com.itsaky.androidide.lsp.java.models.DiagnosticCode +import com.itsaky.androidide.lsp.java.rewrite.CreateMissingMethod +import com.itsaky.androidide.lsp.java.utils.CodeActionUtils.findPosition +import com.itsaky.androidide.projects.IProjectManager +import com.itsaky.androidide.resources.R +import org.slf4j.LoggerFactory + +/** @author Akash Yadav */ +class CreateMissingMethodAction : BaseJavaCodeAction() { + override val id: String = "ide.editor.lsp.java.diagnostics.createMissingMethod" + override var label: String = "" + private val diagnosticCode = DiagnosticCode.MISSING_METHOD.id + + override val titleTextRes: Int = R.string.action_create_missing_method + + companion object { + private val log = LoggerFactory.getLogger(CreateMissingMethodAction::class.java) + } + + override fun prepare(data: ActionData) { + super.prepare(data) + + if ( + !visible || + !data.hasRequiredData(com.itsaky.androidide.lsp.models.DiagnosticItem::class.java) + ) { + markInvisible() + return + } + + val diagnostic = data[com.itsaky.androidide.lsp.models.DiagnosticItem::class.java]!! + if (diagnosticCode != diagnostic.code) { + markInvisible() + return + } + } + + override suspend fun execAction(data: ActionData): Any { + val diagnostic = data[com.itsaky.androidide.lsp.models.DiagnosticItem::class.java]!! + val compiler = + JavaCompilerProvider.forFile(data.requireFile()) ?: return Any() + val file = data.requirePath() + return compiler.compile(file).get { + CreateMissingMethod(file, findPosition(it, diagnostic.range.start)) + } + } + + override fun postExec( + data: ActionData, + result: Any, + ) { + if (result !is CreateMissingMethod) { + log.warn("Unable to create missing method") + return + } + + performCodeAction(data, result) + } +} diff --git a/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/actions/diagnostics/FieldToBlockAction.kt b/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/actions/diagnostics/FieldToBlockAction.kt index b9588f52d5..67670de638 100644 --- a/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/actions/diagnostics/FieldToBlockAction.kt +++ b/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/actions/diagnostics/FieldToBlockAction.kt @@ -64,7 +64,7 @@ class FieldToBlockAction : BaseJavaCodeAction() { override suspend fun execAction(data: ActionData): Any { val compiler = - JavaCompilerProvider.get(IProjectManager.getInstance().findModuleForFile(data.requireFile(), false) ?: return Any()) + JavaCompilerProvider.forFile(data.requireFile()) ?: return Any() val diagnostic = data[DiagnosticItem::class.java]!! val file = data.requirePath() diff --git a/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/actions/diagnostics/RemoveClassAction.kt b/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/actions/diagnostics/RemoveClassAction.kt index 221e5354e7..553fc9d82c 100644 --- a/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/actions/diagnostics/RemoveClassAction.kt +++ b/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/actions/diagnostics/RemoveClassAction.kt @@ -1,84 +1,84 @@ -/* - * This file is part of AndroidIDE. - * - * AndroidIDE is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * AndroidIDE is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with AndroidIDE. If not, see . - */ -package com.itsaky.androidide.lsp.java.actions.diagnostics - -import com.itsaky.androidide.actions.ActionData -import com.itsaky.androidide.actions.hasRequiredData -import com.itsaky.androidide.actions.markInvisible -import com.itsaky.androidide.actions.requireFile -import com.itsaky.androidide.actions.requirePath -import com.itsaky.androidide.lsp.java.JavaCompilerProvider -import com.itsaky.androidide.lsp.java.actions.BaseJavaCodeAction -import com.itsaky.androidide.lsp.java.models.DiagnosticCode -import com.itsaky.androidide.lsp.java.rewrite.RemoveClass -import com.itsaky.androidide.lsp.java.utils.CodeActionUtils.findPosition -import com.itsaky.androidide.projects.IProjectManager -import com.itsaky.androidide.resources.R -import org.slf4j.LoggerFactory - -/** @author Akash Yadav */ -class RemoveClassAction : BaseJavaCodeAction() { - - override val id: String = "ide.editor.lsp.java.diagnostics.removeClass" - override var label: String = "" - private val diagnosticCode = DiagnosticCode.UNUSED_CLASS.id - - override val titleTextRes: Int = R.string.action_remove_class - - companion object { - - private val log = LoggerFactory.getLogger(RemoveClassAction::class.java) - } - - override fun prepare(data: ActionData) { - super.prepare(data) - - if (!visible || !data.hasRequiredData( - com.itsaky.androidide.lsp.models.DiagnosticItem::class.java) - ) { - markInvisible() - return - } - - val diagnostic = data[com.itsaky.androidide.lsp.models.DiagnosticItem::class.java]!! - if (diagnosticCode != diagnostic.code) { - markInvisible() - return - } - } - - override suspend fun execAction(data: ActionData): Any { - val diagnostic = data[com.itsaky.androidide.lsp.models.DiagnosticItem::class.java]!! - val compiler = - JavaCompilerProvider.get( - IProjectManager.getInstance().findModuleForFile(data.requireFile(), false) ?: return Any()) - val file = data.requirePath() - - return compiler.compile(file).get { - RemoveClass(file, findPosition(it, diagnostic.range.start)) - } - } - - override fun postExec(data: ActionData, result: Any) { - if (result !is RemoveClass) { - log.warn("Unable to remove class") - return - } - - performCodeAction(data, result) - } -} +/* + * This file is part of AndroidIDE. + * + * AndroidIDE is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * AndroidIDE is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with AndroidIDE. If not, see . + */ +package com.itsaky.androidide.lsp.java.actions.diagnostics + +import com.itsaky.androidide.actions.ActionData +import com.itsaky.androidide.actions.hasRequiredData +import com.itsaky.androidide.actions.markInvisible +import com.itsaky.androidide.actions.requireFile +import com.itsaky.androidide.actions.requirePath +import com.itsaky.androidide.lsp.java.JavaCompilerProvider +import com.itsaky.androidide.lsp.java.actions.BaseJavaCodeAction +import com.itsaky.androidide.lsp.java.models.DiagnosticCode +import com.itsaky.androidide.lsp.java.rewrite.RemoveClass +import com.itsaky.androidide.lsp.java.utils.CodeActionUtils.findPosition +import com.itsaky.androidide.projects.IProjectManager +import com.itsaky.androidide.resources.R +import org.slf4j.LoggerFactory + +/** @author Akash Yadav */ +class RemoveClassAction : BaseJavaCodeAction() { + override val id: String = "ide.editor.lsp.java.diagnostics.removeClass" + override var label: String = "" + private val diagnosticCode = DiagnosticCode.UNUSED_CLASS.id + + override val titleTextRes: Int = R.string.action_remove_class + + companion object { + private val log = LoggerFactory.getLogger(RemoveClassAction::class.java) + } + + override fun prepare(data: ActionData) { + super.prepare(data) + + if (!visible || + !data.hasRequiredData(com.itsaky.androidide.lsp.models.DiagnosticItem::class.java) + ) { + markInvisible() + return + } + + val diagnostic = data[com.itsaky.androidide.lsp.models.DiagnosticItem::class.java]!! + if (diagnosticCode != diagnostic.code) { + markInvisible() + return + } + } + + override suspend fun execAction(data: ActionData): Any { + val diagnostic = data[com.itsaky.androidide.lsp.models.DiagnosticItem::class.java]!! + val compiler = + JavaCompilerProvider.forFile(data.requireFile()) ?: return Any() + val file = data.requirePath() + + return compiler.compile(file).get { + RemoveClass(file, findPosition(it, diagnostic.range.start)) + } + } + + override fun postExec( + data: ActionData, + result: Any, + ) { + if (result !is RemoveClass) { + log.warn("Unable to remove class") + return + } + + performCodeAction(data, result) + } +} diff --git a/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/actions/diagnostics/RemoveMethodAction.kt b/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/actions/diagnostics/RemoveMethodAction.kt index b0aa7ef5a1..50292d1c1c 100644 --- a/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/actions/diagnostics/RemoveMethodAction.kt +++ b/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/actions/diagnostics/RemoveMethodAction.kt @@ -1,89 +1,89 @@ -/* - * This file is part of AndroidIDE. - * - * AndroidIDE is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * AndroidIDE is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with AndroidIDE. If not, see . - */ -package com.itsaky.androidide.lsp.java.actions.diagnostics - -import com.itsaky.androidide.actions.ActionData -import com.itsaky.androidide.actions.hasRequiredData -import com.itsaky.androidide.actions.markInvisible -import com.itsaky.androidide.actions.requireFile -import com.itsaky.androidide.actions.requirePath -import com.itsaky.androidide.lsp.java.JavaCompilerProvider -import com.itsaky.androidide.lsp.java.actions.BaseJavaCodeAction -import com.itsaky.androidide.lsp.java.models.DiagnosticCode -import com.itsaky.androidide.lsp.java.rewrite.RemoveMethod -import com.itsaky.androidide.lsp.java.utils.CodeActionUtils.findMethod -import com.itsaky.androidide.projects.IProjectManager -import com.itsaky.androidide.resources.R -import org.slf4j.LoggerFactory - -/** @author Akash Yadav */ -class RemoveMethodAction : BaseJavaCodeAction() { - - override val id: String = "ide.editor.lsp.java.diagnostics.removeMethod" - override var label: String = "" - private val diagnosticCode = DiagnosticCode.UNUSED_METHOD.id - - override val titleTextRes: Int = R.string.action_remove_method - - companion object { - - private val log = LoggerFactory.getLogger(RemoveMethodAction::class.java) - } - - override fun prepare(data: ActionData) { - super.prepare(data) - - if (!visible || !data.hasRequiredData( - com.itsaky.androidide.lsp.models.DiagnosticItem::class.java) - ) { - markInvisible() - return - } - - val diagnostic = data[com.itsaky.androidide.lsp.models.DiagnosticItem::class.java]!! - if (diagnosticCode != diagnostic.code) { - markInvisible() - return - } - } - - override suspend fun execAction(data: ActionData): Any { - val diagnostic = data[com.itsaky.androidide.lsp.models.DiagnosticItem::class.java]!! - val compiler = - JavaCompilerProvider.get( - IProjectManager.getInstance().findModuleForFile(data.requireFile(), false) ?: return Any()) - val file = data.requirePath() - - return compiler.compile(file).get { - val unusedMethod = findMethod(it, diagnostic.range) - RemoveMethod( - unusedMethod.className, - unusedMethod.methodName, - unusedMethod.erasedParameterTypes - ) - } - } - - override fun postExec(data: ActionData, result: Any) { - if (result !is RemoveMethod) { - log.warn("Unable to remove method") - return - } - - performCodeAction(data, result) - } -} +/* + * This file is part of AndroidIDE. + * + * AndroidIDE is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * AndroidIDE is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with AndroidIDE. If not, see . + */ +package com.itsaky.androidide.lsp.java.actions.diagnostics + +import com.itsaky.androidide.actions.ActionData +import com.itsaky.androidide.actions.hasRequiredData +import com.itsaky.androidide.actions.markInvisible +import com.itsaky.androidide.actions.requireFile +import com.itsaky.androidide.actions.requirePath +import com.itsaky.androidide.lsp.java.JavaCompilerProvider +import com.itsaky.androidide.lsp.java.actions.BaseJavaCodeAction +import com.itsaky.androidide.lsp.java.models.DiagnosticCode +import com.itsaky.androidide.lsp.java.rewrite.RemoveMethod +import com.itsaky.androidide.lsp.java.utils.CodeActionUtils.findMethod +import com.itsaky.androidide.projects.IProjectManager +import com.itsaky.androidide.resources.R +import org.slf4j.LoggerFactory + +/** @author Akash Yadav */ +class RemoveMethodAction : BaseJavaCodeAction() { + override val id: String = "ide.editor.lsp.java.diagnostics.removeMethod" + override var label: String = "" + private val diagnosticCode = DiagnosticCode.UNUSED_METHOD.id + + override val titleTextRes: Int = R.string.action_remove_method + + companion object { + private val log = LoggerFactory.getLogger(RemoveMethodAction::class.java) + } + + override fun prepare(data: ActionData) { + super.prepare(data) + + if (!visible || + !data.hasRequiredData(com.itsaky.androidide.lsp.models.DiagnosticItem::class.java) + ) { + markInvisible() + return + } + + val diagnostic = data[com.itsaky.androidide.lsp.models.DiagnosticItem::class.java]!! + if (diagnosticCode != diagnostic.code) { + markInvisible() + return + } + } + + override suspend fun execAction(data: ActionData): Any { + val diagnostic = data[com.itsaky.androidide.lsp.models.DiagnosticItem::class.java]!! + val compiler = + JavaCompilerProvider.forFile(data.requireFile()) ?: return Any() + val file = data.requirePath() + + return compiler.compile(file).get { + val unusedMethod = findMethod(it, diagnostic.range) + RemoveMethod( + unusedMethod.className, + unusedMethod.methodName, + unusedMethod.erasedParameterTypes, + ) + } + } + + override fun postExec( + data: ActionData, + result: Any, + ) { + if (result !is RemoveMethod) { + log.warn("Unable to remove method") + return + } + + performCodeAction(data, result) + } +} diff --git a/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/actions/diagnostics/RemoveUnusedThrowsAction.kt b/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/actions/diagnostics/RemoveUnusedThrowsAction.kt index b1c3d35c33..ed0d0b3233 100644 --- a/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/actions/diagnostics/RemoveUnusedThrowsAction.kt +++ b/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/actions/diagnostics/RemoveUnusedThrowsAction.kt @@ -1,92 +1,92 @@ -/* - * This file is part of AndroidIDE. - * - * AndroidIDE is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * AndroidIDE is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with AndroidIDE. If not, see . - */ -package com.itsaky.androidide.lsp.java.actions.diagnostics - -import com.itsaky.androidide.actions.ActionData -import com.itsaky.androidide.actions.hasRequiredData -import com.itsaky.androidide.actions.markInvisible -import com.itsaky.androidide.actions.requireFile -import com.itsaky.androidide.actions.requirePath -import com.itsaky.androidide.lsp.java.JavaCompilerProvider -import com.itsaky.androidide.lsp.java.actions.BaseJavaCodeAction -import com.itsaky.androidide.lsp.java.models.DiagnosticCode -import com.itsaky.androidide.lsp.java.rewrite.RemoveException -import com.itsaky.androidide.lsp.java.utils.CodeActionUtils -import com.itsaky.androidide.projects.IProjectManager -import com.itsaky.androidide.resources.R -import org.slf4j.LoggerFactory - -/** @author Akash Yadav */ -class RemoveUnusedThrowsAction : BaseJavaCodeAction() { - - override val id: String = "ide.editor.lsp.java.diagnostics.removeUnusedThrows" - override var label: String = "" - private val diagnosticCode = DiagnosticCode.UNUSED_THROWS.id - - override val titleTextRes: Int = R.string.action_remove_unused_throws - - companion object { - - private val log = LoggerFactory.getLogger(RemoveUnusedThrowsAction::class.java) - } - - override fun prepare(data: ActionData) { - super.prepare(data) - - if ( - !visible || - !data.hasRequiredData(com.itsaky.androidide.lsp.models.DiagnosticItem::class.java) - ) { - markInvisible() - return - } - - val diagnostic = data[com.itsaky.androidide.lsp.models.DiagnosticItem::class.java]!! - if (diagnosticCode != diagnostic.code) { - markInvisible() - return - } - } - - override suspend fun execAction(data: ActionData): Any { - val d = data[com.itsaky.androidide.lsp.models.DiagnosticItem::class.java]!! - val compiler = - JavaCompilerProvider.get( - IProjectManager.getInstance().findModuleForFile(data.requireFile(), false) ?: return Any()) - val file = data.requirePath() - return compiler.compile(file).get { task -> - val notThrown = CodeActionUtils.extractNotThrownExceptionName(d.message) - val methodWithExtraThrow = CodeActionUtils.findMethod(task, d.range) - - return@get RemoveException( - methodWithExtraThrow.className, - methodWithExtraThrow.methodName, - methodWithExtraThrow.erasedParameterTypes, - notThrown - ) - } - } - - override fun postExec(data: ActionData, result: Any) { - if (result !is RemoveException) { - log.warn("Unable to remove unused throws") - return - } - - performCodeAction(data, result) - } -} +/* + * This file is part of AndroidIDE. + * + * AndroidIDE is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * AndroidIDE is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with AndroidIDE. If not, see . + */ +package com.itsaky.androidide.lsp.java.actions.diagnostics + +import com.itsaky.androidide.actions.ActionData +import com.itsaky.androidide.actions.hasRequiredData +import com.itsaky.androidide.actions.markInvisible +import com.itsaky.androidide.actions.requireFile +import com.itsaky.androidide.actions.requirePath +import com.itsaky.androidide.lsp.java.JavaCompilerProvider +import com.itsaky.androidide.lsp.java.actions.BaseJavaCodeAction +import com.itsaky.androidide.lsp.java.models.DiagnosticCode +import com.itsaky.androidide.lsp.java.rewrite.RemoveException +import com.itsaky.androidide.lsp.java.utils.CodeActionUtils +import com.itsaky.androidide.projects.IProjectManager +import com.itsaky.androidide.resources.R +import org.slf4j.LoggerFactory + +/** @author Akash Yadav */ +class RemoveUnusedThrowsAction : BaseJavaCodeAction() { + override val id: String = "ide.editor.lsp.java.diagnostics.removeUnusedThrows" + override var label: String = "" + private val diagnosticCode = DiagnosticCode.UNUSED_THROWS.id + + override val titleTextRes: Int = R.string.action_remove_unused_throws + + companion object { + private val log = LoggerFactory.getLogger(RemoveUnusedThrowsAction::class.java) + } + + override fun prepare(data: ActionData) { + super.prepare(data) + + if ( + !visible || + !data.hasRequiredData(com.itsaky.androidide.lsp.models.DiagnosticItem::class.java) + ) { + markInvisible() + return + } + + val diagnostic = data[com.itsaky.androidide.lsp.models.DiagnosticItem::class.java]!! + if (diagnosticCode != diagnostic.code) { + markInvisible() + return + } + } + + override suspend fun execAction(data: ActionData): Any { + val d = data[com.itsaky.androidide.lsp.models.DiagnosticItem::class.java]!! + val compiler = + JavaCompilerProvider.forFile(data.requireFile()) ?: return Any() + val file = data.requirePath() + return compiler.compile(file).get { task -> + val notThrown = CodeActionUtils.extractNotThrownExceptionName(d.message) + val methodWithExtraThrow = CodeActionUtils.findMethod(task, d.range) + + return@get RemoveException( + methodWithExtraThrow.className, + methodWithExtraThrow.methodName, + methodWithExtraThrow.erasedParameterTypes, + notThrown, + ) + } + } + + override fun postExec( + data: ActionData, + result: Any, + ) { + if (result !is RemoveException) { + log.warn("Unable to remove unused throws") + return + } + + performCodeAction(data, result) + } +} diff --git a/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/actions/diagnostics/SuppressUncheckedWarningAction.kt b/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/actions/diagnostics/SuppressUncheckedWarningAction.kt index b831e43def..81ddc49e83 100644 --- a/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/actions/diagnostics/SuppressUncheckedWarningAction.kt +++ b/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/actions/diagnostics/SuppressUncheckedWarningAction.kt @@ -1,88 +1,88 @@ -/* - * This file is part of AndroidIDE. - * - * AndroidIDE is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * AndroidIDE is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with AndroidIDE. If not, see . - */ -package com.itsaky.androidide.lsp.java.actions.diagnostics - -import com.itsaky.androidide.actions.ActionData -import com.itsaky.androidide.actions.hasRequiredData -import com.itsaky.androidide.actions.markInvisible -import com.itsaky.androidide.actions.requireFile -import com.itsaky.androidide.actions.requirePath -import com.itsaky.androidide.lsp.java.JavaCompilerProvider -import com.itsaky.androidide.lsp.java.actions.BaseJavaCodeAction -import com.itsaky.androidide.lsp.java.models.DiagnosticCode -import com.itsaky.androidide.lsp.java.rewrite.AddSuppressWarningAnnotation -import com.itsaky.androidide.lsp.java.utils.CodeActionUtils -import com.itsaky.androidide.projects.IProjectManager -import com.itsaky.androidide.resources.R -import org.slf4j.LoggerFactory - -/** @author Akash Yadav */ -class SuppressUncheckedWarningAction : BaseJavaCodeAction() { - - override val id = "ide.editor.lsp.java.diagnostics.suppressUncheckedWarning" - override var label: String = "" - private val diagnosticCode = DiagnosticCode.UNCHECKED.id - - override val titleTextRes: Int = R.string.action_suppress_unchecked_warning - - companion object { - - private val log = LoggerFactory.getLogger(SuppressUncheckedWarningAction::class.java) - } - - override fun prepare(data: ActionData) { - super.prepare(data) - - if (!visible || !data.hasRequiredData( - com.itsaky.androidide.lsp.models.DiagnosticItem::class.java) - ) { - markInvisible() - return - } - - val diagnostic = data[com.itsaky.androidide.lsp.models.DiagnosticItem::class.java]!! - if (diagnosticCode != diagnostic.code) { - markInvisible() - return - } - } - - override suspend fun execAction(data: ActionData): Any { - val diagnostic = data[com.itsaky.androidide.lsp.models.DiagnosticItem::class.java]!! - val compiler = - JavaCompilerProvider.get( - IProjectManager.getInstance().findModuleForFile(data.requireFile(), false) ?: return Any()) - val file = data.requirePath() - return compiler.compile(file).get { task -> - val warnedMethod = CodeActionUtils.findMethod(task, diagnostic.range) - return@get AddSuppressWarningAnnotation( - warnedMethod.className, - warnedMethod.methodName, - warnedMethod.erasedParameterTypes - ) - } - } - - override fun postExec(data: ActionData, result: Any) { - if (result !is AddSuppressWarningAnnotation) { - log.warn("Unable to suppress 'unchecked' warning") - return - } - - performCodeAction(data, result) - } -} +/* + * This file is part of AndroidIDE. + * + * AndroidIDE is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * AndroidIDE is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with AndroidIDE. If not, see . + */ +package com.itsaky.androidide.lsp.java.actions.diagnostics + +import com.itsaky.androidide.actions.ActionData +import com.itsaky.androidide.actions.hasRequiredData +import com.itsaky.androidide.actions.markInvisible +import com.itsaky.androidide.actions.requireFile +import com.itsaky.androidide.actions.requirePath +import com.itsaky.androidide.lsp.java.JavaCompilerProvider +import com.itsaky.androidide.lsp.java.actions.BaseJavaCodeAction +import com.itsaky.androidide.lsp.java.models.DiagnosticCode +import com.itsaky.androidide.lsp.java.rewrite.AddSuppressWarningAnnotation +import com.itsaky.androidide.lsp.java.utils.CodeActionUtils +import com.itsaky.androidide.projects.IProjectManager +import com.itsaky.androidide.resources.R +import org.slf4j.LoggerFactory + +/** @author Akash Yadav */ +class SuppressUncheckedWarningAction : BaseJavaCodeAction() { + override val id = "ide.editor.lsp.java.diagnostics.suppressUncheckedWarning" + override var label: String = "" + private val diagnosticCode = DiagnosticCode.UNCHECKED.id + + override val titleTextRes: Int = R.string.action_suppress_unchecked_warning + + companion object { + private val log = LoggerFactory.getLogger(SuppressUncheckedWarningAction::class.java) + } + + override fun prepare(data: ActionData) { + super.prepare(data) + + if (!visible || + !data.hasRequiredData(com.itsaky.androidide.lsp.models.DiagnosticItem::class.java) + ) { + markInvisible() + return + } + + val diagnostic = data[com.itsaky.androidide.lsp.models.DiagnosticItem::class.java]!! + if (diagnosticCode != diagnostic.code) { + markInvisible() + return + } + } + + override suspend fun execAction(data: ActionData): Any { + val diagnostic = data[com.itsaky.androidide.lsp.models.DiagnosticItem::class.java]!! + val compiler = + JavaCompilerProvider.forFile(data.requireFile()) ?: return Any() + val file = data.requirePath() + return compiler.compile(file).get { task -> + val warnedMethod = CodeActionUtils.findMethod(task, diagnostic.range) + return@get AddSuppressWarningAnnotation( + warnedMethod.className, + warnedMethod.methodName, + warnedMethod.erasedParameterTypes, + ) + } + } + + override fun postExec( + data: ActionData, + result: Any, + ) { + if (result !is AddSuppressWarningAnnotation) { + log.warn("Unable to suppress 'unchecked' warning") + return + } + + performCodeAction(data, result) + } +} diff --git a/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/actions/diagnostics/VariableToStatementAction.kt b/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/actions/diagnostics/VariableToStatementAction.kt index d8288c81da..bb8292e03a 100644 --- a/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/actions/diagnostics/VariableToStatementAction.kt +++ b/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/actions/diagnostics/VariableToStatementAction.kt @@ -67,7 +67,7 @@ class VariableToStatementAction : BaseJavaCodeAction() { override suspend fun execAction(data: ActionData): Any { val diagnostic = data[com.itsaky.androidide.lsp.models.DiagnosticItem::class.java]!! val compiler = - JavaCompilerProvider.get(IProjectManager.getInstance().findModuleForFile(data.requireFile(), false) ?: return Any()) + JavaCompilerProvider.forFile(data.requireFile()) ?: return Any() val path = data.requirePath() return compiler.compile(path).get { diff --git a/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/actions/generators/GenerateConstructorAction.kt b/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/actions/generators/GenerateConstructorAction.kt index 91566a4570..3d251e8c56 100644 --- a/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/actions/generators/GenerateConstructorAction.kt +++ b/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/actions/generators/GenerateConstructorAction.kt @@ -98,9 +98,7 @@ class GenerateConstructorAction : FieldBasedAction() { selected: MutableSet, ) { val compiler = - JavaCompilerProvider.get( - IProjectManager.getInstance().findModuleForFile(data.requireFile(), false) ?: return, - ) + JavaCompilerProvider.forFile(data.requireFile()) ?: return val range = data[Range::class.java]!! val file = data.requirePath() diff --git a/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/actions/generators/GenerateMissingConstructorAction.kt b/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/actions/generators/GenerateMissingConstructorAction.kt index e4fb0a058e..4fea828ef5 100644 --- a/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/actions/generators/GenerateMissingConstructorAction.kt +++ b/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/actions/generators/GenerateMissingConstructorAction.kt @@ -1,87 +1,87 @@ -/* - * This file is part of AndroidIDE. - * - * AndroidIDE is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * AndroidIDE is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with AndroidIDE. If not, see . - */ -package com.itsaky.androidide.lsp.java.actions.generators - -import com.itsaky.androidide.actions.ActionData -import com.itsaky.androidide.actions.hasRequiredData -import com.itsaky.androidide.actions.markInvisible -import com.itsaky.androidide.actions.requireFile -import com.itsaky.androidide.actions.requirePath -import com.itsaky.androidide.idetooltips.TooltipTag -import com.itsaky.androidide.lsp.java.JavaCompilerProvider -import com.itsaky.androidide.lsp.java.actions.BaseJavaCodeAction -import com.itsaky.androidide.lsp.java.models.DiagnosticCode -import com.itsaky.androidide.lsp.java.rewrite.GenerateRecordConstructor -import com.itsaky.androidide.lsp.java.utils.CodeActionUtils -import com.itsaky.androidide.projects.IProjectManager -import com.itsaky.androidide.resources.R -import org.slf4j.LoggerFactory - -/** @author Akash Yadav */ -class GenerateMissingConstructorAction : BaseJavaCodeAction() { - - override val id = "ide.editor.lsp.java.generator.missingConstructor" - override var label: String = "" - private val diagnosticCode = DiagnosticCode.MISSING_CONSTRUCTOR.id - override val titleTextRes: Int = R.string.action_generate_missing_constructor - override var tooltipTag: String = TooltipTag.EDITOR_CODE_ACTIONS_GEN_CONSTRUCTOR - - companion object { - - private val log = LoggerFactory.getLogger(GenerateMissingConstructorAction::class.java) - } - - override fun prepare(data: ActionData) { - super.prepare(data) - - if ( - !visible || - !data.hasRequiredData(com.itsaky.androidide.lsp.models.DiagnosticItem::class.java) - ) { - markInvisible() - return - } - - val diagnostic = data[com.itsaky.androidide.lsp.models.DiagnosticItem::class.java]!! - if (diagnosticCode != diagnostic.code) { - markInvisible() - return - } - } - - override suspend fun execAction(data: ActionData): Any { - val diagnostic = data[com.itsaky.androidide.lsp.models.DiagnosticItem::class.java]!! - val compiler = - JavaCompilerProvider.get( - IProjectManager.getInstance().findModuleForFile(data.requireFile(), false) ?: return Any()) - val file = data.requirePath() - return compiler.compile(file).get { task -> - val needsConstructor = - CodeActionUtils.findClassNeedingConstructor(task, diagnostic.range) ?: return@get false - return@get GenerateRecordConstructor(needsConstructor) - } - } - - override fun postExec(data: ActionData, result: Any) { - if (result !is GenerateRecordConstructor) { - log.warn("Unable to generate constructor") - return - } - - performCodeAction(data, result) - } -} +/* + * This file is part of AndroidIDE. + * + * AndroidIDE is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * AndroidIDE is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with AndroidIDE. If not, see . + */ +package com.itsaky.androidide.lsp.java.actions.generators + +import com.itsaky.androidide.actions.ActionData +import com.itsaky.androidide.actions.hasRequiredData +import com.itsaky.androidide.actions.markInvisible +import com.itsaky.androidide.actions.requireFile +import com.itsaky.androidide.actions.requirePath +import com.itsaky.androidide.idetooltips.TooltipTag +import com.itsaky.androidide.lsp.java.JavaCompilerProvider +import com.itsaky.androidide.lsp.java.actions.BaseJavaCodeAction +import com.itsaky.androidide.lsp.java.models.DiagnosticCode +import com.itsaky.androidide.lsp.java.rewrite.GenerateRecordConstructor +import com.itsaky.androidide.lsp.java.utils.CodeActionUtils +import com.itsaky.androidide.projects.IProjectManager +import com.itsaky.androidide.resources.R +import org.slf4j.LoggerFactory + +/** @author Akash Yadav */ +class GenerateMissingConstructorAction : BaseJavaCodeAction() { + override val id = "ide.editor.lsp.java.generator.missingConstructor" + override var label: String = "" + private val diagnosticCode = DiagnosticCode.MISSING_CONSTRUCTOR.id + override val titleTextRes: Int = R.string.action_generate_missing_constructor + override var tooltipTag: String = TooltipTag.EDITOR_CODE_ACTIONS_GEN_CONSTRUCTOR + + companion object { + private val log = LoggerFactory.getLogger(GenerateMissingConstructorAction::class.java) + } + + override fun prepare(data: ActionData) { + super.prepare(data) + + if ( + !visible || + !data.hasRequiredData(com.itsaky.androidide.lsp.models.DiagnosticItem::class.java) + ) { + markInvisible() + return + } + + val diagnostic = data[com.itsaky.androidide.lsp.models.DiagnosticItem::class.java]!! + if (diagnosticCode != diagnostic.code) { + markInvisible() + return + } + } + + override suspend fun execAction(data: ActionData): Any { + val diagnostic = data[com.itsaky.androidide.lsp.models.DiagnosticItem::class.java]!! + val compiler = + JavaCompilerProvider.forFile(data.requireFile()) ?: return Any() + val file = data.requirePath() + return compiler.compile(file).get { task -> + val needsConstructor = + CodeActionUtils.findClassNeedingConstructor(task, diagnostic.range) ?: return@get false + return@get GenerateRecordConstructor(needsConstructor) + } + } + + override fun postExec( + data: ActionData, + result: Any, + ) { + if (result !is GenerateRecordConstructor) { + log.warn("Unable to generate constructor") + return + } + + performCodeAction(data, result) + } +} diff --git a/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/actions/generators/GenerateSettersAndGettersAction.kt b/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/actions/generators/GenerateSettersAndGettersAction.kt index a06523af87..6595e8fb21 100644 --- a/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/actions/generators/GenerateSettersAndGettersAction.kt +++ b/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/actions/generators/GenerateSettersAndGettersAction.kt @@ -98,9 +98,7 @@ class GenerateSettersAndGettersAction : FieldBasedAction() { names: MutableSet, ) { val compiler = - JavaCompilerProvider.get( - IProjectManager.getInstance().findModuleForFile(data.requireFile(), false) ?: return, - ) + JavaCompilerProvider.forFile(data.requireFile()) ?: return val range = data[com.itsaky.androidide.models.Range::class.java]!! val file = data.requirePath() diff --git a/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/actions/generators/GenerateToStringMethodAction.kt b/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/actions/generators/GenerateToStringMethodAction.kt index 3f90379f99..858b9ea3ce 100644 --- a/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/actions/generators/GenerateToStringMethodAction.kt +++ b/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/actions/generators/GenerateToStringMethodAction.kt @@ -91,9 +91,7 @@ class GenerateToStringMethodAction : FieldBasedAction() { selected: MutableSet, ) { val compiler = - JavaCompilerProvider.get( - IProjectManager.getInstance().findModuleForFile(data.requireFile(), false) ?: return, - ) + JavaCompilerProvider.forFile(data.requireFile()) ?: return val range = data[com.itsaky.androidide.models.Range::class.java]!! val file = data.requirePath() diff --git a/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/actions/generators/OverrideSuperclassMethodsAction.kt b/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/actions/generators/OverrideSuperclassMethodsAction.kt index 3229a89f09..3f5cee2144 100644 --- a/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/actions/generators/OverrideSuperclassMethodsAction.kt +++ b/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/actions/generators/OverrideSuperclassMethodsAction.kt @@ -97,10 +97,7 @@ class OverrideSuperclassMethodsAction : BaseJavaCodeAction() { override suspend fun execAction(data: ActionData): Any { val range = data[com.itsaky.androidide.models.Range::class.java]!! val compiler = - JavaCompilerProvider.get( - IProjectManager.getInstance().findModuleForFile(data.requireFile(), false) - ?: return Any(), - ) + JavaCompilerProvider.forFile(data.requireFile()) ?: return Any() val file = data.requirePath() return compiler.compile(file).get { task -> @@ -238,9 +235,7 @@ class OverrideSuperclassMethodsAction : BaseJavaCodeAction() { checkedMethods: MutableList, ) { val compiler = - JavaCompilerProvider.get( - IProjectManager.getInstance().findModuleForFile(data.requireFile(), false) ?: return, - ) + JavaCompilerProvider.forFile(data.requireFile()) ?: return val file = data.requirePath() compiler.compile(file).run { task -> @@ -320,9 +315,7 @@ class OverrideSuperclassMethodsAction : BaseJavaCodeAction() { position: Position, ) { val compiler = - JavaCompilerProvider.get( - IProjectManager.getInstance().findModuleForFile(data.requireFile(), false) ?: return, - ) + JavaCompilerProvider.forFile(data.requireFile()) ?: return val editor = data[CodeEditor::class.java]!! val file = data.requirePath() val text = editor.text diff --git a/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/compiler/ClasspathTypeLookup.kt b/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/compiler/ClasspathTypeLookup.kt index 76fa397856..62e51ea04c 100644 --- a/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/compiler/ClasspathTypeLookup.kt +++ b/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/compiler/ClasspathTypeLookup.kt @@ -2,6 +2,7 @@ package com.itsaky.androidide.lsp.java.compiler import com.itsaky.androidide.projects.ProjectManagerImpl import com.itsaky.androidide.projects.api.ModuleProject +import com.itsaky.androidide.projects.models.ArtifactScope import org.appdevforall.codeonthego.indexing.jvm.JvmSymbol import org.appdevforall.codeonthego.indexing.jvm.JvmVisibility import org.appdevforall.codeonthego.indexing.jvm.ModuleClasspathLookup @@ -137,16 +138,18 @@ class ClasspathTypeLookup internal constructor( companion object { /** * Creates the lookup for [module] over the indexes registered with the project manager, and the - * boot classes [bootClasses] returns. A `null` [module] has no source or classpath classes. + * boot classes [bootClasses] returns. Source classes are [scope]'s. A + * `null` [module] has no source or classpath classes. */ @JvmStatic fun forModule( module: ModuleProject?, + scope: ArtifactScope, bootClasses: () -> Collection, ) = ClasspathTypeLookup( sourceClasses = { module - ?.compileJavaSourceClasses + ?.javaSourceClasses(scope) ?.allSources() ?.map { it.qualifiedName } .orEmpty() diff --git a/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/compiler/CompileBatch.java b/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/compiler/CompileBatch.java index c0b8022757..9a872dbb90 100644 --- a/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/compiler/CompileBatch.java +++ b/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/compiler/CompileBatch.java @@ -141,7 +141,7 @@ Set needsAdditionalSources() { continue; } String packageName = packageName(err); - ClassTrie.Node node = parent.getModule().compileJavaSourceClasses.findNode(packageName); + ClassTrie.Node node = parent.getSourceClasses().findNode(packageName); if (node != null && node.isClass() && node instanceof SourceClassTrie.SourceNode) { addFiles.add(((SourceClassTrie.SourceNode) node).getFile()); } diff --git a/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/compiler/JavaCompilerService.java b/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/compiler/JavaCompilerService.java index 447381f678..fdc999fb18 100644 --- a/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/compiler/JavaCompilerService.java +++ b/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/compiler/JavaCompilerService.java @@ -37,6 +37,7 @@ import com.itsaky.androidide.projects.FileManager; import com.itsaky.androidide.projects.api.AndroidModule; import com.itsaky.androidide.projects.api.ModuleProject; +import com.itsaky.androidide.projects.models.ArtifactScope; import com.itsaky.androidide.projects.util.BootClasspathProvider; import com.itsaky.androidide.projects.util.StringSearch; import com.itsaky.androidide.utils.Cache; @@ -83,12 +84,15 @@ public class JavaCompilerService implements CompilerProvider { protected final SynchronizedTask synchronizedTask = new SynchronizedTask(); protected final SourceFileManager fileManager; protected final ModuleProject module; + @NonNull + protected final ArtifactScope scope; private final ClasspathTypeLookup types; public ReusableCompiler compiler = new JCReusableCompiler(); protected Set bootClasspathClasses = BootClasspathProvider.getTopLevelClasses( Collections.singleton(Environment.ANDROID_JAR.getAbsolutePath())); private CompileBatch cachedCompile; private int changeDelta = 0; + private volatile boolean stale = false; private Position lastReparsePosition = Position.NONE; private Position newCursorPosition = Position.NONE; @@ -96,14 +100,20 @@ public class JavaCompilerService implements CompilerProvider { // The module project must not be null // It is marked as nullable just for some special cases like tests public JavaCompilerService(@Nullable ModuleProject module) { + this(module, ArtifactScope.Main.INSTANCE); + } + + /** A compiler for {@code module}'s {@code scope} sources. */ + public JavaCompilerService(@Nullable ModuleProject module, @NonNull ArtifactScope scope) { this.module = module; + this.scope = scope; if (module == null) { this.fileManager = SourceFileManager.NO_MODULE; } else { - this.fileManager = SourceFileManager.forModule(module); + this.fileManager = SourceFileManager.forModule(module, scope); this.bootClasspathClasses = Collections.unmodifiableSet(getBootclasspathClasses()); } - this.types = ClasspathTypeLookup.forModule(module, () -> this.bootClasspathClasses); + this.types = ClasspathTypeLookup.forModule(module, scope, () -> this.bootClasspathClasses); } @VisibleForTesting @@ -112,7 +122,17 @@ public JavaCompilerService(@Nullable ModuleProject module) { SourceFileManager fileManager, Set bootClasspathClasses, ClasspathTypeLookup types) { + this(module, ArtifactScope.Main.INSTANCE, fileManager, bootClasspathClasses, types); + } + + private JavaCompilerService( + @Nullable ModuleProject module, + @NonNull ArtifactScope scope, + SourceFileManager fileManager, + Set bootClasspathClasses, + ClasspathTypeLookup types) { this.module = module; + this.scope = scope; this.fileManager = fileManager; this.bootClasspathClasses = bootClasspathClasses; this.types = types; @@ -143,7 +163,7 @@ public SynchronizedTask compile(final CompilationRequest request) { public JavaCompilerService copy() { final JavaCompilerService compiler = new JavaCompilerService( - this.module, this.fileManager, this.bootClasspathClasses, this.types); + this.module, this.scope, this.fileManager, this.bootClasspathClasses, this.types); compiler.cachedCompile = null; compiler.newCursorPosition = Position.NONE; compiler.lastReparsePosition = Position.NONE; @@ -186,7 +206,7 @@ public List findImportableQualifiedNames(String simpleName, String impor @Override public Path[] findMemberReferences(String className, String memberName) { List candidates = new ArrayList<>(); - List sourceNodes = module != null ? module.compileJavaSourceClasses.allSources() : Collections.emptyList(); + List sourceNodes = module != null ? getSourceClasses().allSources() : Collections.emptyList(); for (SourceClassTrie.SourceNode node : sourceNodes) { final Path path = node.getFile(); if (containsWord(path, memberName)) { @@ -207,7 +227,7 @@ public Path findTypeDeclaration(String className) { // optimization. String packageName = Extractors.packageName(className); String simpleName = Extractors.simpleName(className); - List classes = module != null ? module.listClassesFromSourceDirs(packageName) : Collections.emptyList(); + List classes = module != null ? module.listClassesFromSourceDirs(packageName, scope) : Collections.emptyList(); for (SourceClassTrie.SourceNode node : classes) { final Path path = node.getFile(); if (containsWord(path, simpleName) && containsType(path, className)) { @@ -232,7 +252,7 @@ public Path[] findTypeReferences(String className) { String packageName = Extractors.packageName(className); String simpleName = Extractors.simpleName(className); List candidates = new ArrayList<>(); - List sourceNodes = module != null ? module.compileJavaSourceClasses.allSources() : Collections.emptyList(); + List sourceNodes = module != null ? getSourceClasses().allSources() : Collections.emptyList(); for (SourceClassTrie.SourceNode node : sourceNodes) { final Path path = node.getFile(); if (containsWord(path, packageName) @@ -249,10 +269,28 @@ public ModuleProject getModule() { return module; } + /** The scope this compiler compiles. */ + @NonNull + public ArtifactScope getScope() { + return scope; + } + + /** The Java source classes this compiler sees: main's, or main's plus its test scope's. Requires a module. */ + public SourceClassTrie getSourceClasses() { + return module.javaSourceClasses(scope); + } + public SynchronizedTask getSynchronizedTask() { return synchronizedTask; } + /** + * Makes the next request recompile. The cache only checks the requested files' timestamps, so it cannot see an edit to a source it merely reads, such as a main source a test reads. Only sets a flag: callers run per keystroke and must not wait on a compile in progress. + */ + public void invalidateCompile() { + stale = true; + } + public void onDocumentChange(@NonNull DocumentChangeEvent event) { this.changeDelta += event.getChangeDelta(); this.newCursorPosition = event.getChangeRange().getEnd(); @@ -275,6 +313,12 @@ public ParseTask parse(Path file) { return new ParseTask(parser.task, parser.root); } + /** Whether the next request recompiles regardless of the cache. */ + @VisibleForTesting + boolean isStale() { + return stale; + } + @Nullable private Pair binarySearchCurrentMethod( @NonNull final List> positions, final long cursor) { @@ -301,7 +345,11 @@ private Pair binarySearchCurrentMethod( private SynchronizedTask compileBatch(CompilationRequest request) { synchronizedTask.post( () -> { - if (needsCompilation(request.sources)) { + if (stale) { + // Cleared first, so an invalidation during this compile marks it stale again. + stale = false; + recompile(request); + } else if (needsCompilation(request.sources)) { reparseOrRecompile(request); } else { LOG.info("...using cached compile"); @@ -435,7 +483,7 @@ private boolean needsRecompilation(final CompilationRequest request) { } private String packageNameOrEmpty(Path file) { - return module != null ? module.packageNameOrEmpty(file) : ""; + return module != null ? module.packageNameOrEmpty(file, scope) : ""; } private CompileBatch performCompilation(CompilationRequest request) { diff --git a/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/compiler/SourceFileManager.java b/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/compiler/SourceFileManager.java index a688f275e6..09565526c5 100644 --- a/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/compiler/SourceFileManager.java +++ b/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/compiler/SourceFileManager.java @@ -27,6 +27,7 @@ import com.itsaky.androidide.projects.api.AndroidModule; import com.itsaky.androidide.projects.api.ModuleProject; import com.itsaky.androidide.projects.models.AndroidProjectExtsKt; +import com.itsaky.androidide.projects.models.ArtifactScope; import com.itsaky.androidide.projects.util.StringSearch; import com.itsaky.androidide.utils.ClassTrie; import com.itsaky.androidide.utils.Environment; @@ -63,12 +64,13 @@ public class SourceFileManager extends ForwardingJavaFileManager cachedFileManagers = new ConcurrentHashMap<>(); + // Keyed by scope as well as module: a shared entry would give main code the test classpath, or tests main's. + private static final Map cachedFileManagers = new ConcurrentHashMap<>(); static { // Initialize LOG first to prevent NPE LOG = LoggerFactory.getLogger(SourceFileManager.class); - NO_MODULE = new SourceFileManager(null); + NO_MODULE = new SourceFileManager(null, null); } public static void clearCache() { @@ -84,8 +86,13 @@ public static void clearCache() { } public static SourceFileManager forModule(@NonNull ModuleProject project) { + return forModule(project, ArtifactScope.Main.INSTANCE); + } + + /** The file manager for {@code project}'s {@code scope} sources. */ + public static SourceFileManager forModule(@NonNull ModuleProject project, @NonNull ArtifactScope scope) { Objects.requireNonNull(project); - return cachedFileManagers.computeIfAbsent(project, SourceFileManager::createForModule); + return cachedFileManagers.computeIfAbsent(new Key(project, scope), SourceFileManager::createForModule); } /* Mirrors JavacTool.getStandardFileManager, plus the shared jar package provider. It must be in the context before the file manager is built, because the classpath archive containers are created in the constructor and read the provider only once. */ @@ -99,16 +106,19 @@ static JavacFileManager createDelegateFileManager() { return new JavacFileManager(context, true, StandardCharsets.UTF_8); } - private static SourceFileManager createForModule(@NonNull ModuleProject project) { - LOG.info("Creating source file manager instance for module: {}", project); - return new SourceFileManager(project); + private static SourceFileManager createForModule(@NonNull Key key) { + LOG.info("Creating source file manager instance for module: {}, test scope: {}", key.module(), key.scope()); + return new SourceFileManager(key.module(), key.scope()); } private final ModuleProject module; - private SourceFileManager(final ModuleProject module) { + private final ArtifactScope scope; + + private SourceFileManager(final ModuleProject module, final ArtifactScope scope) { super(createDelegateFileManager()); this.module = module; + this.scope = scope; AndroidFsProviderImpl.INSTANCE.init(); @@ -120,7 +130,8 @@ private SourceFileManager(final ModuleProject module) { System.setProperty(JavacConfigProvider.PROP_ANDROIDIDE_JAVA_HOME, Environment.JAVA_HOME.getAbsolutePath()); - setLocationLogError(StandardLocation.SOURCE_PATH, module.getCompileSourceDirectories()); + final Set sourcePath = module.getCompileSourceDirectories(scope); + setLocationLogError(StandardLocation.SOURCE_PATH, sourcePath); setLocationLogError(StandardLocation.CLASS_PATH, configureClasspaths(module)); listLocations(EnumSet.of(StandardLocation.CLASS_PATH, StandardLocation.PLATFORM_CLASS_PATH)); } @@ -129,7 +140,7 @@ private SourceFileManager(final ModuleProject module) { public boolean contains(Location location, FileObject file) throws IOException { if (location == StandardLocation.SOURCE_PATH) { SourceFileObject source = (SourceFileObject) file; - return module.compileJavaSourceClasses.findSource(source.path) != null; + return module.javaSourceClasses(scope).findSource(source.path) != null; } else { return super.contains(location, file); } @@ -150,7 +161,7 @@ public JavaFileObject getJavaFileForInput( if (location == StandardLocation.SOURCE_PATH) { String packageName = StringSearch.mostName(className); String simpleClassName = StringSearch.lastName(className); - List classes = module != null ? module.listClassesFromSourceDirs(packageName) : emptyList(); + List classes = module != null ? module.listClassesFromSourceDirs(packageName, scope) : emptyList(); for (SourceClassTrie.SourceNode node : classes) { final Path path = node.getFile(); if (path.getFileName().toString().equals(simpleClassName + kind.extension)) { @@ -194,7 +205,7 @@ public Iterable list( return emptyList(); } - final ClassTrie.Node node = module.compileJavaSourceClasses.findNode(packageName); + final ClassTrie.Node node = module.javaSourceClasses(scope).findNode(packageName); if (node == null || node.isClass()) { return emptyList(); } @@ -248,7 +259,7 @@ private Set configureClasspaths(final ModuleProject module) { setLocationLogError(StandardLocation.PLATFORM_CLASS_PATH, AndroidProjectExtsKt.getBootClassPaths(androidModule)); } - return module.getCompileClasspaths(); + return module.getCompileClasspaths(scope, false); } private void listLocations(final EnumSet locations) { @@ -263,11 +274,13 @@ private void listLocations(final EnumSet locations) { } private String packageNameOrEmpty(Path file) { - return this.module != null ? module.packageNameOrEmpty(file) : ""; + return this.module != null ? module.packageNameOrEmpty(file, scope) : ""; } private String removeExtension(String fileName) { int lastDot = fileName.lastIndexOf("."); return (lastDot == -1 ? fileName : fileName.substring(0, lastDot)); } + + private record Key(ModuleProject module, ArtifactScope scope) {} } diff --git a/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/edits/AdvancedJavaEditHandler.kt b/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/edits/AdvancedJavaEditHandler.kt index 387d546cb4..7de362b795 100644 --- a/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/edits/AdvancedJavaEditHandler.kt +++ b/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/edits/AdvancedJavaEditHandler.kt @@ -30,19 +30,18 @@ import java.nio.file.Path * * @author Akash Yadav */ -abstract class AdvancedJavaEditHandler(protected val file: Path) : BaseJavaEditHandler() { - +abstract class AdvancedJavaEditHandler( + protected val file: Path, +) : BaseJavaEditHandler() { override fun performEdits( item: CompletionItem, editor: CodeEditor, text: Content, line: Int, column: Int, - index: Int + index: Int, ) { - val compiler = JavaCompilerProvider.get( - IProjectManager.getInstance().findModuleForFile(file, false) ?: return - ) + val compiler = JavaCompilerProvider.forFile(file) ?: return performEdits(compiler, editor, item) executeCommand(editor, item.command) @@ -59,6 +58,6 @@ abstract class AdvancedJavaEditHandler(protected val file: Path) : BaseJavaEditH abstract fun performEdits( compiler: JavaCompilerService, editor: CodeEditor, - completionItem: CompletionItem + completionItem: CompletionItem, ) } diff --git a/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/providers/JavaDiagnosticProvider.kt b/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/providers/JavaDiagnosticProvider.kt index 78671f4d67..4a38fa6e4d 100644 --- a/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/providers/JavaDiagnosticProvider.kt +++ b/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/providers/JavaDiagnosticProvider.kt @@ -36,22 +36,20 @@ import java.util.concurrent.atomic.AtomicBoolean * @author Akash Yadav */ class JavaDiagnosticProvider { - private val analyzeTimestamps = mutableMapOf() private var cachedDiagnostics = DiagnosticResult.NO_UPDATE private var analyzing = AtomicBoolean(false) private var analyzingThread: AnalyzingThread? = null companion object { - private val log = LoggerFactory.getLogger(JavaDiagnosticProvider::class.java) } fun analyze(file: Path): DiagnosticResult { - - val module = IProjectManager.getInstance().findModuleForFile(file, false) - ?: return DiagnosticResult.NO_UPDATE - val compiler = JavaCompilerService(module) + val module = + IProjectManager.getInstance().findModuleForFile(file, false) + ?: return DiagnosticResult.NO_UPDATE + val compiler = JavaCompilerService(module, module.artifactScopeOf(file)) abortIfCancelled() @@ -75,20 +73,19 @@ class JavaDiagnosticProvider { analyzing.set(true) - val analyzingThread = AnalyzingThread(compiler, file).also { - analyzingThread = it - it.start() - it.join() - } + val analyzingThread = + AnalyzingThread(compiler, file).also { + analyzingThread = it + it.start() + it.join() + } return analyzingThread.result.also { this.analyzingThread = null } } - fun isAnalyzing(): Boolean { - return this.analyzing.get() - } + fun isAnalyzing(): Boolean = this.analyzing.get() fun cancel() { this.analyzingThread?.cancel() @@ -98,7 +95,10 @@ class JavaDiagnosticProvider { analyzeTimestamps.remove(file) } - private fun doAnalyze(file: Path, task: CompileTask): DiagnosticResult { + private fun doAnalyze( + file: Path, + task: CompileTask, + ): DiagnosticResult { val result = if (!isTaskValid(task)) { // Do not use Collections.emptyList () @@ -106,13 +106,14 @@ class JavaDiagnosticProvider { // throws exception when trying to access. log.info("Using cached diagnostics") cachedDiagnostics - } else + } else { DiagnosticResult( file, findDiagnostics(task, file).sortedBy { it.range - } + }, ) + } return result.also { log.info("Analyze file completed. Found {} diagnostic items", result.diagnostics.size) } @@ -123,9 +124,10 @@ class JavaDiagnosticProvider { return task?.task != null && task.roots != null && task.roots.size > 0 } - inner class AnalyzingThread(val compiler: JavaCompilerService, val file: Path) : - Thread("JavaAnalyzerThread") { - + inner class AnalyzingThread( + val compiler: JavaCompilerService, + val file: Path, + ) : Thread("JavaAnalyzerThread") { var result: DiagnosticResult = DiagnosticResult.NO_UPDATE fun cancel() { @@ -146,11 +148,10 @@ class JavaDiagnosticProvider { } finally { compiler.destroy() analyzing.set(false) + }.also { + cachedDiagnostics = it + analyzeTimestamps[file] = Instant.now() } - .also { - cachedDiagnostics = it - analyzeTimestamps[file] = Instant.now() - } } } } diff --git a/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/providers/completion/ImportCompletionProvider.kt b/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/providers/completion/ImportCompletionProvider.kt index 4c3abf0e46..e7aaab5721 100644 --- a/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/providers/completion/ImportCompletionProvider.kt +++ b/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/providers/completion/ImportCompletionProvider.kt @@ -237,7 +237,7 @@ class ImportCompletionProvider( // A file in no module has no sources or classpath of its own, but still completes boot classpath imports. private fun importPathChildren(module: ModuleProject?) = ImportPathChildren( - module?.compileJavaSourceClasses ?: ClassTrie(), + module?.javaSourceClasses(compiler.scope) ?: ClassTrie(), compiler.classpathPackages(), BootClasspathProvider.getAllEntries(), ) diff --git a/lsp/java/src/test/java/com/itsaky/androidide/lsp/java/compiler/SourceFileManagerTestScopesTest.kt b/lsp/java/src/test/java/com/itsaky/androidide/lsp/java/compiler/SourceFileManagerTestScopesTest.kt new file mode 100644 index 0000000000..c7fed90b29 --- /dev/null +++ b/lsp/java/src/test/java/com/itsaky/androidide/lsp/java/compiler/SourceFileManagerTestScopesTest.kt @@ -0,0 +1,368 @@ +package com.itsaky.androidide.lsp.java.compiler + +import com.google.common.truth.Truth.assertThat +import com.itsaky.androidide.eventbus.events.file.FileCreationEvent +import com.itsaky.androidide.eventbus.events.file.FileDeletionEvent +import com.itsaky.androidide.lsp.java.JavaCompilerProvider +import com.itsaky.androidide.project.AndroidModels +import com.itsaky.androidide.project.GradleModels +import com.itsaky.androidide.projects.ProjectManagerImpl +import com.itsaky.androidide.projects.api.AndroidModule +import com.itsaky.androidide.projects.api.GradleProject +import com.itsaky.androidide.projects.api.Workspace +import com.itsaky.androidide.projects.models.ArtifactScope +import com.itsaky.androidide.utils.Environment +import jdkx.tools.JavaFileObject +import jdkx.tools.StandardLocation +import org.junit.After +import org.junit.Before +import org.junit.Rule +import org.junit.Test +import org.junit.rules.TemporaryFolder +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config +import java.io.File +import java.util.zip.ZipEntry +import java.util.zip.ZipOutputStream + +/** + * Java test sources compile in their own scope (ADFA-7115): a unit test sees main and its own + * sources and jars, an android test likewise, and main sees neither. + */ +@RunWith(RobolectricTestRunner::class) +@Config(manifest = Config.NONE) +class SourceFileManagerTestScopesTest { + @get:Rule + val temp = TemporaryFolder() + + private lateinit var mainDir: File + private lateinit var unitDir: File + private lateinit var deviceDir: File + private lateinit var sharedDir: File + private lateinit var junit: File + private lateinit var module: AndroidModule + private var previousJavaHome: File? = null + + // Other test classes in this JVM (JavaLSPTest) sync the test project once and keep relying on it. + private var previousWorkspace: Workspace? = null + + @Before + fun setUp() { + previousJavaHome = Environment.JAVA_HOME + previousWorkspace = ProjectManagerImpl.getInstance().workspace + Environment.JAVA_HOME = File(System.getProperty("java.home")) + + mainDir = temp.newFolder("app", "src", "main", "java") + unitDir = temp.newFolder("app", "src", "test", "java") + deviceDir = temp.newFolder("app", "src", "androidTest", "java") + sharedDir = temp.newFolder("app", "src", "sharedTest", "java") + source(mainDir, "Main") + source(unitDir, "MainTest") + source(deviceDir, "DeviceHelper") + junit = jar("junit.jar", "org/junit/Test.class") + val libDir = temp.newFolder("lib", "src", "main", "java") + source(libDir, "Lib") + + module = androidModule() + val lib = libraryModule(libDir) + val root = + GradleProject( + GradleModels.GradleProject + .newBuilder() + .setName("root") + .setPath(":") + .build(), + ) + ProjectManagerImpl.getInstance().workspace = + Workspace(rootProject = root, subProjects = listOf(module, lib), syncIssues = emptyList()) + module.indexSources() + } + + @After + fun tearDown() { + SourceFileManager.clearCache() + ProjectManagerImpl.getInstance().workspace = previousWorkspace + Environment.JAVA_HOME = previousJavaHome + } + + @Test + fun `a unit test sees main and its own sources, not android tests`() { + val unit = SourceFileManager.forModule(module, ArtifactScope.UNIT_TEST) + + assertThat(sourceFor(unit, "Main")).isNotNull() + assertThat(sourceFor(unit, "MainTest")).isNotNull() + assertThat(sourceFor(unit, "DeviceHelper")).isNull() + } + + @Test + fun `an android test sees main and its own sources, not unit tests`() { + val device = SourceFileManager.forModule(module, ArtifactScope.ANDROID_TEST) + + assertThat(sourceFor(device, "Main")).isNotNull() + assertThat(sourceFor(device, "DeviceHelper")).isNotNull() + assertThat(sourceFor(device, "MainTest")).isNull() + } + + @Test + fun `main sees no test sources`() { + val main = SourceFileManager.forModule(module) + + assertThat(sourceFor(main, "Main")).isNotNull() + assertThat(sourceFor(main, "MainTest")).isNull() + assertThat(sourceFor(main, "DeviceHelper")).isNull() + } + + @Test + fun `only the unit test scope compiles against a unit test jar`() { + assertThat(junitClasses(SourceFileManager.forModule(module, ArtifactScope.UNIT_TEST))).isNotEmpty() + assertThat(junitClasses(SourceFileManager.forModule(module, ArtifactScope.ANDROID_TEST))).isEmpty() + assertThat(junitClasses(SourceFileManager.forModule(module))).isEmpty() + } + + @Test + fun `a test source gets its package in the binary name`() { + val unit = SourceFileManager.forModule(module, ArtifactScope.UNIT_TEST) + + val binaryName = unit.inferBinaryName(StandardLocation.SOURCE_PATH, sourceFor(unit, "MainTest")) + + assertThat(binaryName).isEqualTo("com.app.MainTest") + } + + @Test + fun `a test file belongs to its scope`() { + assertThat(module.artifactScopeOf(File(unitDir, "com/app/MainTest.java"))).isEqualTo(ArtifactScope.UNIT_TEST) + assertThat(module.artifactScopeOf(File(deviceDir, "com/app/DeviceHelper.java"))).isEqualTo(ArtifactScope.ANDROID_TEST) + assertThat(module.artifactScopeOf(File(mainDir, "com/app/Main.java"))).isEqualTo(ArtifactScope.Main) + } + + @Test + fun `a created file is indexed only where it is visible`() { + val manager = ProjectManagerImpl.getInstance() + val newTest = source(unitDir, "NewTest") + val newMain = source(mainDir, "NewMain") + + manager.onFileCreated(FileCreationEvent(newTest)) + manager.onFileCreated(FileCreationEvent(newMain)) + + assertThat(indexedIn("NewTest")).containsExactly(ArtifactScope.UNIT_TEST) + assertThat(indexedIn("NewMain")).containsExactly(ArtifactScope.Main, ArtifactScope.UNIT_TEST, ArtifactScope.ANDROID_TEST) + + manager.onFileDeleted(FileDeletionEvent(newMain)) + + assertThat(indexedIn("NewMain")).isEmpty() + } + + @Test + fun `a file created in a dir shared by both test scopes is indexed in both`() { + val shared = source(sharedDir, "SharedHelper") + + ProjectManagerImpl.getInstance().onFileCreated(FileCreationEvent(shared)) + + assertThat(indexedIn("SharedHelper")).containsExactly(ArtifactScope.UNIT_TEST, ArtifactScope.ANDROID_TEST) + } + + @Test + fun `a test-only project dependency's sources are visible to that test scope only`() { + assertThat(sourceFor(SourceFileManager.forModule(module, ArtifactScope.UNIT_TEST), "Lib")).isNotNull() + assertThat(sourceFor(SourceFileManager.forModule(module, ArtifactScope.ANDROID_TEST), "Lib")).isNull() + assertThat(sourceFor(SourceFileManager.forModule(module), "Lib")).isNull() + // The trie feeds completion and import lookup, which do not fall back to the source path. + assertThat(indexedIn("Lib")).containsExactly(ArtifactScope.UNIT_TEST) + } + + @Test + fun `a directory that only shares a main source root's prefix is not under it`() { + val sibling = File(mainDir.path + "Test", "com/app/Sibling.java") + + assertThat(module.findSourceRoot(sibling)).isNull() + assertThat(module.findSourceRoot(File(mainDir, "com/app/Main.java"))).isEqualTo(mainDir.toPath()) + } + + @Test + fun `a main edit invalidates the test scopes' compiles, not main's`() { + val previousAndroidJar = Environment.ANDROID_JAR + Environment.ANDROID_JAR = previousAndroidJar ?: File("android.jar") + try { + val provider = JavaCompilerProvider.getInstance() + val main = provider.forModule(module, ArtifactScope.Main) + val unit = provider.forModule(module, ArtifactScope.UNIT_TEST) + + provider.invalidateScopesSeeing(module, ArtifactScope.Main) + + assertThat(unit.isStale).isTrue() + assertThat(main.isStale).isFalse() + } finally { + JavaCompilerProvider.getInstance().destroy() + Environment.ANDROID_JAR = previousAndroidJar + } + } + + @Test + fun `a test fixtures edit invalidates the test scopes' compiles, not main's or its own`() { + withAndroidJar { + val provider = JavaCompilerProvider.getInstance() + val main = provider.forModule(module, ArtifactScope.Main) + val unit = provider.forModule(module, ArtifactScope.UNIT_TEST) + val fixtures = provider.forModule(module, ArtifactScope.TestFixtures) + + provider.invalidateScopesSeeing(module, ArtifactScope.TestFixtures) + + assertThat(unit.isStale).isTrue() + assertThat(main.isStale).isFalse() + assertThat(fixtures.isStale).isFalse() + } + } + + /** The scopes whose trie holds `com.app.[name]`. */ + private fun indexedIn(name: String): List = + listOf(ArtifactScope.Main, ArtifactScope.UNIT_TEST, ArtifactScope.ANDROID_TEST).filter { + module.javaSourceClasses(it).findNode("com.app.$name") != + null + } + + private fun sourceFor( + manager: SourceFileManager, + name: String, + ): JavaFileObject? = manager.getJavaFileForInput(StandardLocation.SOURCE_PATH, "com.app.$name", JavaFileObject.Kind.SOURCE) + + private fun junitClasses(manager: SourceFileManager) = + manager.list(StandardLocation.CLASS_PATH, "org.junit", setOf(JavaFileObject.Kind.CLASS), false).toList() + + /** 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 + Environment.ANDROID_JAR = previousAndroidJar ?: File("android.jar") + try { + block() + } finally { + JavaCompilerProvider.getInstance().destroy() + Environment.ANDROID_JAR = previousAndroidJar + } + } + + private fun source( + root: File, + name: String, + ): File = + File(root, "com/app/$name.java").apply { + parentFile.mkdirs() + writeText("package com.app;\n\npublic class $name {}\n") + } + + private fun jar( + name: String, + vararg entries: String, + ): File { + val jar = temp.newFile(name) + ZipOutputStream(jar.outputStream()).use { zip -> + entries.forEach { + zip.putNextEntry(ZipEntry(it)) + zip.closeEntry() + } + } + return jar + } + + /** `:lib`, which only the app's unit tests depend on. */ + private fun libraryModule(dir: File): AndroidModule { + val projectDir = dir.parentFile.parentFile.parentFile + return AndroidModule( + GradleModels.GradleProject + .newBuilder() + .setName("lib") + .setPath(":lib") + .setProjectDirPath(projectDir.path) + .setBuildDirPath(File(projectDir, "build").path) + .setBuildScriptPath(File(projectDir, "build.gradle").path) + .setAndroidProject( + AndroidModels.AndroidProject + .newBuilder() + .setProjectType(AndroidModels.ProjectType.LibraryProject) + .setMainSourceSet( + AndroidModels.SourceSetContainer.newBuilder().putSourceProviders(ArtifactScope.Main.key, provider(dir)), + ).setVariantDependencies( + AndroidModels.VariantDependencies + .newBuilder() + .setName("debug") + .putArtifacts(ArtifactScope.Main.key, AndroidModels.ArtifactDependencies.getDefaultInstance()), + ), + ).build(), + ) + } + + private fun androidModule(): AndroidModule { + val junitKey = "junit" + val libKey = "project:lib" + val unitGraph = + AndroidModels.DependencyGraph + .newBuilder() + .addKey(junitKey) + .addNode(AndroidModels.GraphNode.newBuilder().setKeyId(0)) + .addRoot(0) + .addKey(libKey) + .addNode(AndroidModels.GraphNode.newBuilder().setKeyId(1)) + .addRoot(1) + val projectDir = mainDir.parentFile.parentFile.parentFile + return AndroidModule( + GradleModels.GradleProject + .newBuilder() + .setName("app") + .setPath(":app") + .setProjectDirPath(projectDir.path) + .setBuildDirPath(File(projectDir, "build").path) + .setBuildScriptPath(File(projectDir, "build.gradle").path) + .setAndroidProject( + AndroidModels.AndroidProject + .newBuilder() + .setProjectType(AndroidModels.ProjectType.ApplicationProject) + .setMainSourceSet( + AndroidModels.SourceSetContainer + .newBuilder() + .putSourceProviders(ArtifactScope.Main.key, provider(mainDir)) + .putSourceProviders(ArtifactScope.UNIT_TEST.key, provider(unitDir, sharedDir)) + .putSourceProviders(ArtifactScope.ANDROID_TEST.key, provider(deviceDir, sharedDir)), + ).setVariantDependencies( + AndroidModels.VariantDependencies + .newBuilder() + .setName("debug") + .putArtifacts(ArtifactScope.Main.key, AndroidModels.ArtifactDependencies.getDefaultInstance()) + .putArtifacts( + ArtifactScope.UNIT_TEST.key, + AndroidModels.ArtifactDependencies + .newBuilder() + .setCompileGraph(unitGraph) + .build(), + ).putArtifacts(ArtifactScope.ANDROID_TEST.key, AndroidModels.ArtifactDependencies.getDefaultInstance()) + .putLibraries( + junitKey, + AndroidModels.Library + .newBuilder() + .setKey(junitKey) + .setType(AndroidModels.LibraryType.ExternalJavaLibrary) + .setArtifactPath(junit.path) + .build(), + ).putLibraries( + libKey, + AndroidModels.Library + .newBuilder() + .setKey(libKey) + .setType(AndroidModels.LibraryType.Project) + .setProjectInfo( + AndroidModels.ProjectInfo + .newBuilder() + .setBuildId(":") + .setProjectPath(":lib"), + ).build(), + ), + ), + ).build(), + ) + } + + private fun provider(vararg dirs: File) = + AndroidModels.SourceProvider + .newBuilder() + .addAllJavaDirs(dirs.map { it.path }) + .build() +}