List and cache bootstrap classes once ProjectManager is registered

This commit is contained in:
Akash Yadav
2022-07-06 22:29:23 +05:30
parent 0910df73e1
commit 8d2f2f2b02
5 changed files with 119 additions and 59 deletions
@@ -26,6 +26,7 @@ import com.itsaky.androidide.projects.api.ModuleProject
import com.itsaky.androidide.projects.api.Project
import com.itsaky.androidide.projects.builder.BuildService
import com.itsaky.androidide.projects.models.ActiveDocument
import com.itsaky.androidide.projects.util.BootstrapClassesProvider
import com.itsaky.androidide.projects.util.ProjectTransformer
import com.itsaky.androidide.tooling.api.IProject
import com.itsaky.androidide.utils.ILogger
@@ -37,6 +38,7 @@ import java.io.StringReader
import java.nio.file.Files
import java.nio.file.Path
import java.time.Instant
import java.util.concurrent.*
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode.BACKGROUND
@@ -257,6 +259,13 @@ object ProjectManager : EventReceiver {
////// TODO Subscribe to file creation/deletion/rename events and update source map //////
//////////////////////////////////////////////////////////////////////////////////////////
override fun register() {
super.register()
// Make sure we list and store the bootstrap classes
CompletableFuture.runAsync { BootstrapClassesProvider.bootstrapClasses() }
}
@Subscribe(threadMode = BACKGROUND)
@Suppress("unused")
fun onDocumentOpen(event: DocumentOpenEvent) {
@@ -0,0 +1,104 @@
/*
* 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 <https://www.gnu.org/licenses/>.
*/
package com.itsaky.androidide.projects.util;
import androidx.annotation.Nullable;
import com.itsaky.androidide.utils.ILogger;
import org.jetbrains.annotations.Contract;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Method;
import java.net.URI;
import java.nio.file.FileSystem;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.util.Collections;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
/**
* Provides class names from the bootstrap classpath (i.e. android.jar).
*
* @author Akash Yadav
*/
public class BootstrapClassesProvider {
private static Set<String> sCachedClasses;
private static final ILogger LOG = ILogger.newInstance("BootstrapClassesProvider");
public static Set<String> bootstrapClasses() {
if (sCachedClasses != null && !sCachedClasses.isEmpty()) {
return sCachedClasses;
}
final var start = System.currentTimeMillis();
sCachedClasses = new HashSet<>();
try {
final var fs = getJRTFileSystem();
if (fs == null) {
LOG.error("Unable to create JRT FileSystem instance");
return sCachedClasses;
}
final var javaBase = fs.getPath("/modules/java.base/");
try (final var stream = Files.walk(javaBase)) {
final var it = stream.iterator();
while (it.hasNext()) {
final var classFile = it.next();
final String relative = javaBase.relativize(classFile).toString();
if (relative.endsWith(".class") && !relative.contains("$")) {
final String trim = relative.substring(0, relative.length() - ".class".length());
final String qualifiedName = trim.replace(File.separatorChar, '.');
sCachedClasses.add(qualifiedName);
}
}
LOG.info("Found", sCachedClasses.size(), "classes in bootstrap classpath");
} catch (IOException io) {
LOG.error("An error occurred while listing classes from bootstrap classpath", io);
}
} catch (Throwable err) {
LOG.error("Unable to find classes from bootstrap classpath", err);
}
return sCachedClasses;
}
@Nullable
@Contract(" -> new")
private static FileSystem getJRTFileSystem() throws Exception {
final URI uri = URI.create("jrt:/");
try {
// Tests run on the JVM, so we cannot directly access JRTFileSystemProvider
// But this method will work
return FileSystems.getFileSystem(uri);
} catch (Throwable th) {
// When on ART, JRT file system is not available
// So we create an instance of the FS manually
final Class<?> klass = Class.forName("jdk.internal.jrtfs.JrtFileSystemProvider");
final Method newFs = klass.getMethod("newFileSystem", URI.class, Map.class);
newFs.setAccessible(true);
return (FileSystem) newFs.invoke(klass.newInstance(), uri, Collections.emptyMap());
}
}
}
@@ -29,12 +29,12 @@ import com.itsaky.androidide.lsp.java.models.CompilationRequest;
import com.itsaky.androidide.lsp.java.parser.ParseTask;
import com.itsaky.androidide.lsp.java.parser.Parser;
import com.itsaky.androidide.lsp.java.utils.Extractors;
import com.itsaky.androidide.lsp.java.utils.ScanClassPath;
import com.itsaky.androidide.lsp.java.visitors.FindTypeDeclarations;
import com.itsaky.androidide.models.Range;
import com.itsaky.androidide.projects.ProjectManager;
import com.itsaky.androidide.projects.api.ModuleProject;
import com.itsaky.androidide.projects.models.ActiveDocument;
import com.itsaky.androidide.projects.util.BootstrapClassesProvider;
import com.itsaky.androidide.projects.util.Cache;
import com.itsaky.androidide.projects.util.SourceClassTrie;
import com.itsaky.androidide.projects.util.StringSearch;
@@ -76,9 +76,9 @@ public class JavaCompilerService implements CompilerProvider {
private static final Cache<Void, List<String>> cacheContainsType = new Cache<>();
private static final ILogger LOG = ILogger.newInstance("JavaCompilerService");
protected final ScanClassPath classPathScanner = new ScanClassPath();
protected final Set<Path> classPath;
protected final Set<String> jdkClasses = classPathScanner.jdkTopLevelClasses(), classPathClasses;
protected final Set<String> classPathClasses;
protected final Set<String> jdkClasses = BootstrapClassesProvider.bootstrapClasses();
protected final List<Diagnostic<? extends JavaFileObject>> diagnostics = new ArrayList<>();
protected final Map<JavaFileObject, Long> cachedModified = new HashMap<>();
protected final Cache<Void, List<String>> cacheFileImports = new Cache<>();
@@ -94,15 +94,16 @@ public class JavaCompilerService implements CompilerProvider {
// It is marked as nullable just for some special cases like tests
public JavaCompilerService(@Nullable ModuleProject module) {
this.module = module;
this.fileManager = new SourceFileManager(module);
if (module == null) {
this.classPath = Collections.unmodifiableSet(Collections.emptySet());
this.classPathClasses = Collections.emptySet();
} else {
this.classPath =
Collections.unmodifiableSet(
module.getCompileClasspaths().stream().map(File::toPath).collect(Collectors.toSet()));
this.classPathClasses = module.compileClasspathClasses.allClassNames();
}
this.classPathClasses = classPathScanner.classPathTopLevelClasses(classPath);
this.fileManager = new SourceFileManager(module);
}
public ModuleProject getModule() {
@@ -82,58 +82,4 @@ public class ScanClassPath {
LOG.info(String.format(Locale.ROOT, "Found %d classes in the java platform", classes.size()));
return classes;
}
@Nullable
@Contract(" -> new")
public FileSystem getJRTFileSystem() throws Exception {
final URI uri = URI.create("jrt:/");
try {
// Tests run on the JVM, so we cannot directly access JRTFileSystemProvider
// But this method will work
return FileSystems.getFileSystem(uri);
} catch (Throwable th) {
// When on ART, JRT file system is not available
// So we create an instance of the FS manually
final Class<?> klass = Class.forName("jdk.internal.jrtfs.JrtFileSystemProvider");
final Method newFs = klass.getMethod("newFileSystem", URI.class, Map.class);
newFs.setAccessible(true);
return (FileSystem) newFs.invoke(klass.newInstance(), uri, Collections.emptyMap());
}
}
public Set<String> classPathTopLevelClasses(Set<Path> classPath) {
LOG.info(
String.format(
Locale.getDefault(),
"Searching for top-level classes in %d classpath locations",
classPath.size()));
URL[] urls = classPath.stream().map(this::toUrl).toArray(URL[]::new);
ClassLoader classLoader = new URLClassLoader(urls, null);
ClassPath scanner;
try {
scanner = ClassPath.from(classLoader);
} catch (IOException e) {
throw new RuntimeException(e);
}
Set<String> classes = new HashSet<>();
for (ClassPath.ClassInfo c : scanner.getTopLevelClasses()) {
classes.add(c.getName());
}
LOG.info(String.format(Locale.ROOT, "Found %d classes in classpath", classes.size()));
return classes;
}
private URL toUrl(@NonNull Path p) {
try {
return p.toUri().toURL();
} catch (MalformedURLException e) {
throw new RuntimeException(e);
}
}
}