From 9628ef7837544654deb7cb25a97acec6da83b7b9 Mon Sep 17 00:00:00 2001 From: Hal Eisen Date: Fri, 13 Nov 2026 18:24:53 -0800 Subject: [PATCH 1/4] style: spotless reformat, no functional change --- .../lsp/java/JavaCompilerProvider.java | 121 ++++++------ .../actions/diagnostics/AddThrowsAction.kt | 178 ++++++++--------- .../diagnostics/CreateMissingMethodAction.kt | 168 ++++++++-------- .../actions/diagnostics/RemoveClassAction.kt | 168 ++++++++-------- .../actions/diagnostics/RemoveMethodAction.kt | 178 ++++++++--------- .../diagnostics/RemoveUnusedThrowsAction.kt | 184 +++++++++--------- .../SuppressUncheckedWarningAction.kt | 176 ++++++++--------- .../GenerateMissingConstructorAction.kt | 174 ++++++++--------- .../lsp/java/edits/AdvancedJavaEditHandler.kt | 16 +- .../java/providers/JavaDiagnosticProvider.kt | 47 ++--- 10 files changed, 704 insertions(+), 706 deletions(-) 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..2fd3987fef 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,13 @@ import androidx.annotation.NonNull; import androidx.annotation.Nullable; - import com.itsaky.androidide.lsp.java.compiler.JavaCompilerService; import com.itsaky.androidide.projects.api.ModuleProject; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - 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 +33,69 @@ * @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 static final Logger logger = LoggerFactory.getLogger(JavaCompilerProvider.class); + private static JavaCompilerProvider sInstance; + + @NonNull + public static JavaCompilerService get(ModuleProject module) { + return JavaCompilerProvider.getInstance().forModule(module); + } - private JavaCompilerProvider() {} + public static JavaCompilerProvider getInstance() { + if (sInstance == null) { + sInstance = new JavaCompilerProvider(); + } - @NonNull - public static JavaCompilerService get(ModuleProject module) { - return JavaCompilerProvider.getInstance().forModule(module); - } + return sInstance; + } - public static JavaCompilerProvider getInstance() { - if (sInstance == null) { - sInstance = new JavaCompilerProvider(); - } + private final Map mCompilers = new ConcurrentHashMap<>(); - return sInstance; - } + private JavaCompilerProvider() {} - /** - * 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; - } + // 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(); + } - @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; - } + /** + * 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; + } - final JavaCompilerService newInstance = new JavaCompilerService(module); - mCompilers.put(module, newInstance); + @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; + } - return newInstance; - } + final JavaCompilerService newInstance = new JavaCompilerService(module); + mCompilers.put(module, 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(); - } + return newInstance; + } } 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..d40f32a3f2 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.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) + } +} 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..6350f8bebc 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.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) + } +} 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..09da5a5ad7 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.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) + } +} 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..1500fb5068 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.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) + } +} 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..acfbd5a64a 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.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) + } +} 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..5d03260274 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.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) + } +} 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..9c533c8b52 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.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) + } +} 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..d466a35601 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,21 @@ 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.get( + IProjectManager.getInstance().findModuleForFile(file, false) ?: return, + ) performEdits(compiler, editor, item) executeCommand(editor, item.command) @@ -59,6 +61,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..b1241d73bf 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,21 +36,19 @@ 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 module = + IProjectManager.getInstance().findModuleForFile(file, false) + ?: return DiagnosticResult.NO_UPDATE val compiler = JavaCompilerService(module) 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() - } } } } From be2cbb55bc52e7aaa28514166bf0f1a332d5cb42 Mon Sep 17 00:00:00 2001 From: Hal Eisen Date: Fri, 13 Nov 2026 18:33:22 -0800 Subject: [PATCH 2/4] ADFA-7115: Compile Java test sources in their own scope A .java file under src/test or src/androidTest compiled with main's source path and classpath, so its sibling test classes and test-only dependencies were unresolved. - ModuleProject keeps one Java source trie per test scope, holding main's sources plus that scope's, beside the main-only compileJavaSourceClasses. indexSources fills them; testScopeOf maps a file to its scope. - SourceFileManager and JavaCompilerProvider cache per (module, scope). A scope's manager adds its test dirs to the source path, uses getTestCompileClasspaths, and reads the scope's trie. Keying by module alone would hand main the test classpath or tests main's. - JavaCompilerService carries the scope; CompileBatch, ClasspathTypeLookup and import completion read its trie. packageNameOrEmpty takes the scope, so a test class gets its real binary name. - Every compiler lookup passes the file: JavaCompilerProvider.get(module, file), or the new forFile(file) where the call site only looked the module up to pass it on. ModelUtils keeps main's compiler: it is the debugger's per-module class lookup. - File watchers index a created or renamed main file into main's trie and every test scope's, a test file into its own scope's only, and remove a deleted file from all of them. --- .../lsp/java/JavaCompilerProvider.java | 50 +++- .../androidide/lsp/java/JavaLanguageServer.kt | 4 +- .../lsp/java/actions/BaseJavaCodeAction.kt | 2 +- .../lsp/java/actions/FieldBasedAction.kt | 2 +- .../actions/diagnostics/AddImportAction.kt | 4 +- .../actions/diagnostics/AddThrowsAction.kt | 2 +- .../diagnostics/CreateMissingMethodAction.kt | 2 +- .../actions/diagnostics/FieldToBlockAction.kt | 2 +- .../actions/diagnostics/RemoveClassAction.kt | 2 +- .../actions/diagnostics/RemoveMethodAction.kt | 2 +- .../diagnostics/RemoveUnusedThrowsAction.kt | 2 +- .../SuppressUncheckedWarningAction.kt | 2 +- .../diagnostics/VariableToStatementAction.kt | 2 +- .../generators/GenerateConstructorAction.kt | 4 +- .../GenerateMissingConstructorAction.kt | 2 +- .../GenerateSettersAndGettersAction.kt | 4 +- .../GenerateToStringMethodAction.kt | 4 +- .../OverrideSuperclassMethodsAction.kt | 13 +- .../lsp/java/compiler/ClasspathTypeLookup.kt | 7 +- .../lsp/java/compiler/CompileBatch.java | 2 +- .../java/compiler/JavaCompilerService.java | 44 +++- .../lsp/java/compiler/SourceFileManager.java | 45 +++- .../lsp/java/edits/AdvancedJavaEditHandler.kt | 5 +- .../java/providers/JavaDiagnosticProvider.kt | 2 +- .../completion/ImportCompletionProvider.kt | 2 +- .../SourceFileManagerTestScopesTest.kt | 229 ++++++++++++++++++ .../androidide/projects/ProjectManagerImpl.kt | 46 ++-- .../androidide/projects/api/ModuleProject.kt | 99 ++++++-- 28 files changed, 473 insertions(+), 113 deletions(-) create mode 100644 lsp/java/src/test/java/com/itsaky/androidide/lsp/java/compiler/SourceFileManagerTestScopesTest.kt 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 2fd3987fef..a57d8accae 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 @@ -20,7 +20,11 @@ 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 com.itsaky.androidide.projects.api.TestScope; +import java.io.File; +import java.nio.file.Path; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.function.Function; @@ -36,9 +40,35 @@ public class JavaCompilerProvider { 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. */ + @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); + return JavaCompilerProvider.getInstance().forModule(module, null); + } + + /** See {@link #get(ModuleProject, Path)}. */ + @NonNull + public static JavaCompilerService get(@NonNull ModuleProject module, @NonNull File file) { + return get(module, file.toPath()); + } + + /** The compiler for {@code file}: its test scope's if {@code file} is a test source of {@code module}, main's otherwise. */ + @NonNull + public static JavaCompilerService get(@NonNull ModuleProject module, @NonNull Path file) { + return JavaCompilerProvider.getInstance().forModule(module, module.testScopeOf(file)); } public static JavaCompilerProvider getInstance() { @@ -49,7 +79,8 @@ public static JavaCompilerProvider getInstance() { return sInstance; } - private final Map mCompilers = new ConcurrentHashMap<>(); + // One compiler per module and test scope: each compiles against its own source path and classpath. + private final Map mCompilers = new ConcurrentHashMap<>(); private JavaCompilerProvider() {} @@ -86,16 +117,25 @@ public synchronized T find(Function action) { @NonNull public synchronized JavaCompilerService forModule(ModuleProject module) { + return forModule(module, null); + } + + /** The compiler for {@code scope}'s tests of {@code module}, or for its main sources when {@code scope} is null. */ + @NonNull + public synchronized JavaCompilerService forModule(ModuleProject module, @Nullable TestScope 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 JavaCompilerService cached = mCompilers.get(module); + 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); - mCompilers.put(module, newInstance); + final JavaCompilerService newInstance = new JavaCompilerService(module, scope); + mCompilers.put(key, newInstance); return newInstance; } + + private record Key(ModuleProject module, @Nullable TestScope 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..1733b041d8 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,7 +369,7 @@ class JavaLanguageServer : ILanguageServer { getInstance() .findModuleForFile(event.changedFile) if (module != null) { - val compiler = JavaCompilerProvider.get(module) + val compiler = JavaCompilerProvider.get(module, event.changedFile) compiler.onDocumentChange(event) } 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 d40f32a3f2..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 @@ -61,7 +61,7 @@ class AddThrowsAction : BaseJavaCodeAction() { 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()) + JavaCompilerProvider.forFile(data.requireFile()) ?: return Any() val file = data.requirePath() return compiler.compile(file).get { task -> val needsThrow = CodeActionUtils.findMethod(task, diagnostic.range) 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 6350f8bebc..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 @@ -63,7 +63,7 @@ class CreateMissingMethodAction : 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 file = data.requirePath() return compiler.compile(file).get { CreateMissingMethod(file, findPosition(it, diagnostic.range.start)) 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 09da5a5ad7..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 @@ -62,7 +62,7 @@ class RemoveClassAction : 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 file = data.requirePath() return compiler.compile(file).get { 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 1500fb5068..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 @@ -62,7 +62,7 @@ class RemoveMethodAction : 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 file = data.requirePath() return compiler.compile(file).get { 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 acfbd5a64a..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 @@ -63,7 +63,7 @@ class RemoveUnusedThrowsAction : BaseJavaCodeAction() { 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()) + JavaCompilerProvider.forFile(data.requireFile()) ?: return Any() val file = data.requirePath() return compiler.compile(file).get { task -> val notThrown = CodeActionUtils.extractNotThrownExceptionName(d.message) 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 5d03260274..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 @@ -62,7 +62,7 @@ class SuppressUncheckedWarningAction : 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 file = data.requirePath() return compiler.compile(file).get { task -> val warnedMethod = CodeActionUtils.findMethod(task, diagnostic.range) 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 9c533c8b52..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 @@ -64,7 +64,7 @@ class GenerateMissingConstructorAction : 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 file = data.requirePath() return compiler.compile(file).get { task -> val needsConstructor = 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..0f264bcb91 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.api.TestScope 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, or main's when it is null. A + * `null` [module] has no source or classpath classes. */ @JvmStatic fun forModule( module: ModuleProject?, + scope: TestScope?, 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..fe616f2490 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.api.TestScope; import com.itsaky.androidide.projects.util.BootClasspathProvider; import com.itsaky.androidide.projects.util.StringSearch; import com.itsaky.androidide.utils.Cache; @@ -83,6 +84,8 @@ public class JavaCompilerService implements CompilerProvider { protected final SynchronizedTask synchronizedTask = new SynchronizedTask(); protected final SourceFileManager fileManager; protected final ModuleProject module; + @Nullable + protected final TestScope scope; private final ClasspathTypeLookup types; public ReusableCompiler compiler = new JCReusableCompiler(); protected Set bootClasspathClasses = BootClasspathProvider.getTopLevelClasses( @@ -96,14 +99,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, (TestScope) null); + } + + /** A compiler for {@code scope}'s tests of {@code module}, or for its main sources when {@code scope} is null. */ + public JavaCompilerService(@Nullable ModuleProject module, @Nullable TestScope 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 +121,17 @@ public JavaCompilerService(@Nullable ModuleProject module) { SourceFileManager fileManager, Set bootClasspathClasses, ClasspathTypeLookup types) { + this(module, null, fileManager, bootClasspathClasses, types); + } + + private JavaCompilerService( + @Nullable ModuleProject module, + @Nullable TestScope scope, + SourceFileManager fileManager, + Set bootClasspathClasses, + ClasspathTypeLookup types) { this.module = module; + this.scope = scope; this.fileManager = fileManager; this.bootClasspathClasses = bootClasspathClasses; this.types = types; @@ -143,7 +162,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 +205,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 +226,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 +251,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,6 +268,17 @@ public ModuleProject getModule() { return module; } + /** The test scope this compiler compiles, or null for main sources. */ + @Nullable + public TestScope 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; } @@ -435,7 +465,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..05dd579b71 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 @@ -21,11 +21,13 @@ import static java.util.Collections.emptySet; import androidx.annotation.NonNull; +import androidx.annotation.Nullable; import com.itsaky.androidide.javac.config.JavacConfigProvider; import com.itsaky.androidide.javac.services.fs.AndroidFsProviderImpl; import com.itsaky.androidide.javac.services.fs.JarPackageProviderImpl; import com.itsaky.androidide.projects.api.AndroidModule; import com.itsaky.androidide.projects.api.ModuleProject; +import com.itsaky.androidide.projects.api.TestScope; import com.itsaky.androidide.projects.models.AndroidProjectExtsKt; import com.itsaky.androidide.projects.util.StringSearch; import com.itsaky.androidide.utils.ClassTrie; @@ -40,6 +42,7 @@ import java.nio.file.Files; import java.nio.file.Path; import java.util.EnumSet; +import java.util.LinkedHashSet; import java.util.List; import java.util.Locale; import java.util.Map; @@ -63,12 +66,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 +88,13 @@ public static void clearCache() { } public static SourceFileManager forModule(@NonNull ModuleProject project) { + return forModule(project, null); + } + + /** The file manager for {@code scope}'s tests of {@code project}, or for its main sources when {@code scope} is null. */ + public static SourceFileManager forModule(@NonNull ModuleProject project, @Nullable TestScope 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 +108,20 @@ 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) { + @Nullable + private final TestScope scope; + + private SourceFileManager(final ModuleProject module, @Nullable final TestScope scope) { super(createDelegateFileManager()); this.module = module; + this.scope = scope; AndroidFsProviderImpl.INSTANCE.init(); @@ -120,7 +133,11 @@ 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 = new LinkedHashSet<>(module.getCompileSourceDirectories()); + if (scope != null) { + sourcePath.addAll(module.getTestSourceDirectories(scope)); + } + setLocationLogError(StandardLocation.SOURCE_PATH, sourcePath); setLocationLogError(StandardLocation.CLASS_PATH, configureClasspaths(module)); listLocations(EnumSet.of(StandardLocation.CLASS_PATH, StandardLocation.PLATFORM_CLASS_PATH)); } @@ -129,7 +146,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 +167,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 +211,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 +265,7 @@ private Set configureClasspaths(final ModuleProject module) { setLocationLogError(StandardLocation.PLATFORM_CLASS_PATH, AndroidProjectExtsKt.getBootClassPaths(androidModule)); } - return module.getCompileClasspaths(); + return scope == null ? module.getCompileClasspaths() : module.getTestCompileClasspaths(scope, false); } private void listLocations(final EnumSet locations) { @@ -263,11 +280,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, @Nullable TestScope 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 d466a35601..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 @@ -41,10 +41,7 @@ abstract class AdvancedJavaEditHandler( column: 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) 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 b1241d73bf..363a2893a0 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 @@ -49,7 +49,7 @@ class JavaDiagnosticProvider { val module = IProjectManager.getInstance().findModuleForFile(file, false) ?: return DiagnosticResult.NO_UPDATE - val compiler = JavaCompilerService(module) + val compiler = JavaCompilerService(module, module.testScopeOf(file)) abortIfCancelled() 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..f671efdcc9 --- /dev/null +++ b/lsp/java/src/test/java/com/itsaky/androidide/lsp/java/compiler/SourceFileManagerTestScopesTest.kt @@ -0,0 +1,229 @@ +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.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.TestScope +import com.itsaky.androidide.projects.api.Workspace +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 junit: File + private lateinit var module: AndroidModule + private var previousJavaHome: File? = null + + @Before + fun setUp() { + previousJavaHome = Environment.JAVA_HOME + 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") + source(mainDir, "Main") + source(unitDir, "MainTest") + source(deviceDir, "DeviceHelper") + junit = jar("junit.jar", "org/junit/Test.class") + + module = androidModule() + val root = + GradleProject( + GradleModels.GradleProject + .newBuilder() + .setName("root") + .setPath(":") + .build(), + ) + ProjectManagerImpl.getInstance().workspace = Workspace(rootProject = root, subProjects = listOf(module), syncIssues = emptyList()) + module.indexSources() + } + + @After + fun tearDown() { + SourceFileManager.clearCache() + runCatching { ProjectManagerImpl.getInstance().workspace = null } + Environment.JAVA_HOME = previousJavaHome + } + + @Test + fun `a unit test sees main and its own sources, not android tests`() { + val unit = SourceFileManager.forModule(module, TestScope.UNIT) + + 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, TestScope.ANDROID) + + 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, TestScope.UNIT))).isNotEmpty() + assertThat(junitClasses(SourceFileManager.forModule(module, TestScope.ANDROID))).isEmpty() + assertThat(junitClasses(SourceFileManager.forModule(module))).isEmpty() + } + + @Test + fun `a test source gets its package in the binary name`() { + val unit = SourceFileManager.forModule(module, TestScope.UNIT) + + 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.testScopeOf(File(unitDir, "com/app/MainTest.java"))).isEqualTo(TestScope.UNIT) + assertThat(module.testScopeOf(File(deviceDir, "com/app/DeviceHelper.java"))).isEqualTo(TestScope.ANDROID) + assertThat(module.testScopeOf(File(mainDir, "com/app/Main.java"))).isNull() + } + + @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(TestScope.UNIT) + assertThat(indexedIn("NewMain")).containsExactly(null, TestScope.UNIT, TestScope.ANDROID) + + manager.onFileDeleted(FileDeletionEvent(newMain)) + + assertThat(indexedIn("NewMain")).isEmpty() + } + + /** The scopes (null for main) whose trie holds `com.app.[name]`. */ + private fun indexedIn(name: String): List = + (listOf(null) + TestScope.entries).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() + + 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 + } + + private fun androidModule(): AndroidModule { + val junitKey = "junit" + val unitGraph = + AndroidModels.DependencyGraph + .newBuilder() + .addKey(junitKey) + .addNode(AndroidModels.GraphNode.newBuilder().setKeyId(0)) + .addRoot(0) + 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() + .setSourceProvider(provider(mainDir)) + .setUnitTestSourceProvider(provider(unitDir)) + .setAndroidTestSourceProvider(provider(deviceDir)), + ).setVariantDependencies( + AndroidModels.VariantDependencies + .newBuilder() + .setName("debug") + .setMainArtifact(AndroidModels.ArtifactDependencies.getDefaultInstance()) + .setUnitTestArtifact(AndroidModels.ArtifactDependencies.newBuilder().setCompileGraph(unitGraph)) + .setAndroidTestArtifact(AndroidModels.ArtifactDependencies.getDefaultInstance()) + .putLibraries( + junitKey, + AndroidModels.Library + .newBuilder() + .setKey(junitKey) + .setType(AndroidModels.LibraryType.ExternalJavaLibrary) + .setArtifactPath(junit.path) + .build(), + ), + ), + ).build(), + ) + } + + private fun provider(dir: File) = AndroidModels.SourceProvider.newBuilder().addJavaDirs(dir.path) +} diff --git a/subprojects/projects/src/main/java/com/itsaky/androidide/projects/ProjectManagerImpl.kt b/subprojects/projects/src/main/java/com/itsaky/androidide/projects/ProjectManagerImpl.kt index 094c3c695f..45d4359ab5 100644 --- a/subprojects/projects/src/main/java/com/itsaky/androidide/projects/ProjectManagerImpl.kt +++ b/subprojects/projects/src/main/java/com/itsaky/androidide/projects/ProjectManagerImpl.kt @@ -446,11 +446,11 @@ class ProjectManagerImpl : generateSourcesIfNecessary(event) if (DocumentUtils.isJavaFile(event.file.toPath())) { - IProjectManager.getInstance().findModuleForFile(event.file, false)?.let { - val sourceRoot = it.findSourceRoot(event.file) ?: return@let - - // add the source node entry - it.compileJavaSourceClasses.append(event.file.toPath(), sourceRoot) + IProjectManager.getInstance().findModuleForFile(event.file, false)?.let { module -> + // add the source node entry to main's trie and/or the test scopes' that see this file + module.javaSourceClassesFor(event.file).forEach { (trie, sourceRoot) -> + trie.append(event.file.toPath(), sourceRoot) + } } } } @@ -464,17 +464,19 @@ class ProjectManagerImpl : // Do not check for Java file DocumentUtils.isJavaFile(...) as it checks for file existence as // well. As the file is already deleted, it will always return false if (event.file.extension == "java") { - IProjectManager - .getInstance() - .findModuleForFile( - event.file, - false, - )?.compileJavaSourceClasses - ?.findSource(event.file.toPath()) - ?.let { it.parent?.removeChild(it) } + removeJavaSource(event.file) } } + /** Removes [file] from every Java source trie of its module. */ + private fun removeJavaSource(file: File) { + IProjectManager + .getInstance() + .findModuleForFile(file, false) + ?.allJavaSourceClasses() + ?.forEach { trie -> trie.findSource(file.toPath())?.let { it.parent?.removeChild(it) } } + } + @Suppress("unused") @Subscribe(threadMode = ThreadMode.BACKGROUND) fun onFileRenamed(event: FileRenameEvent) { @@ -483,22 +485,14 @@ class ProjectManagerImpl : // Do not check for Java file DocumentUtils.isJavaFile(...) as it checks for file existence as // well. As the file is already renamed to another filename, it will always return false if (event.file.extension == "java") { - // remove the source node entry - IProjectManager - .getInstance() - .findModuleForFile( - event.file, - false, - )?.compileJavaSourceClasses - ?.findSource(event.file.toPath()) - ?.let { it.parent?.removeChild(it) } + removeJavaSource(event.file) } if (DocumentUtils.isJavaFile(event.newFile.toPath())) { - IProjectManager.getInstance().findModuleForFile(event.newFile, false)?.let { - val sourceRoot = it.findSourceRoot(event.newFile) ?: return@let - // add the new source node entry - it.compileJavaSourceClasses.append(event.newFile.toPath(), sourceRoot) + IProjectManager.getInstance().findModuleForFile(event.newFile, false)?.let { module -> + module.javaSourceClassesFor(event.newFile).forEach { (trie, sourceRoot) -> + trie.append(event.newFile.toPath(), sourceRoot) + } } } } diff --git a/subprojects/projects/src/main/java/com/itsaky/androidide/projects/api/ModuleProject.kt b/subprojects/projects/src/main/java/com/itsaky/androidide/projects/api/ModuleProject.kt index 6b927ebad5..e523010ff8 100644 --- a/subprojects/projects/src/main/java/com/itsaky/androidide/projects/api/ModuleProject.kt +++ b/subprojects/projects/src/main/java/com/itsaky/androidide/projects/api/ModuleProject.kt @@ -78,9 +78,44 @@ abstract class ModuleProject( val COMPLETION_MODULE_KEY = Lookup.Key() } + /** The Java classes main code compiles against: this module's and its compile dependencies' sources. */ @JvmField val compileJavaSourceClasses = SourceClassTrie() + // Each scope's trie holds the main sources too, so a test compilation reads one trie, as main does. + private val testJavaSourceClasses = TestScope.entries.associateWith { SourceClassTrie() } + + /** The Java classes [scope] tests compile against, or main's when [scope] is null. */ + fun javaSourceClasses(scope: TestScope?): SourceClassTrie = + if (scope == null) compileJavaSourceClasses else testJavaSourceClasses.getValue(scope) + + /** The test scope whose source directories hold [file], or null for main sources and anything else. */ + fun testScopeOf(file: Path): TestScope? = + TestScope.entries.firstOrNull { scope -> getTestSourceDirectories(scope).any { file.startsWith(it.toPath()) } } + + fun testScopeOf(file: File): TestScope? = testScopeOf(file.toPath()) + + /** + * The tries a Java [file] belongs in, each with the source root to index it under: a main source + * goes in main's trie and every test scope's, a test source in its own scope's only. Empty when + * the file is in no source directory. + */ + fun javaSourceClassesFor(file: File): List> { + findSourceRoot(file)?.let { root -> + return listOf(compileJavaSourceClasses to root) + + TestScope.entries + .filter { getTestSourceDirectories(it).isNotEmpty() } + .map { testJavaSourceClasses.getValue(it) to root } + } + val path = file.toPath() + val scope = testScopeOf(path) ?: return emptyList() + val root = getTestSourceDirectories(scope).first { path.startsWith(it.toPath()) }.toPath() + return listOf(testJavaSourceClasses.getValue(scope) to root) + } + + /** Every Java source trie of this module, for removing a file that may be in any of them. */ + fun allJavaSourceClasses(): List = listOf(compileJavaSourceClasses) + testJavaSourceClasses.values + /** * Get the source directories of this module (non-transitive i.e for this module only). * @@ -267,34 +302,52 @@ abstract class ModuleProject( @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP_PREFIX) fun indexSources() { - this.compileJavaSourceClasses.clear() + allJavaSourceClasses().forEach { it.clear() } val watch = StopWatch("Indexing sources") - var count = 0 - getCompileSourceDirectories().forEach { - val sourceDir = it.toPath() - it - .walk() - .filter { file -> file.isFile && file.exists() && DocumentUtils.isJavaFile(file.toPath()) } - .map { file -> file.toPath() } - .forEach { file -> - this.compileJavaSourceClasses.append(file, sourceDir) - count++ - } + val mainSources = javaSourcesIn(getCompileSourceDirectories()) + mainSources.forEach { (file, root) -> compileJavaSourceClasses.append(file, root) } + + var count = mainSources.size + for (scope in TestScope.entries) { + val testDirs = getTestSourceDirectories(scope) + if (testDirs.isEmpty()) { + continue + } + val trie = testJavaSourceClasses.getValue(scope) + val testSources = javaSourcesIn(testDirs) + (mainSources + testSources).forEach { (file, root) -> trie.append(file, root) } + count += testSources.size } watch.log() log.debug("Found {} source files.", count) } + /** Every Java file under [dirs], paired with the directory it was found under. */ + private fun javaSourcesIn(dirs: Collection): List> = + dirs.flatMap { dir -> + val root = dir.toPath() + dir + .walk() + .filter { file -> file.isFile && file.exists() && DocumentUtils.isJavaFile(file.toPath()) } + .map { file -> file.toPath() to root } + .toList() + } + fun getSourceFilesInDir(dir: Path): List = this.compileJavaSourceClasses.getSourceFilesInDir(dir) - fun packageNameOrEmpty(file: Path?): String { + /** The package of [file] as [scope]'s compilation sees it; main's when [scope] is null. */ + @JvmOverloads + fun packageNameOrEmpty( + file: Path?, + scope: TestScope? = null, + ): String { if (file == null) { return "" } - val sourceNode = searchSourceFileRelatively(file) + val sourceNode = searchSourceFileRelatively(file, scope) if (sourceNode != null) { return sourceNode.packageName } @@ -302,8 +355,12 @@ abstract class ModuleProject( return "" } - private fun searchSourceFileRelatively(file: Path?): SourceNode? { - for (source in getCompileSourceDirectories().map(File::toPath)) { + private fun searchSourceFileRelatively( + file: Path?, + scope: TestScope?, + ): SourceNode? { + val roots = getCompileSourceDirectories() + (scope?.let(::getTestSourceDirectories) ?: emptySet()) + for (source in roots.map(File::toPath)) { val relative = source.relativize(file) if (relative.pathString.contains("..")) { // This is most probably not the one we're expecting @@ -313,7 +370,7 @@ abstract class ModuleProject( var name = relative.pathString.substringBeforeLast(".java") name = name.replace('/', '.') - val node = this.compileJavaSourceClasses.findNode(name) + val node = javaSourceClasses(scope).findNode(name) if (node != null && node is SourceNode) { return node } @@ -345,8 +402,12 @@ abstract class ModuleProject( return "" } - fun listClassesFromSourceDirs(packageName: String): List = - compileJavaSourceClasses + @JvmOverloads + fun listClassesFromSourceDirs( + packageName: String, + scope: TestScope? = null, + ): List = + javaSourceClasses(scope) .findInPackage(packageName) .filterIsInstance() From 8b39c5dd2923c2e8a5e29a2451362d065c8ab845 Mon Sep 17 00:00:00 2001 From: Hal Eisen Date: Fri, 13 Nov 2026 19:23:57 -0800 Subject: [PATCH 3/4] ADFA-7115: Address CodeRabbit review of the Java test scopes - Test-only project dependencies: a scope's source path and trie now come from getTestCompileSourceDirectories (main's, the scope's tests, and the sources of modules only those tests depend on), so testImplementation(project(":lib")) resolves in Java tests too. - findSourceRoot matches whole directories (Path.startsWith), so src/main/javaTest is no longer taken for src/main/java and its files indexed into main. - An edit to a main source marks the module's test-scope compilers stale. The compile cache only checks the requested files' timestamps, so a test compile reused a task built against the old main source. The flag is lock-free: change events arrive per keystroke and must not wait on a compile in progress. --- .../lsp/java/JavaCompilerProvider.java | 9 ++ .../androidide/lsp/java/JavaLanguageServer.kt | 4 + .../java/compiler/JavaCompilerService.java | 20 ++++- .../lsp/java/compiler/SourceFileManager.java | 8 +- .../SourceFileManagerTestScopesTest.kt | 85 ++++++++++++++++++- .../androidide/projects/api/ModuleProject.kt | 23 +++-- 6 files changed, 137 insertions(+), 12 deletions(-) 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 a57d8accae..2911640901 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 @@ -137,5 +137,14 @@ public synchronized JavaCompilerService forModule(ModuleProject module, @Nullabl return newInstance; } + /** Invalidates the cached compiles of {@code module}'s test scopes, which read its main sources. */ + public void invalidateTestScopes(@NonNull ModuleProject module) { + mCompilers.forEach((key, compiler) -> { + if (key.module() == module && key.scope() != null) { + compiler.invalidateCompile(); + } + }); + } + private record Key(ModuleProject module, @Nullable TestScope 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 1733b041d8..139244dc04 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 @@ -371,6 +371,10 @@ class JavaLanguageServer : ILanguageServer { if (module != null) { val compiler = JavaCompilerProvider.get(module, event.changedFile) compiler.onDocumentChange(event) + if (compiler.scope == null) { + // The test scopes compile against main, so their cached compiles are stale now. + JavaCompilerProvider.getInstance().invalidateTestScopes(module) + } } startOrRestartAnalyzeTimer() } 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 fe616f2490..9a9b8c47bc 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 @@ -92,6 +92,7 @@ public class JavaCompilerService implements CompilerProvider { 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; @@ -283,6 +284,13 @@ 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(); @@ -305,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) { @@ -331,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"); 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 05dd579b71..cd7829ac6e 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 @@ -42,7 +42,6 @@ import java.nio.file.Files; import java.nio.file.Path; import java.util.EnumSet; -import java.util.LinkedHashSet; import java.util.List; import java.util.Locale; import java.util.Map; @@ -133,10 +132,9 @@ private SourceFileManager(final ModuleProject module, @Nullable final TestScope System.setProperty(JavacConfigProvider.PROP_ANDROIDIDE_JAVA_HOME, Environment.JAVA_HOME.getAbsolutePath()); - final Set sourcePath = new LinkedHashSet<>(module.getCompileSourceDirectories()); - if (scope != null) { - sourcePath.addAll(module.getTestSourceDirectories(scope)); - } + final Set sourcePath = scope == null + ? module.getCompileSourceDirectories() + : module.getTestCompileSourceDirectories(scope); setLocationLogError(StandardLocation.SOURCE_PATH, sourcePath); setLocationLogError(StandardLocation.CLASS_PATH, configureClasspaths(module)); listLocations(EnumSet.of(StandardLocation.CLASS_PATH, StandardLocation.PLATFORM_CLASS_PATH)); 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 index f671efdcc9..d423596ef8 100644 --- 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 @@ -3,6 +3,7 @@ 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 @@ -54,8 +55,11 @@ class SourceFileManagerTestScopesTest { 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 @@ -64,7 +68,8 @@ class SourceFileManagerTestScopesTest { .setPath(":") .build(), ) - ProjectManagerImpl.getInstance().workspace = Workspace(rootProject = root, subProjects = listOf(module), syncIssues = emptyList()) + ProjectManagerImpl.getInstance().workspace = + Workspace(rootProject = root, subProjects = listOf(module, lib), syncIssues = emptyList()) module.indexSources() } @@ -142,6 +147,42 @@ class SourceFileManagerTestScopesTest { assertThat(indexedIn("NewMain")).isEmpty() } + @Test + fun `a test-only project dependency's sources are visible to that test scope only`() { + assertThat(sourceFor(SourceFileManager.forModule(module, TestScope.UNIT), "Lib")).isNotNull() + assertThat(sourceFor(SourceFileManager.forModule(module, TestScope.ANDROID), "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(TestScope.UNIT) + } + + @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, null) + val unit = provider.forModule(module, TestScope.UNIT) + + provider.invalidateTestScopes(module) + + assertThat(unit.isStale).isTrue() + assertThat(main.isStale).isFalse() + } finally { + JavaCompilerProvider.getInstance().destroy() + Environment.ANDROID_JAR = previousAndroidJar + } + } + /** The scopes (null for main) whose trie holds `com.app.[name]`. */ private fun indexedIn(name: String): List = (listOf(null) + TestScope.entries).filter { module.javaSourceClasses(it).findNode("com.app.$name") != null } @@ -177,14 +218,44 @@ class SourceFileManagerTestScopesTest { 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().setSourceProvider(provider(dir))) + .setVariantDependencies( + AndroidModels.VariantDependencies + .newBuilder() + .setName("debug") + .setMainArtifact(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 @@ -219,6 +290,18 @@ class SourceFileManagerTestScopesTest { .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(), diff --git a/subprojects/projects/src/main/java/com/itsaky/androidide/projects/api/ModuleProject.kt b/subprojects/projects/src/main/java/com/itsaky/androidide/projects/api/ModuleProject.kt index bfa96b4f7b..7edea12611 100644 --- a/subprojects/projects/src/main/java/com/itsaky/androidide/projects/api/ModuleProject.kt +++ b/subprojects/projects/src/main/java/com/itsaky/androidide/projects/api/ModuleProject.kt @@ -158,6 +158,16 @@ abstract class ModuleProject( */ abstract fun getTestCompileModuleProjects(scope: TestScope): List + /** + * The source directories [scope] tests compile against, the test counterpart of + * [getCompileSourceDirectories]: main's, this module's [scope] tests, and the sources of the + * modules only those tests depend on. + */ + fun getTestCompileSourceDirectories(scope: TestScope): Set = + getCompileSourceDirectories() + + getTestSourceDirectories(scope) + + getTestCompileModuleProjects(scope).flatMap { it.getSourceDirectories() } + /** * Get the classpaths for this module project. The returned list always included the * `classes.jar`. @@ -281,7 +291,11 @@ abstract class ModuleProject( * @param file The file to find the source root for. * @return The source root (directory) of the given file, or `null` if not found. */ - fun findSourceRoot(file: File): Path? = getCompileSourceDirectories().find { file.path.startsWith(it.path) }?.toPath() + fun findSourceRoot(file: File): Path? { + // Path.startsWith matches whole directories: src/main/javaTest is not under src/main/java. + val path = file.toPath() + return getCompileSourceDirectories().map(File::toPath).find { path.startsWith(it) } + } /** Indexes the source files' classes and prepares the classpaths for the compiler. */ @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP_PREFIX) @@ -316,12 +330,11 @@ abstract class ModuleProject( var count = mainSources.size for (scope in TestScope.entries) { - val testDirs = getTestSourceDirectories(scope) - if (testDirs.isEmpty()) { + if (getTestSourceDirectories(scope).isEmpty()) { continue } val trie = testJavaSourceClasses.getValue(scope) - val testSources = javaSourcesIn(testDirs) + val testSources = javaSourcesIn(getTestCompileSourceDirectories(scope) - getCompileSourceDirectories()) (mainSources + testSources).forEach { (file, root) -> trie.append(file, root) } count += testSources.size } @@ -365,7 +378,7 @@ abstract class ModuleProject( file: Path?, scope: TestScope?, ): SourceNode? { - val roots = getCompileSourceDirectories() + (scope?.let(::getTestSourceDirectories) ?: emptySet()) + val roots = scope?.let(::getTestCompileSourceDirectories) ?: getCompileSourceDirectories() for (source in roots.map(File::toPath)) { val relative = source.relativize(file) if (relative.pathString.contains("..")) { From b91a8043912a5ec1ec07ca9e0f80c013469ee092 Mon Sep 17 00:00:00 2001 From: Hal Eisen Date: Sat, 14 Nov 2026 08:17:00 -0800 Subject: [PATCH 4/4] ADFA-7115: Index a new file in every test scope that holds its dir A source dir such as src/sharedTest/java can be in both the unit and the android test source sets. indexSources already put its files in both tries, but javaSourceClassesFor picked the first matching scope, so a file created or renamed there was visible to unit tests only until the next sync. --- .../compiler/SourceFileManagerTestScopesTest.kt | 17 ++++++++++++++--- .../androidide/projects/api/ModuleProject.kt | 11 +++++++---- 2 files changed, 21 insertions(+), 7 deletions(-) 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 index d423596ef8..6145140437 100644 --- 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 @@ -39,6 +39,7 @@ class SourceFileManagerTestScopesTest { 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 @@ -51,6 +52,7 @@ class SourceFileManagerTestScopesTest { 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") @@ -147,6 +149,15 @@ class SourceFileManagerTestScopesTest { 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(TestScope.UNIT, TestScope.ANDROID) + } + @Test fun `a test-only project dependency's sources are visible to that test scope only`() { assertThat(sourceFor(SourceFileManager.forModule(module, TestScope.UNIT), "Lib")).isNotNull() @@ -273,8 +284,8 @@ class SourceFileManagerTestScopesTest { AndroidModels.SourceSetContainer .newBuilder() .setSourceProvider(provider(mainDir)) - .setUnitTestSourceProvider(provider(unitDir)) - .setAndroidTestSourceProvider(provider(deviceDir)), + .setUnitTestSourceProvider(provider(unitDir, sharedDir)) + .setAndroidTestSourceProvider(provider(deviceDir, sharedDir)), ).setVariantDependencies( AndroidModels.VariantDependencies .newBuilder() @@ -308,5 +319,5 @@ class SourceFileManagerTestScopesTest { ) } - private fun provider(dir: File) = AndroidModels.SourceProvider.newBuilder().addJavaDirs(dir.path) + private fun provider(vararg dirs: File) = AndroidModels.SourceProvider.newBuilder().addAllJavaDirs(dirs.map { it.path }) } diff --git a/subprojects/projects/src/main/java/com/itsaky/androidide/projects/api/ModuleProject.kt b/subprojects/projects/src/main/java/com/itsaky/androidide/projects/api/ModuleProject.kt index 7edea12611..15366c5faf 100644 --- a/subprojects/projects/src/main/java/com/itsaky/androidide/projects/api/ModuleProject.kt +++ b/subprojects/projects/src/main/java/com/itsaky/androidide/projects/api/ModuleProject.kt @@ -97,7 +97,7 @@ abstract class ModuleProject( /** * The tries a Java [file] belongs in, each with the source root to index it under: a main source - * goes in main's trie and every test scope's, a test source in its own scope's only. Empty when + * goes in main's trie and every test scope's, a test source in each scope that holds its dir. Empty when * the file is in no source directory. */ fun javaSourceClassesFor(file: File): List> { @@ -108,9 +108,12 @@ abstract class ModuleProject( .map { testJavaSourceClasses.getValue(it) to root } } val path = file.toPath() - val scope = testScopeOf(path) ?: return emptyList() - val root = getTestSourceDirectories(scope).first { path.startsWith(it.toPath()) }.toPath() - return listOf(testJavaSourceClasses.getValue(scope) to root) + // Every matching scope, not the first: a dir such as src/sharedTest can be in both. + return TestScope.entries.mapNotNull { scope -> + getTestSourceDirectories(scope) + .firstOrNull { path.startsWith(it.toPath()) } + ?.let { testJavaSourceClasses.getValue(scope) to it.toPath() } + } } /** Every Java source trie of this module, for removing a file that may be in any of them. */