Skip to content
Closed
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,132 @@

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.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;
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. */
@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, 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() {
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;
}

@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 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 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) {}
}
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,12 @@ 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)
if (compiler.scope == null) {
// The test scopes compile against main, so their cached compiles are stale now.
JavaCompilerProvider.getInstance().invalidateTestScopes(module)

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

MINOR: invalidateTestScopes marks only the edited file's own module, but test scopes also read other modules' sources through getTestCompileSourceDirectories.

With testImplementation(project(":lib")), editing Lib.java resolves to :lib, so :app's cached unit-test compile is reused and diagnostics in FooTest show the old Lib API until FooTest changes. Not a regression: main compilers reading dependency modules already have this gap.

Invalidate every compiler whose source path includes the edited module, or list it under Limitations.

}
}
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())

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

MINOR: The defect is in AddImportTest.kt:119, outside this diff: its guard verify(exactly = 0) { JavaCompilerProvider.get(any()) } matches only the one-argument overload, and this PR moved every action off that overload.

If prepare() later calls get(module, file) or forFile(file), which is the main-thread index I/O the test exists to catch, the verify still passes.

Verify get(any<ModuleProject>(), any<File>()), get(any(), any<Path>()) and forFile(any()) as well.

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