Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -19,88 +19,129 @@

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.itsaky.androidide.lsp.java.compiler.JavaCompilerService;
import com.itsaky.androidide.projects.IProjectManager;
import com.itsaky.androidide.projects.api.ModuleProject;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.itsaky.androidide.projects.models.ArtifactScope;
import java.io.File;
import java.nio.file.Path;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
* Provides {@link JavaCompilerService} instances for different {@link ModuleProject}s.
*
* @author Akash Yadav
*/
public class JavaCompilerProvider {
private static final Logger logger = LoggerFactory.getLogger(JavaCompilerProvider.class);
private static JavaCompilerProvider sInstance;
private final Map<ModuleProject, JavaCompilerService> mCompilers = new ConcurrentHashMap<>();

private JavaCompilerProvider() {}

@NonNull
public static JavaCompilerService get(ModuleProject module) {
return JavaCompilerProvider.getInstance().forModule(module);
}

public static JavaCompilerProvider getInstance() {
if (sInstance == null) {
sInstance = new JavaCompilerProvider();
}

return sInstance;
}

/**
* Iterate over all available {@link JavaCompilerService} instances to perform given {@code action}
* function and return the result of the function.
*
* @param action The function to consume the {@link JavaCompilerService} instances and produce a result.
* The function can return {@code null} to indicate that no result was produced for the
* provided element. If the function returns a non-null value, the iteration is stopped
* and the non-null result is returned. If the function returns {@code null} for all
* elements, then {@code null} is returned.
* @return The result of the action.
* @param <T> The type of the result produced by the given function.
*/
@Nullable
public synchronized <T> T find(Function<JavaCompilerService, T> action) {
logger.debug("find from {} compiler services", mCompilers.size());
for (JavaCompilerService service : mCompilers.values()) {
final var result = action.apply(service);
if (result != null) {
return result;
}
}
return null;
}

@NonNull
public synchronized JavaCompilerService forModule(ModuleProject module) {
// A module instance is set to the compiler only in case the project is initialized or
// this method was called with other module instance.
final JavaCompilerService cached = mCompilers.get(module);
if (cached != null && cached.getModule() != null) {
return cached;
}

final JavaCompilerService newInstance = new JavaCompilerService(module);
mCompilers.put(module, newInstance);

return newInstance;
}

// TODO This currently destroys all the compiler instances
// We must have a method to destroy only the required instance in
// JavaLanguageServer.handleFailure(LSPFailure)
public synchronized void destroy() {
for (final JavaCompilerService compiler : mCompilers.values()) {
compiler.destroy();
}
mCompilers.clear();
}
private static final Logger logger = LoggerFactory.getLogger(JavaCompilerProvider.class);
private static JavaCompilerProvider sInstance;

/**
* The compiler for {@code file}, per {@link #get(ModuleProject, Path)}, or null when no module holds it or it is outside every source directory of its module's selected variant.
*/
@Nullable
public static JavaCompilerService forFile(@NonNull File file) {
return forFile(file.toPath());
}

/** See {@link #forFile(File)}. */
@Nullable
public static JavaCompilerService forFile(@NonNull Path file) {
final ModuleProject module = IProjectManager.getInstance().findModuleForFile(file, false);
return module == null ? null : get(module, file);
}

/** The compiler for {@code module}'s main sources. Use {@link #get(ModuleProject, Path)} for a file that may be a test. */
@NonNull
public static JavaCompilerService get(ModuleProject module) {
return JavaCompilerProvider.getInstance().forModule(module, ArtifactScope.Main.INSTANCE);
}

/** See {@link #get(ModuleProject, Path)}. */
@NonNull
public static JavaCompilerService get(@NonNull ModuleProject module, @NonNull File file) {
return get(module, file.toPath());
}

/** The compiler for the scope of {@code module} that holds {@code file}. */
@NonNull
public static JavaCompilerService get(@NonNull ModuleProject module, @NonNull Path file) {
return JavaCompilerProvider.getInstance().forModule(module, module.artifactScopeOf(file));
}

public static JavaCompilerProvider getInstance() {
if (sInstance == null) {
sInstance = new JavaCompilerProvider();
}

return sInstance;
}

// One compiler per module and test scope: each compiles against its own source path and classpath.
private final Map<Key, JavaCompilerService> mCompilers = new ConcurrentHashMap<>();

private JavaCompilerProvider() {}

// TODO This currently destroys all the compiler instances
// We must have a method to destroy only the required instance in
// JavaLanguageServer.handleFailure(LSPFailure)
public synchronized void destroy() {
for (final JavaCompilerService compiler : mCompilers.values()) {
compiler.destroy();
}
mCompilers.clear();
}

/**
* Iterate over all available {@link JavaCompilerService} instances to perform given {@code action} function and return the result of the function.
*
* @param action
* The function to consume the {@link JavaCompilerService} instances and produce a result. The function can return {@code null} to indicate that no result was produced for the provided element. If the function returns a non-null value, the iteration is stopped and the non-null result is returned. If the function returns {@code null} for all elements, then {@code null} is returned.
* @return The result of the action.
* @param <T>
* The type of the result produced by the given function.
*/
@Nullable
public synchronized <T> T find(Function<JavaCompilerService, T> action) {
logger.debug("find from {} compiler services", mCompilers.size());
for (JavaCompilerService service : mCompilers.values()) {
final var result = action.apply(service);
if (result != null) {
return result;
}
}
return null;
}

/** The compiler for {@code module}'s {@code scope} sources. */
@NonNull
public synchronized JavaCompilerService forModule(ModuleProject module, @NonNull ArtifactScope scope) {
// A module instance is set to the compiler only in case the project is initialized or
// this method was called with other module instance.
final Key key = new Key(module, scope);
final JavaCompilerService cached = mCompilers.get(key);
if (cached != null && cached.getModule() != null) {
return cached;
}

final JavaCompilerService newInstance = new JavaCompilerService(module, scope);
mCompilers.put(key, newInstance);

return newInstance;
}

/** Invalidates the cached compiles of {@code module}'s other scopes that read {@code changed}'s sources. */
public void invalidateScopesSeeing(@NonNull ModuleProject module, @NonNull ArtifactScope changed) {
mCompilers.forEach((key, compiler) -> {
if (key.module() == module && !key.scope().equals(changed) && key.scope().sees(changed)) {
Comment thread
itsaky-adfa marked this conversation as resolved.
Resolved
compiler.invalidateCompile();
}
});
}

private record Key(ModuleProject module, @NonNull ArtifactScope scope) {}
}
Original file line number Diff line number Diff line change
Expand Up @@ -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() {
Expand All @@ -369,8 +369,10 @@ class JavaLanguageServer : ILanguageServer {
getInstance()
.findModuleForFile(event.changedFile)
if (module != null) {
val compiler = JavaCompilerProvider.get(module)
compiler.onDocumentChange(event)
val changedScope = module.artifactScopeOf(event.changedFile)
JavaCompilerProvider.getInstance().forModule(module, changedScope).onDocumentChange(event)
// Scopes that compile against the changed one (tests against main or fixtures) are stale now.
JavaCompilerProvider.getInstance().invalidateScopesSeeing(module, changedScope)
}
startOrRestartAnalyzeTimer()
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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())
}
}

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

Expand Down Expand Up @@ -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<CodeActionItem>()

for (index in result.rewrites.indices) {
Expand Down
Loading
Loading