From b0b16eb5aa66a3ccd8c73c852561d5076ed667b6 Mon Sep 17 00:00:00 2001 From: Wadamzmail Date: Wed, 25 Nov 2026 10:35:57 +0200 Subject: [PATCH] update --- .../androidide/zipfs2/ZipFileSystem.java | 141 ++- .../androidide/zipfs2/listing/JarListing.java | 702 +++++++++++ .../zipfs2/listing/JarListingCache.java | 256 ++++ core/app/proguard-rules.pro | 5 + .../activities/editor/BaseEditorActivity.kt | 7 +- .../editor/EditorHandlerActivity.kt | 15 +- .../editor/ProjectHandlerActivity.kt | 74 +- .../editor/ProjectHandlerActivity.kt.bak | 1058 +++++++++++++++++ .../activities/editor/ProjectSessionCloser.kt | 66 + .../services/builder/ToolingMessageTap.kt | 45 + .../services/builder/ToolingServerRunner.kt | 14 +- .../androidide/memprof/AllocationSampler.kt | 21 +- .../mutwakil/androidide/memprof/MemprofLog.kt | 71 ++ .../androidide/memprof/MemprofReceiver.kt | 21 +- .../androidide/memprof/MemprofReportWriter.kt | 7 +- .../androidide/memprof/MemprofSession.kt | 4 +- .../memprof/MessageBoundaryInputStream.kt | 98 ++ .../memprof/ProfileableMemprofSink.kt | 17 +- .../androidide/memprof/ToolingMessageProbe.kt | 201 ++++ .../androidide/lsp/api/ILanguageServer.kt | 6 +- .../editor/ui/BaseEditorWindow.java | 25 +- .../androidide/editor/ui/IDEEditor.kt | 15 + .../editor/ui/SignatureHelpWindow.java | 16 +- .../editor/ui/TracingEditorRenderer.kt | 774 ++++++++---- gradle/libs.versions.toml | 18 +- .../javac/services/fs/CachedJarFileSystem.kt | 83 +- .../fs/CachingJarFileSystemProvider.kt | 104 +- .../services/fs/JarPackageProviderImpl.kt | 10 +- .../javac/services/fs/ListingPackageMap.kt | 106 ++ .../lsp/java/JavaCompilerProvider.java | 163 ++- .../androidide/lsp/java/JavaLanguageServer.kt | 32 +- .../lsp/java/actions/BaseJavaCodeAction.kt | 2 +- .../lsp/java/actions/FieldBasedAction.kt | 2 +- .../actions/diagnostics/AddImportAction.kt | 4 +- .../actions/diagnostics/AddThrowsAction.kt | 6 +- .../diagnostics/CreateMissingMethodAction.kt | 6 +- .../actions/diagnostics/FieldToBlockAction.kt | 6 +- .../actions/diagnostics/RemoveClassAction.kt | 6 +- .../actions/diagnostics/RemoveMethodAction.kt | 6 +- .../diagnostics/RemoveUnusedThrowsAction.kt | 6 +- .../SuppressUncheckedWarningAction.kt | 6 +- .../diagnostics/VariableToStatementAction.kt | 6 +- .../generators/GenerateConstructorAction.kt | 6 +- .../GenerateMissingConstructorAction.kt | 6 +- .../GenerateSettersAndGettersAction.kt | 6 +- .../GenerateToStringMethodAction.kt | 6 +- .../OverrideSuperclassMethodsAction.kt | 6 +- .../lsp/java/compiler/ClasspathTypeLookup.kt | 7 +- .../lsp/java/compiler/CompileBatch.java | 8 +- .../java/compiler/JavaCompilerService.java | 64 +- .../lsp/java/compiler/SourceFileManager.java | 431 +++---- .../lsp/java/edits/AdvancedJavaEditHandler.kt | 4 +- .../java/providers/JavaDiagnosticProvider.kt | 237 ++-- .../completion/ImportCompletionProvider.kt | 2 +- lsp/indexing/build.gradle.kts | 1 + .../indexing/IndexSessionLifetime.kt | 21 + .../codeonthego/indexing/SQLiteIndex.kt | 78 +- .../codeonthego/indexing/api/Index.kt | 4 + .../indexing/service/IndexRegistry.kt | 119 +- .../service/IndexRegistryClosedException.kt | 11 + .../service/IndexingServiceManager.kt | 18 +- .../indexing/util/BackgroundIndexer.kt | 17 +- .../indexing/jvm/JarIndexingService.kt | 5 +- .../indexing/jvm/JvmSymbolIndex.kt | 8 + .../indexing/jvm/KtFileMetadataIndex.kt | 74 +- lsp/kotlin/build.gradle.kts | 1 + .../androidide/lsp/kotlin/CompilerSession.kt | 169 +++ .../lsp/kotlin/KotlinLanguageServer.kt | 252 ++-- .../AbstractCompilationEnvironment.kt | 141 ++- .../kotlin/compiler/CompilationEnvironment.kt | 161 +-- .../lsp/kotlin/compiler/Compiler.kt | 17 +- .../KotlinApplicationEnvironmentPin.kt | 25 +- .../lsp/kotlin/compiler/KotlinModuleLayout.kt | 161 +++ .../lsp/kotlin/compiler/KotlinProjectModel.kt | 48 +- .../lsp/kotlin/compiler/ReadWriteLock.kt | 28 +- .../lsp/kotlin/compiler/WorkspaceExts.kt | 96 +- .../lsp/kotlin/compiler/index/IndexCommand.kt | 2 +- .../lsp/kotlin/compiler/index/IndexWorker.kt | 34 +- .../kotlin/compiler/index/KtSymbolIndex.kt | 54 +- .../kotlin/compiler/index/PackageFileCache.kt | 94 ++ .../kotlin/compiler/index/ScanningWorker.kt | 2 +- .../compiler/index/SourceFileIndexer.kt | 58 +- .../compiler/modules/AbstractKtModule.kt | 4 +- .../lsp/kotlin/compiler/modules/KtFileExts.kt | 2 + .../compiler/modules/KtLibraryModule.kt | 21 +- .../kotlin/compiler/modules/KtSourceModule.kt | 62 +- .../compiler/modules/LibraryRootsScope.kt | 33 + .../registrar/AnalysisApiServiceProviders.kt | 2 +- .../compiler/services/DeclarationsProvider.kt | 91 +- .../services/DirectInheritorsProvider.kt | 73 +- .../services/ProjectStructureProvider.kt | 46 +- .../compiler/services/TopLevelDeclarations.kt | 72 ++ .../compiler/vfs/ListingJarFileSystem.kt | 111 ++ .../kotlin/compiler/vfs/ListingJarHandler.kt | 247 ++++ .../compiler/vfs/ListingJarVirtualFile.kt | 76 ++ .../kotlin/completion/KotlinCompletions.kt | 19 +- .../completion/KotlinSnippetRepository.kt | 14 +- .../diagnostic/KotlinDiagnosticProvider.kt | 43 +- .../lsp/kotlin/format/KotlinCodeFormatter.kt | 24 +- .../lsp/kotlin/navigation/FindUsages.kt | 22 +- .../signaturehelp/KotlinSignatureHelp.kt | 4 +- .../lsp/kotlin/utils/ContextResolver.kt | 108 +- .../kotlin/utils/SymbolVisibilityChecker.kt | 17 +- .../lsp/kotlin/CompilerSessionTest.kt | 362 ++++++ .../lsp/kotlin/VariantSourceSetsTest.kt | 116 ++ .../kotlin/compiler/CollectKtModulesTest.kt | 226 +++- .../CompilationEnvironmentCloseTest.kt | 95 ++ .../kotlin/compiler/KotlinModuleLayoutTest.kt | 90 ++ .../compiler/KotlinProjectModelIndexTest.kt | 26 + .../index/InBodyEditRedeclarationTest.kt | 82 ++ .../compiler/index/IndexWorkerDisposalTest.kt | 1 + .../compiler/index/IndexWorkerOpenFileTest.kt | 69 ++ .../index/IndexWorkerPhaseLifecycleTest.kt | 65 +- .../compiler/index/KotlinFileRemovalTest.kt | 118 ++ .../compiler/index/KtSymbolIndexCloseTest.kt | 68 ++ .../compiler/index/PackageFileCacheTest.kt | 194 +++ .../compiler/index/SourceFileIndexerTest.kt | 86 +- .../modules/KtLibraryModuleScopeTest.kt | 121 ++ .../compiler/modules/LibraryRootsScopeTest.kt | 73 ++ .../compiler/services/ClassLikeWithIdTest.kt | 55 + .../services/DeclarationStalenessTest.kt | 161 +++ .../services/DirectInheritorsProviderTest.kt | 82 ++ .../services/PrivateTopLevelResolutionTest.kt | 44 + .../TopLevelDeclarationsEquivalenceTest.kt | 114 ++ .../compiler/vfs/ListingJarFileSystemTest.kt | 373 ++++++ .../kotlin/fixtures/GradleProjectFixtures.kt | 176 +++ .../lsp/kotlin/fixtures/KtLspTest.kt | 10 +- .../kotlin/fixtures/KtLspTestEnvironment.kt | 40 +- .../lsp/kotlin/fixtures/KtLspTestRule.kt | 4 + .../lsp/kotlin/fixtures/TestKtSourceModule.kt | 37 +- .../kotlin/fixtures/TestSourceModuleSpec.kt | 3 + .../kotlin/fixtures/VariantProjectFixtures.kt | 114 ++ .../kotlin/navigation/TestSourceScopesTest.kt | 91 ++ .../utils/SymbolVisibilityCheckerTest.kt | 348 +++--- .../kotlin-analysis-api/build.gradle.kts | 4 +- .../projects/models/ArtifactScope.kt | 119 ++ .../src/main/proto/android.proto | 34 +- .../androidide/projects/ProjectManagerImpl.kt | 67 +- .../androidide/projects/api/AndroidModule.kt | 130 +- .../androidide/projects/api/JavaModule.kt | 293 +++-- .../androidide/projects/api/ModuleProject.kt | 190 ++- .../androidide/projects/api/Workspace.kt | 11 +- .../classpath/JarFsClasspathReader.kt | 159 +-- .../tooling/api/sync/ProjectSyncHelper.kt | 2 +- .../tooling/api/util/ToolingApiLauncher.kt | 6 +- .../events/task/TaskOperationDescriptor.kt | 58 +- .../transform/TransformOperationDescriptor.kt | 75 +- .../tooling/impl/progress/EventTransformer.kt | 791 ++++++------ .../tooling/impl/serial/AndroidProjectExts.kt | 10 +- .../tooling/impl/serial/ScopedComponents.kt | 145 +++ .../mutwakil/androidide/memprof/Memprof.kt | 13 +- .../androidide/memprof/MemprofLines.kt | 14 +- .../androidide/memprof/MemprofReport.kt | 6 +- .../androidide/utils/DocumentUtils.java | 74 +- 154 files changed, 10911 insertions(+), 2538 deletions(-) create mode 100644 composite-builds/build-deps/java-compiler/src/main/java/dev/mutwakil/androidide/zipfs2/listing/JarListing.java create mode 100644 composite-builds/build-deps/java-compiler/src/main/java/dev/mutwakil/androidide/zipfs2/listing/JarListingCache.java create mode 100644 core/app/src/main/java/dev/mutwakil/androidide/activities/editor/ProjectHandlerActivity.kt.bak create mode 100644 core/app/src/main/java/dev/mutwakil/androidide/activities/editor/ProjectSessionCloser.kt create mode 100644 core/app/src/main/java/dev/mutwakil/androidide/services/builder/ToolingMessageTap.kt create mode 100644 core/app/src/profileable/java/dev/mutwakil/androidide/memprof/MemprofLog.kt create mode 100644 core/app/src/profileable/java/dev/mutwakil/androidide/memprof/MessageBoundaryInputStream.kt create mode 100644 core/app/src/profileable/java/dev/mutwakil/androidide/memprof/ToolingMessageProbe.kt create mode 100644 java/javac-services/src/main/java/dev/mutwakil/androidide/javac/services/fs/ListingPackageMap.kt create mode 100644 lsp/indexing/src/main/kotlin/org/appdevforall/codeonthego/indexing/IndexSessionLifetime.kt create mode 100644 lsp/indexing/src/main/kotlin/org/appdevforall/codeonthego/indexing/service/IndexRegistryClosedException.kt create mode 100644 lsp/kotlin/src/main/java/dev/mutwakil/androidide/lsp/kotlin/CompilerSession.kt create mode 100644 lsp/kotlin/src/main/java/dev/mutwakil/androidide/lsp/kotlin/compiler/KotlinModuleLayout.kt create mode 100644 lsp/kotlin/src/main/java/dev/mutwakil/androidide/lsp/kotlin/compiler/index/PackageFileCache.kt create mode 100644 lsp/kotlin/src/main/java/dev/mutwakil/androidide/lsp/kotlin/compiler/modules/LibraryRootsScope.kt create mode 100644 lsp/kotlin/src/main/java/dev/mutwakil/androidide/lsp/kotlin/compiler/services/TopLevelDeclarations.kt create mode 100644 lsp/kotlin/src/main/java/dev/mutwakil/androidide/lsp/kotlin/compiler/vfs/ListingJarFileSystem.kt create mode 100644 lsp/kotlin/src/main/java/dev/mutwakil/androidide/lsp/kotlin/compiler/vfs/ListingJarHandler.kt create mode 100644 lsp/kotlin/src/main/java/dev/mutwakil/androidide/lsp/kotlin/compiler/vfs/ListingJarVirtualFile.kt create mode 100644 lsp/kotlin/src/test/java/dev/mutwakil/androidide/lsp/kotlin/CompilerSessionTest.kt create mode 100644 lsp/kotlin/src/test/java/dev/mutwakil/androidide/lsp/kotlin/VariantSourceSetsTest.kt create mode 100644 lsp/kotlin/src/test/java/dev/mutwakil/androidide/lsp/kotlin/compiler/CompilationEnvironmentCloseTest.kt create mode 100644 lsp/kotlin/src/test/java/dev/mutwakil/androidide/lsp/kotlin/compiler/KotlinModuleLayoutTest.kt create mode 100644 lsp/kotlin/src/test/java/dev/mutwakil/androidide/lsp/kotlin/compiler/KotlinProjectModelIndexTest.kt create mode 100644 lsp/kotlin/src/test/java/dev/mutwakil/androidide/lsp/kotlin/compiler/index/InBodyEditRedeclarationTest.kt create mode 100644 lsp/kotlin/src/test/java/dev/mutwakil/androidide/lsp/kotlin/compiler/index/IndexWorkerOpenFileTest.kt create mode 100644 lsp/kotlin/src/test/java/dev/mutwakil/androidide/lsp/kotlin/compiler/index/KotlinFileRemovalTest.kt create mode 100644 lsp/kotlin/src/test/java/dev/mutwakil/androidide/lsp/kotlin/compiler/index/KtSymbolIndexCloseTest.kt create mode 100644 lsp/kotlin/src/test/java/dev/mutwakil/androidide/lsp/kotlin/compiler/index/PackageFileCacheTest.kt create mode 100644 lsp/kotlin/src/test/java/dev/mutwakil/androidide/lsp/kotlin/compiler/modules/KtLibraryModuleScopeTest.kt create mode 100644 lsp/kotlin/src/test/java/dev/mutwakil/androidide/lsp/kotlin/compiler/modules/LibraryRootsScopeTest.kt create mode 100644 lsp/kotlin/src/test/java/dev/mutwakil/androidide/lsp/kotlin/compiler/services/ClassLikeWithIdTest.kt create mode 100644 lsp/kotlin/src/test/java/dev/mutwakil/androidide/lsp/kotlin/compiler/services/DeclarationStalenessTest.kt create mode 100644 lsp/kotlin/src/test/java/dev/mutwakil/androidide/lsp/kotlin/compiler/services/DirectInheritorsProviderTest.kt create mode 100644 lsp/kotlin/src/test/java/dev/mutwakil/androidide/lsp/kotlin/compiler/services/PrivateTopLevelResolutionTest.kt create mode 100644 lsp/kotlin/src/test/java/dev/mutwakil/androidide/lsp/kotlin/compiler/services/TopLevelDeclarationsEquivalenceTest.kt create mode 100644 lsp/kotlin/src/test/java/dev/mutwakil/androidide/lsp/kotlin/compiler/vfs/ListingJarFileSystemTest.kt create mode 100644 lsp/kotlin/src/test/java/dev/mutwakil/androidide/lsp/kotlin/fixtures/GradleProjectFixtures.kt create mode 100644 lsp/kotlin/src/test/java/dev/mutwakil/androidide/lsp/kotlin/fixtures/VariantProjectFixtures.kt create mode 100644 lsp/kotlin/src/test/java/dev/mutwakil/androidide/lsp/kotlin/navigation/TestSourceScopesTest.kt create mode 100644 subprojects/project-models/src/main/java/dev/mutwakil/androidide/projects/models/ArtifactScope.kt create mode 100644 tooling/impl/src/main/java/dev/mutwakil/androidide/tooling/impl/serial/ScopedComponents.kt diff --git a/composite-builds/build-deps/java-compiler/src/main/java/dev/mutwakil/androidide/zipfs2/ZipFileSystem.java b/composite-builds/build-deps/java-compiler/src/main/java/dev/mutwakil/androidide/zipfs2/ZipFileSystem.java index 426cd56240..6596ccb7dd 100644 --- a/composite-builds/build-deps/java-compiler/src/main/java/dev/mutwakil/androidide/zipfs2/ZipFileSystem.java +++ b/composite-builds/build-deps/java-compiler/src/main/java/dev/mutwakil/androidide/zipfs2/ZipFileSystem.java @@ -58,6 +58,8 @@ import java.util.zip.InflaterInputStream; import java.util.zip.ZipException; +import dev.mutwakil.androidide.zipfs2.listing.JarListing; + import static java.lang.Boolean.TRUE; import static java.nio.file.StandardCopyOption.COPY_ATTRIBUTES; import static java.nio.file.StandardCopyOption.REPLACE_EXISTING; @@ -94,8 +96,8 @@ public class ZipFileSystem extends FileSystem { // METHOD_DEFLATED otherwise protected ZipFileSystem(ZipFileSystemProvider provider, - Path zfpath, - Map env) throws IOException { + Path zfpath, + Map env) throws IOException { // default encoding for name/comment String nameEncoding = env.containsKey("encoding") ? (String) env.get("encoding") : "UTF-8"; @@ -132,6 +134,35 @@ protected ZipFileSystem(ZipFileSystemProvider provider, } this.provider = provider; this.zfpath = zfpath; + this.listing = null; + } + + /** + * Creates a read-only file system that looks entries up in the given listing instead of + * indexing the JAR itself. + * + *

The channel must be open on the same file the listing was read from; this file system + * takes ownership of it. + */ + protected ZipFileSystem(ZipFileSystemProvider provider, + Path zfpath, + JarListing listing, + SeekableByteChannel ch) { + this.noExtt = false; + this.useTempFile = false; + this.forceEnd64 = false; + this.defaultMethod = METHOD_DEFLATED; + this.readOnly = true; + // JarListing keeps names as raw CEN bytes; ZipPath must encode lookups the same way. + this.zc = ZipCoder.get("UTF-8"); + this.rootdir = new ZipPath(this, new byte[]{'/'}); + this.ch = ch; + this.cen = null; + // JarListing offsets already include any bytes before the archive. + this.locpos = 0; + this.listing = listing; + this.provider = provider; + this.zfpath = zfpath; } // returns true if there is a name=true/"true" setting in env @@ -285,7 +316,7 @@ public void close() throws IOException { try { sync(); closeChannelQuietly(ch); // close the ch just in case no update - // and sync didn't close the ch + // and sync didn't close the ch } finally { endWrite(); } @@ -417,8 +448,11 @@ boolean isDirectory(byte[] path) // returns the list of child paths of "path" Iterator iteratorOf(ZipPath dir, - DirectoryStream.Filter filter) + DirectoryStream.Filter filter) throws IOException { + if (listing != null) { + return listingIteratorOf(dir, filter); + } beginWrite(); // iteration of inodes needs exclusive lock try { ensureOpen(); @@ -450,6 +484,31 @@ Iterator iteratorOf(ZipPath dir, } } + private Iterator listingIteratorOf(ZipPath dir, + DirectoryStream.Filter filter) + throws IOException { + beginRead(); // the listing is immutable + try { + ensureOpen(); + byte[] path = dir.getResolvedPath(); + int i = listing.find(path); + if (i < 0) { + throw new NotDirectoryException(getString(path)); + } + List list = new ArrayList<>(); + for (int child = listing.firstChild(i); child != -1; child = listing.nextSibling(child)) { + ZipPath childPath = new ZipPath(this, listing.nameBytes(child), true); + ZipPath zpath = dir.resolve(childPath.getFileName()); + if (filter == null || filter.accept(zpath)) { + list.add(zpath); + } + } + return list.iterator(); + } finally { + endRead(); + } + } + void createDirectory(byte[] dir, FileAttribute... attrs) throws IOException { checkWritable(); @@ -676,8 +735,8 @@ private int getCompressMethod() { // file on the default file system and create a FileChannel on top of // it. SeekableByteChannel newByteChannel(byte[] path, - Set options, - FileAttribute... attrs) + Set options, + FileAttribute... attrs) throws IOException { checkOptions(options); if (options.contains(StandardOpenOption.WRITE) @@ -815,8 +874,8 @@ public byte[] readNBytes(InputStream is, int len) throws IOException { // copy the entry data into it if the entry exists, and then create a // FileChannel on top of it. FileChannel newFileChannel(byte[] path, - Set options, - FileAttribute... attrs) + Set options, + FileAttribute... attrs) throws IOException { checkOptions(options); final boolean forWrite = (options.contains(StandardOpenOption.WRITE) @@ -894,13 +953,13 @@ public void force(boolean metaData) } public long transferTo(long position, long count, - WritableByteChannel target) + WritableByteChannel target) throws IOException { return fch.transferTo(position, count, target); } public long transferFrom(ReadableByteChannel src, - long position, long count) + long position, long count) throws IOException { return fch.transferFrom(src, position, count); } @@ -925,7 +984,7 @@ public int write(ByteBuffer src, long position) } public MappedByteBuffer map(MapMode mode, - long position, long size) + long position, long size) throws IOException { throw new UnsupportedOperationException(); } @@ -1046,6 +1105,8 @@ private final void endRead() { private volatile boolean isOpen = true; private final SeekableByteChannel ch; // channel to the zipfile final byte[] cen; // CEN & ENDHDR + /* Replaces cen and inodes for read-only JARs; null otherwise. */ + private final JarListing listing; private END end; private long locpos; // position of first LOC header (usually 0) @@ -1323,8 +1384,8 @@ private void update(Entry e) { // copy over the whole LOC entry (header if necessary, data and ext) from // old zip to the new one. private long copyLOCEntry(Entry e, boolean updateHeader, - OutputStream os, - long written, byte[] buf) + OutputStream os, + long written, byte[] buf) throws IOException { long locoff = e.locoff; // where to read e.locoff = written; // update the e.locoff with new value @@ -1538,14 +1599,45 @@ private PosixFileAttributes getPosixAttributes(Path path) throws IOException { } } + /** + * Returns how many index nodes this file system keeps in memory: 0 when it reads through a + * {@link JarListing}. + */ + int retainedIndexNodeCount() { + beginRead(); + try { + return inodes == null ? 0 : inodes.size(); + } finally { + endRead(); + } + } + IndexNode getInode(byte[] path) { if (path == null) { throw new NullPointerException("path"); } + if (listing != null) { + int i = listing.find(path); + if (i < 0) { + return null; + } + // Transient and never used as a map key, so it skips hashing the name. + IndexNode inode = new IndexNode(); + inode.name = path; + inode.isdir = listing.isDirectory(i); + return inode; + } return inodes.get(IndexNode.keyOf(path)); } Entry getEntry(byte[] path) throws IOException { + if (listing != null) { + int i = listing.find(path); + if (i < 0 || listing.localHeaderOffset(i) == -1) { + return null; // absent, or the root or a synthesized directory + } + return new Entry(listing, i); + } IndexNode inode = getInode(path); if (inode instanceof Entry) { return (Entry) inode; @@ -2282,6 +2374,19 @@ static class Entry extends IndexNode implements ZipFileAttributes { this.file = file; } + /* An entry read from a listing has no extra field or comment, so only the DOS time. */ + Entry(JarListing listing, int i) { + name(listing.nameBytes(i)); + this.isdir = listing.isDirectory(i); + this.flag = listing.flag(i); + this.method = listing.method(i); + this.mtime = dosToJavaTime(listing.dosTime(i)); + this.crc = listing.crc(i); + this.csize = listing.compressedSize(i); + this.size = listing.size(i); + this.locoff = listing.localHeaderOffset(i); + } + int version() throws ZipException { if (method == METHOD_DEFLATED) { return 20; @@ -2814,8 +2919,8 @@ private static class ExistingChannelCloser { private final Set streams; ExistingChannelCloser(Path path, - SeekableByteChannel ch, - Set streams) { + SeekableByteChannel ch, + Set streams) { this.path = path; this.ch = ch; this.streams = streams; @@ -2905,19 +3010,19 @@ public boolean equals(Object other) { private boolean arrEquals(byte[] a, int aI, int aT, byte[] b, int bI, int bT) { rangeCheck(a.length, aI, aT); rangeCheck(b.length, bI, bT); - + int aL = aT - aI; int bL = bT - bI; if (aL != bL) { return false; } - + for (int i=0;i. + */ + +package dev.mutwakil.androidide.zipfs2.listing; + +import java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.channels.FileChannel; +import java.nio.charset.StandardCharsets; +import java.nio.file.Path; +import java.nio.file.StandardOpenOption; +import java.util.Arrays; +import java.util.HashMap; +import java.util.Map; +import java.util.zip.ZipException; + +/** + * An immutable, packed index of the entries of one JAR, built from its central directory. + * + *

Entries are identified by an {@code int} index. Index 0 is the root, named {@code "/"}. + * Names are stored like zipfs2's {@code IndexNode}: a leading {@code /}, no trailing {@code /} + * and no {@code //}. Parent directories missing from the archive are synthesized. Storage is a + * handful of primitive arrays, with no per-entry objects. + * + *

Instances are safe for use by multiple threads. + */ +public final class JarListing { + + private static final int ENDHDR = 22; + private static final int END_MAXLEN = 0xFFFF + ENDHDR; + private static final int ZIP64_LOCHDR = 20; + private static final int ZIP64_ENDHDR = 56; + private static final int CENHDR = 46; + private static final long CENSIG = 0x02014b50L; + private static final long ENDSIG = 0x06054b50L; + private static final long ZIP64_LOCSIG = 0x07064b50L; + private static final long ZIP64_ENDSIG = 0x06064b50L; + private static final int ZIP64_EXTID = 0x0001; + private static final long ZIP64_MINVAL = 0xFFFFFFFFL; + private static final int ZIP64_MINVAL32 = 0xFFFF; + private static final int FLAG_ENCRYPTED = 0x01; + private static final int METHOD_STORED = 0; + private static final int METHOD_DEFLATED = 8; + + private static final int KIND_DIRECTORY_BIT = 1 << 16; + private static final int KIND_METHOD_SHIFT = 17; + private static final int KIND_FLAG_MASK = 0xFFFF; + private static final int SYNTHESIZED = 0; + private static final int NARROW_KINDS = 256; + + private static final int OVERFLOW_COMPRESSED = 0; + private static final int OVERFLOW_SIZE = 1; + private static final int OVERFLOW_OFFSET = 2; + private static final int OVERFLOW_FIELDS = 3; + + private final int count; + private final byte[] names; + private final int[] nameOffsets; + private final int[] table; + private final int[] firstChildren; + private final int[] nextSiblings; + + /* Index into kinds[] per entry; 0 marks a directory synthesized for lack of an entry. */ + private final byte[] kindIndex; + private final int[] wideKindIndex; + private final int[] kinds; + private final int[] crcs; + private final int[] compressedSizes; + private final int[] sizes; + private final int[] offsets; + private final int[] dosTimes; + + /* + * Values that do not fit in 32 bits (zip64). The per-entry int holds -1 and the real value is + * found by binary search of overflowEntries. + */ + private final int[] overflowEntries; + private final long[] overflowValues; + + private JarListing(Builder b) { + this.count = b.count; + this.names = Arrays.copyOf(b.names, b.namesUsed); + this.nameOffsets = Arrays.copyOf(b.nameOffsets, count + 1); + this.firstChildren = Arrays.copyOf(b.firstChildren, count); + this.nextSiblings = Arrays.copyOf(b.nextSiblings, count); + if (b.kindCount <= NARROW_KINDS) { + this.kindIndex = new byte[count]; + for (int i = 0; i < count; i++) { + kindIndex[i] = (byte) b.kindIndex[i]; + } + this.wideKindIndex = null; + } else { + this.kindIndex = null; + this.wideKindIndex = Arrays.copyOf(b.kindIndex, count); + } + this.kinds = Arrays.copyOf(b.kinds, b.kindCount); + this.crcs = Arrays.copyOf(b.crcs, count); + this.compressedSizes = Arrays.copyOf(b.compressedSizes, count); + this.sizes = Arrays.copyOf(b.sizes, count); + this.offsets = Arrays.copyOf(b.offsets, count); + this.dosTimes = Arrays.copyOf(b.dosTimes, count); + this.table = buildTable(names, nameOffsets, count); + + this.overflowEntries = new int[b.overflow.size()]; + int slot = 0; + for (int entry : b.overflow.keySet()) { + overflowEntries[slot++] = entry; + } + Arrays.sort(overflowEntries); + this.overflowValues = new long[overflowEntries.length * OVERFLOW_FIELDS]; + for (slot = 0; slot < overflowEntries.length; slot++) { + System.arraycopy(b.overflow.get(overflowEntries[slot]), 0, overflowValues, + slot * OVERFLOW_FIELDS, OVERFLOW_FIELDS); + } + } + + /** + * Reads the central directory of the given JAR in one pass and indexes its entries. + * + * @throws ZipException if the central directory is malformed or the file is not a zip + * @throws IOException if the file cannot be read + */ + public static JarListing read(Path jar) throws IOException { + try (FileChannel ch = FileChannel.open(jar, StandardOpenOption.READ)) { + Directory directory = locateDirectory(ch); + byte[] cen = new byte[(int) directory.length]; + readFully(ch, ByteBuffer.wrap(cen), directory.position); + return new Builder(directory.entryHint, directory.localHeaderBase).parse(cen).finish(); + } + } + + /** Returns the number of entries, including the root and synthesized directories. */ + public int size() { + return count; + } + + /** Returns the index of the entry with the given normalized name, or -1 if absent. */ + public int find(byte[] name) { + return lookup(table, names, nameOffsets, name, 0, name.length); + } + + /** Returns the index of the entry with the given normalized name, or -1 if absent. */ + public int find(String name) { + return find(name.getBytes(StandardCharsets.UTF_8)); + } + + /** Returns whether the entry is a directory, explicit or synthesized. */ + public boolean isDirectory(int i) { + return i == 0 || kindOf(i) == SYNTHESIZED || (kinds[kindOf(i)] & KIND_DIRECTORY_BIT) != 0; + } + + /** Returns the index of the entry's parent directory, or -1 for the root. */ + public int parent(int i) { + if (i == 0) { + return -1; + } + int start = nameOffsets[i]; + int slash = nameOffsets[i + 1] - 1; + while (names[slash] != '/') { + slash--; + } + return slash == start ? 0 : lookup(table, names, nameOffsets, names, start, slash - start); + } + + /** Returns the index of the entry's first child, or -1 if it has none. Child order is unspecified. */ + public int firstChild(int i) { + return firstChildren[i]; + } + + /** Returns the index of the next entry with the same parent, or -1 after the last one. */ + public int nextSibling(int i) { + return nextSiblings[i]; + } + + /** Returns the full normalized name of the entry. */ + public String name(int i) { + return new String(names, nameOffsets[i], nameOffsets[i + 1] - nameOffsets[i], StandardCharsets.UTF_8); + } + + /** Returns the last path segment of the entry's name, or the empty string for the root. */ + public String shortName(int i) { + if (i == 0) { + return ""; + } + int end = nameOffsets[i + 1]; + int slash = end - 1; + while (names[slash] != '/') { + slash--; + } + return new String(names, slash + 1, end - slash - 1, StandardCharsets.UTF_8); + } + + /** Returns a copy of the full normalized name of the entry. */ + public byte[] nameBytes(int i) { + return Arrays.copyOfRange(names, nameOffsets[i], nameOffsets[i + 1]); + } + + /** Returns the compression method of the entry, or 0 for a synthesized directory. */ + public int method(int i) { + return kinds[kindOf(i)] >>> KIND_METHOD_SHIFT; + } + + /** Returns the general purpose bit flag of the entry, or 0 for a synthesized directory. */ + public int flag(int i) { + return kinds[kindOf(i)] & KIND_FLAG_MASK; + } + + /** Returns the CRC-32 of the uncompressed data. */ + public long crc(int i) { + return crcs[i] & 0xFFFFFFFFL; + } + + /** Returns the compressed size in bytes, or 0 for a synthesized directory. */ + public long compressedSize(int i) { + return widen(compressedSizes[i], i, OVERFLOW_COMPRESSED); + } + + /** Returns the uncompressed size in bytes, or 0 for a synthesized directory. */ + public long size(int i) { + return widen(sizes[i], i, OVERFLOW_SIZE); + } + + /** + * Returns the file position of the entry's local header, including any prefix before the + * archive, or -1 for a synthesized directory. + */ + public long localHeaderOffset(int i) { + if (i == 0 || kindOf(i) == SYNTHESIZED) { + return -1L; + } + return widen(offsets[i], i, OVERFLOW_OFFSET); + } + + /** Returns the entry's modification time as the raw MS-DOS date and time word. */ + public long dosTime(int i) { + return dosTimes[i] & 0xFFFFFFFFL; + } + + /** Returns the total length in bytes of all arrays this listing retains. */ + public long retainedBytes() { + return names.length + + 4L * (nameOffsets.length + table.length + firstChildren.length + nextSiblings.length + + kinds.length + crcs.length + compressedSizes.length + sizes.length + + offsets.length + dosTimes.length + overflowEntries.length) + + (kindIndex != null ? kindIndex.length : 4L * wideKindIndex.length) + + 8L * overflowValues.length; + } + + private int kindOf(int i) { + return kindIndex != null ? kindIndex[i] & 0xFF : wideKindIndex[i]; + } + + private long widen(int stored, int i, int field) { + if (stored != -1) { + return stored & 0xFFFFFFFFL; + } + int slot = Arrays.binarySearch(overflowEntries, i); + return overflowValues[slot * OVERFLOW_FIELDS + field]; + } + + private static int hash(byte[] a, int off, int len) { + int h = 1; + for (int k = off; k < off + len; k++) { + h = 31 * h + a[k]; + } + return h ^ (h >>> 16); + } + + /* Slots hold entry index + 1, so 0 means empty. */ + private static int lookup(int[] table, byte[] names, int[] nameOffsets, byte[] key, int off, int len) { + int slot = (hash(key, off, len) & 0x7FFFFFFF) % table.length; + int stored; + while ((stored = table[slot]) != 0) { + int i = stored - 1; + int start = nameOffsets[i]; + if (nameOffsets[i + 1] - start == len && regionEquals(names, start, key, off, len)) { + return i; + } + if (++slot == table.length) { + slot = 0; + } + } + return -1; + } + + private static boolean regionEquals(byte[] a, int aOff, byte[] b, int bOff, int len) { + for (int k = 0; k < len; k++) { + if (a[aOff + k] != b[bOff + k]) { + return false; + } + } + return true; + } + + private static void insert(int[] table, byte[] names, int[] nameOffsets, int i) { + int start = nameOffsets[i]; + int slot = (hash(names, start, nameOffsets[i + 1] - start) & 0x7FFFFFFF) % table.length; + while (table[slot] != 0) { + if (++slot == table.length) { + slot = 0; + } + } + table[slot] = i + 1; + } + + private static int[] buildTable(byte[] names, int[] nameOffsets, int count) { + int[] table = new int[count + count / 3 + 2]; + for (int i = 0; i < count; i++) { + insert(table, names, nameOffsets, i); + } + return table; + } + + private static int sh(byte[] b, int pos) { + return (b[pos] & 0xFF) | ((b[pos + 1] & 0xFF) << 8); + } + + private static long lg(byte[] b, int pos) { + return (sh(b, pos) | ((long) sh(b, pos + 2) << 16)) & 0xFFFFFFFFL; + } + + private static long ll(byte[] b, int pos) { + return lg(b, pos) | (lg(b, pos + 4) << 32); + } + + private static void readFully(FileChannel ch, ByteBuffer buf, long position) throws IOException { + while (buf.hasRemaining()) { + int n = ch.read(buf, position + buf.position()); + if (n < 0) { + throw new ZipException("read CEN tables failed"); + } + } + } + + private static final class Directory { + long position; + long length; + long localHeaderBase; + int entryHint; + } + + /* Mirrors ZipFileSystem.findEND and the start of initCEN. */ + private static Directory locateDirectory(FileChannel ch) throws IOException { + long fileLength = ch.size(); + if (fileLength < ENDHDR) { + throw new ZipException("zip END header not found"); + } + int tailLength = (int) Math.min(fileLength, END_MAXLEN); + long tailStart = fileLength - tailLength; + byte[] tail = new byte[tailLength]; + readFully(ch, ByteBuffer.wrap(tail), tailStart); + + int at = -1; + for (int i = tailLength - ENDHDR; i >= 0; i--) { + if (lg(tail, i) == ENDSIG && tailStart + i + ENDHDR + sh(tail, i + 20) == fileLength) { + at = i; + break; + } + } + if (at < 0) { + throw new ZipException("zip END header not found"); + } + + long entries = sh(tail, at + 10); + long cenLength = lg(tail, at + 12); + long cenOffset = lg(tail, at + 16); + long endPosition = tailStart + at; + + if (endPosition >= ZIP64_LOCHDR) { + byte[] locator = new byte[ZIP64_LOCHDR]; + readFully(ch, ByteBuffer.wrap(locator), endPosition - ZIP64_LOCHDR); + if (lg(locator, 0) == ZIP64_LOCSIG) { + long end64Position = ll(locator, 8); + byte[] end64 = new byte[ZIP64_ENDHDR]; + if (end64Position >= 0 && end64Position + ZIP64_ENDHDR <= fileLength) { + readFully(ch, ByteBuffer.wrap(end64), end64Position); + long total64 = ll(end64, 32); + long length64 = ll(end64, 40); + long offset64 = ll(end64, 48); + boolean consistent = lg(end64, 0) == ZIP64_ENDSIG + && (length64 == cenLength || cenLength == ZIP64_MINVAL) + && (offset64 == cenOffset || cenOffset == ZIP64_MINVAL) + && (total64 == entries || entries == ZIP64_MINVAL32); + if (consistent) { + cenLength = length64; + cenOffset = offset64; + entries = total64; + endPosition = end64Position; + } + } + } + } + + if (endPosition == 0) { + Directory empty = new Directory(); + empty.length = 0; + return empty; + } + if (cenLength < 0 || cenLength > endPosition) { + throw new ZipException("invalid END header (bad central directory size)"); + } + if (cenLength > Integer.MAX_VALUE - ENDHDR) { + throw new ZipException("invalid END header (central directory too large)"); + } + long cenPosition = endPosition - cenLength; + long base = cenPosition - cenOffset; + if (base < 0) { + throw new ZipException("invalid END header (bad central directory offset)"); + } + Directory directory = new Directory(); + directory.position = cenPosition; + directory.length = cenLength; + directory.localHeaderBase = base; + directory.entryHint = (int) Math.min(entries, cenLength / (CENHDR + 1)); + return directory; + } + + private static final class Builder { + private final long localHeaderBase; + private final Map overflow = new HashMap<>(); + private final Map kindLookup = new HashMap<>(); + private int[] kinds = new int[NARROW_KINDS]; + private int kindCount = 1; + + private int count; + private int capacity; + private byte[] names; + private int namesUsed; + private int[] nameOffsets; + private int[] table; + private int[] firstChildren; + private int[] nextSiblings; + private int[] kindIndex; + private int[] crcs; + private int[] compressedSizes; + private int[] sizes; + private int[] offsets; + private int[] dosTimes; + + private byte[] scratch = new byte[256]; + + Builder(int entryHint, long localHeaderBase) { + this.localHeaderBase = localHeaderBase; + this.kinds[SYNTHESIZED] = KIND_DIRECTORY_BIT; + this.capacity = entryHint + 8; + this.names = new byte[capacity * 24]; + this.nameOffsets = new int[capacity + 1]; + this.table = new int[Integer.highestOneBit(capacity * 2) * 2]; + this.firstChildren = new int[capacity]; + this.nextSiblings = new int[capacity]; + this.kindIndex = new int[capacity]; + this.crcs = new int[capacity]; + this.compressedSizes = new int[capacity]; + this.sizes = new int[capacity]; + this.offsets = new int[capacity]; + this.dosTimes = new int[capacity]; + append(new byte[] {'/'}, 0, 1); + } + + Builder parse(byte[] cen) throws ZipException { + int pos = 0; + int limit = cen.length; + while (pos < limit) { + if (limit - pos < CENHDR || lg(cen, pos) != CENSIG) { + throw new ZipException("invalid CEN header (bad signature)"); + } + int flag = sh(cen, pos + 8); + int method = sh(cen, pos + 10); + int nlen = sh(cen, pos + 28); + int elen = sh(cen, pos + 30); + int clen = sh(cen, pos + 32); + if ((flag & FLAG_ENCRYPTED) != 0) { + throw new ZipException("invalid CEN header (encrypted entry)"); + } + if (method != METHOD_STORED && method != METHOD_DEFLATED) { + throw new ZipException("invalid CEN header (unsupported compression method: " + method + ")"); + } + if ((long) pos + CENHDR + nlen + elen + clen > limit) { + throw new ZipException("invalid CEN header (bad header size)"); + } + addEntry(cen, pos, flag, method, nlen, elen); + pos += CENHDR + nlen + elen + clen; + } + return this; + } + + JarListing finish() { + return new JarListing(this); + } + + private void addEntry(byte[] cen, int pos, int flag, int method, int nlen, int elen) { + int nameStart = pos + CENHDR; + boolean directory = nlen > 0 && cen[nameStart + nlen - 1] == '/'; + int len = normalizeInto(cen, nameStart, nlen); + + long size = lg(cen, pos + 24); + long compressed = lg(cen, pos + 20); + long offset = lg(cen, pos + 42); + if (size == ZIP64_MINVAL || compressed == ZIP64_MINVAL || offset == ZIP64_MINVAL) { + long[] wide = readZip64(cen, nameStart + nlen, elen, size, compressed, offset); + size = wide[0]; + compressed = wide[1]; + offset = wide[2]; + } + + int i = find(scratch, 0, len); + if (i < 0) { + i = create(scratch, len); + } + int kind = kindFor(method, directory, flag); + kindIndex[i] = kind; + crcs[i] = (int) lg(cen, pos + 16); + dosTimes[i] = (int) lg(cen, pos + 12); + store(i, size, compressed, offset + localHeaderBase); + } + + private void store(int i, long size, long compressed, long offset) { + sizes[i] = narrow(size); + compressedSizes[i] = narrow(compressed); + offsets[i] = narrow(offset); + if (sizes[i] == -1 || compressedSizes[i] == -1 || offsets[i] == -1) { + long[] wide = new long[OVERFLOW_FIELDS]; + wide[OVERFLOW_SIZE] = size; + wide[OVERFLOW_COMPRESSED] = compressed; + wide[OVERFLOW_OFFSET] = offset; + overflow.put(i, wide); + } else { + overflow.remove(i); + } + } + + private static int narrow(long v) { + return v >= ZIP64_MINVAL ? -1 : (int) v; + } + + /* + * Like ZipFileSystem.readExtra, a missing or short zip64 field leaves the 32-bit value in + * place instead of failing. + */ + private static long[] readZip64(byte[] cen, int extraStart, int elen, long size, long compressed, + long offset) { + int p = extraStart; + int end = extraStart + elen; + while (p + 4 <= end) { + int id = sh(cen, p); + int dataLen = sh(cen, p + 2); + int data = p + 4; + if (data + dataLen > end) { + break; + } + if (id == ZIP64_EXTID) { + int at = data; + int dataEnd = data + dataLen; + if (size == ZIP64_MINVAL && at + 8 <= dataEnd) { + size = ll(cen, at); + at += 8; + } + if (compressed == ZIP64_MINVAL && at + 8 <= dataEnd) { + compressed = ll(cen, at); + at += 8; + } + if (offset == ZIP64_MINVAL && at + 8 <= dataEnd) { + offset = ll(cen, at); + } + break; + } + p = data + dataLen; + } + return new long[] {size, compressed, offset}; + } + + private int kindFor(int method, boolean directory, int flag) { + int kind = (method << KIND_METHOD_SHIFT) | (directory ? KIND_DIRECTORY_BIT : 0) | flag; + Integer known = kindLookup.get(kind); + if (known != null) { + return known; + } + if (kindCount == kinds.length) { + kinds = Arrays.copyOf(kinds, kinds.length * 2); + } + kinds[kindCount] = kind; + kindLookup.put(kind, kindCount); + return kindCount++; + } + + /* + * Writes the normalized name into scratch and returns its length: leading slash, no + * trailing slash, repeated slashes collapsed. An empty or all-slash name is the root. + */ + private int normalizeInto(byte[] src, int off, int len) { + if (scratch.length < len + 1) { + scratch = new byte[len + 1]; + } + int out = 0; + byte prev = 0; + for (int k = off; k < off + len; k++) { + byte c = src[k]; + if (c == '/' && prev == '/') { + continue; + } + if (out == 0 && c != '/') { + scratch[out++] = '/'; + } + scratch[out++] = c; + prev = c; + } + if (out == 0) { + scratch[out++] = '/'; + } + if (out > 1 && scratch[out - 1] == '/') { + out--; + } + return out; + } + + private int find(byte[] key, int off, int len) { + return lookup(table, names, nameOffsets, key, off, len); + } + + /* + * Creates an entry for key[0..len), plus any missing ancestors, and links each to its parent. + * Iterative because one entry name can hold tens of thousands of segments. The entry and its + * missing ancestors get consecutive indices, deepest first, so the links are made by walking + * those indices back from the shallowest. + */ + private int create(byte[] key, int len) { + final int first = count; + int end = len; + int parent; + do { + append(key, 0, end); + end--; + while (key[end] != '/') { + end--; + } + parent = end == 0 ? 0 : find(key, 0, end); + } while (parent < 0); + for (int i = count - 1; i >= first; i--) { + nextSiblings[i] = firstChildren[parent]; + firstChildren[parent] = i; + parent = i; + } + return first; + } + + private int append(byte[] src, int off, int len) { + if (count == capacity) { + grow(); + } + int i = count++; + if (namesUsed + len > names.length) { + names = Arrays.copyOf(names, Math.max(names.length * 2, namesUsed + len)); + } + System.arraycopy(src, off, names, namesUsed, len); + nameOffsets[i] = namesUsed; + namesUsed += len; + nameOffsets[i + 1] = namesUsed; + firstChildren[i] = -1; + nextSiblings[i] = -1; + if (count * 4L > table.length * 3L) { + rehash(); + } + insert(table, names, nameOffsets, i); + return i; + } + + private void grow() { + capacity = capacity + (capacity >> 1) + 8; + nameOffsets = Arrays.copyOf(nameOffsets, capacity + 1); + firstChildren = Arrays.copyOf(firstChildren, capacity); + nextSiblings = Arrays.copyOf(nextSiblings, capacity); + kindIndex = Arrays.copyOf(kindIndex, capacity); + crcs = Arrays.copyOf(crcs, capacity); + compressedSizes = Arrays.copyOf(compressedSizes, capacity); + sizes = Arrays.copyOf(sizes, capacity); + offsets = Arrays.copyOf(offsets, capacity); + dosTimes = Arrays.copyOf(dosTimes, capacity); + } + + /* Called with the new entry's names and offsets in place but not yet inserted. */ + private void rehash() { + table = new int[table.length * 2]; + for (int i = 0; i < count - 1; i++) { + insert(table, names, nameOffsets, i); + } + } + } +} \ No newline at end of file diff --git a/composite-builds/build-deps/java-compiler/src/main/java/dev/mutwakil/androidide/zipfs2/listing/JarListingCache.java b/composite-builds/build-deps/java-compiler/src/main/java/dev/mutwakil/androidide/zipfs2/listing/JarListingCache.java new file mode 100644 index 0000000000..f4a0a97f6e --- /dev/null +++ b/composite-builds/build-deps/java-compiler/src/main/java/dev/mutwakil/androidide/zipfs2/listing/JarListingCache.java @@ -0,0 +1,256 @@ +/* + * 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 dev.mutwakil.androidide.zipfs2.listing; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.NoSuchFileException; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.nio.file.attribute.BasicFileAttributes; +import java.util.List; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.atomic.AtomicLong; +import java.util.concurrent.locks.ReentrantLock; +import java.util.function.Consumer; + +/** + * Shares one {@link JarListing} per JAR and rebuilds it when the JAR's size or modification time + * changes on disk. + * + *

Each JAR has its own lock, so a build or a listener on one JAR never blocks {@link #get} on + * another. The lock is reentrant: a listener may call {@link #get} or {@link #invalidate} for the + * JAR it was notified about. + */ +public final class JarListingCache { + + /** The cache shared by every file system and virtual file system in the process. */ + public static final JarListingCache SHARED = new JarListingCache(JarListing::read); + + /** Builds a listing for a JAR. */ + @FunctionalInterface + public interface Reader { + JarListing read(Path jar) throws IOException; + } + + /** + * A cached listing together with the size and modification time of the JAR it was built from. + * + *

Each build gets a generation greater than every earlier build in the same cache, so of two + * snapshots of one JAR the one with the greater generation is the more recent. + */ + public static final class Snapshot { + private final JarListing listing; + private final long generation; + private final long size; + private final long modifiedNanos; + + Snapshot(JarListing listing, long generation, long size, long modifiedNanos) { + this.listing = listing; + this.generation = generation; + this.size = size; + this.modifiedNanos = modifiedNanos; + } + + /** Returns the listing. */ + public JarListing listing() { + return listing; + } + + /** Returns the build order of this snapshot within its cache. */ + public long generation() { + return generation; + } + + /** Returns the JAR's size in bytes when the listing was built. */ + public long size() { + return size; + } + + /** Returns the JAR's modification time, in nanoseconds since the epoch, when the listing was built. */ + public long modifiedNanos() { + return modifiedNanos; + } + } + + private final Reader reader; + private final AtomicLong generations = new AtomicLong(); + private final ConcurrentHashMap entries = new ConcurrentHashMap<>(); + private final ConcurrentHashMap locks = new ConcurrentHashMap<>(); + private final List> listeners = new CopyOnWriteArrayList<>(); + + /** Creates a cache that builds listings with the given reader. */ + public JarListingCache(Reader reader) { + this.reader = reader; + } + + /** + * Returns the listing for the JAR, building it on first use and rebuilding it when the JAR's + * size or modification time differs from when it was built. + * + *

Listeners are notified of a dropped listing before its replacement is built. Every + * listener is called even if one throws; the first failure is then rethrown with the others + * suppressed, and the next call builds the replacement. If the build fails, the exception + * propagates and nothing is cached. A JAR that no longer exists has its listing dropped, and + * listeners notified, before the {@link NoSuchFileException} propagates. + * + * @throws IOException if the JAR cannot be read or its central directory is malformed + */ + public JarListing get(Path jar) throws IOException { + return snapshot(jar).listing; + } + + /** + * Returns the listing for the JAR with the state it was built from; see {@link #get}. + * + * @throws IOException if the JAR cannot be read or its central directory is malformed + */ + public Snapshot snapshot(Path jar) throws IOException { + final Path key = normalize(jar); + final String id = key.toString(); + final BasicFileAttributes attrs; + try { + attrs = Files.readAttributes(key, BasicFileAttributes.class); + } catch (NoSuchFileException e) { + // The check keeps lookups of JARs that never existed from adding a lock entry + if (entries.containsKey(id)) { + invalidate(key); + } + throw e; + } + final long size = attrs.size(); + final long mtime = modifiedNanos(attrs); + + final Snapshot cached = entries.get(id); + if (isCurrent(cached, size, mtime)) { + return cached; + } + + final ReentrantLock lock = lockFor(id); + lock.lock(); + try { + Snapshot current = entries.get(id); + if (current != null && !isCurrent(current, size, mtime)) { + dropAndNotify(id, key); + current = entries.get(id); + } + if (isCurrent(current, size, mtime)) { + return current; + } + final Snapshot built = new Snapshot(reader.read(key), generations.incrementAndGet(), size, mtime); + entries.put(id, built); + return built; + } finally { + lock.unlock(); + } + } + + /** + * Returns the snapshot currently cached for the JAR, or null if none is, without checking the + * file on disk or waiting for a build in progress. + */ + public Snapshot peek(Path jar) { + return entries.get(normalize(jar).toString()); + } + + /** Drops the JAR's listing, if cached, and notifies listeners. */ + public void invalidate(Path jar) { + final Path key = normalize(jar); + final String id = key.toString(); + final ReentrantLock lock = lockFor(id); + lock.lock(); + try { + dropAndNotify(id, key); + } finally { + lock.unlock(); + } + } + + /** + * Drops every cached listing and notifies listeners once per JAR. + * + *

Every JAR is dropped even if a listener throws; the first failure is then rethrown with the + * others suppressed. A listing built concurrently with the clear may stay cached. + */ + public void clear() { + RuntimeException failure = null; + for (String id : entries.keySet()) { + try { + invalidate(Paths.get(id)); + } catch (RuntimeException e) { + if (failure == null) { + failure = e; + } else { + failure.addSuppressed(e); + } + } + } + if (failure != null) { + throw failure; + } + } + + /** + * Registers a listener called with the JAR's path once for every listing that is dropped. + * + *

The listener runs on the thread that dropped the listing, after the old listing is no + * longer returned and before its replacement is built. + */ + public void addListener(Consumer onInvalidated) { + listeners.add(onInvalidated); + } + + private void dropAndNotify(String id, Path key) { + if (entries.remove(id) == null) { + return; + } + RuntimeException failure = null; + for (Consumer listener : listeners) { + try { + listener.accept(key); + } catch (RuntimeException e) { + if (failure == null) { + failure = e; + } else { + failure.addSuppressed(e); + } + } + } + if (failure != null) { + throw failure; + } + } + + private ReentrantLock lockFor(String id) { + return locks.computeIfAbsent(id, k -> new ReentrantLock()); + } + + private static boolean isCurrent(Snapshot entry, long size, long mtime) { + return entry != null && entry.size == size && entry.modifiedNanos == mtime; + } + + private static long modifiedNanos(BasicFileAttributes attrs) { + final var time = attrs.lastModifiedTime().toInstant(); + return time.getEpochSecond() * 1_000_000_000L + time.getNano(); + } + + private static Path normalize(Path jar) { + return jar.toAbsolutePath().normalize(); + } +} \ No newline at end of file diff --git a/core/app/proguard-rules.pro b/core/app/proguard-rules.pro index 4ae232f7b8..3224793bca 100644 --- a/core/app/proguard-rules.pro +++ b/core/app/proguard-rules.pro @@ -158,6 +158,11 @@ #-keep class io.sentry.** { *; } #-dontwarn io.sentry.** +-keep class androidx.compose.** { *; } +-keep class androidx.lifecycle.** { *; } +-keep class androidx.activity.** { *; } +-keep class androidx.savedstate.** { *; } + ## R8 Kotlin metadata workaround for Kotlin 2.3.0 compatibility ## Suppresses D8 errors when parsing kotlin metadata for StopWatch inline functions -keep class dev.mutwakil.androidide.utils.StopWatch { *; } diff --git a/core/app/src/main/java/dev/mutwakil/androidide/activities/editor/BaseEditorActivity.kt b/core/app/src/main/java/dev/mutwakil/androidide/activities/editor/BaseEditorActivity.kt index c1d49451f0..31bcbf2d4f 100644 --- a/core/app/src/main/java/dev/mutwakil/androidide/activities/editor/BaseEditorActivity.kt +++ b/core/app/src/main/java/dev/mutwakil/androidide/activities/editor/BaseEditorActivity.kt @@ -259,6 +259,9 @@ abstract class BaseEditorActivity : EdgeToEdgeIDEActivity(), TabLayout.OnTabSele protected abstract fun getOpenedFiles(): List internal abstract fun doConfirmProjectClose() + + // whatever a genuinely live sibling instance set up instead. + private var didCompleteLiveOnCreate = false protected open fun preDestroy() { _binding = null @@ -282,7 +285,7 @@ abstract class BaseEditorActivity : EdgeToEdgeIDEActivity(), TabLayout.OnTabSele } protected open fun postDestroy() { - if (isDestroying) { + if (didCompleteLiveOnCreate && isDestroying) { Lookup.getDefault().unregisterAll() ApiVersionsRegistry.getInstance().clear() ResourceTableRegistry.getInstance().clear() @@ -406,6 +409,8 @@ abstract class BaseEditorActivity : EdgeToEdgeIDEActivity(), TabLayout.OnTabSele setupMemUsageChart() watchMemory() + + didCompleteLiveOnCreate = true } private fun setupDependencyUpdater() { diff --git a/core/app/src/main/java/dev/mutwakil/androidide/activities/editor/EditorHandlerActivity.kt b/core/app/src/main/java/dev/mutwakil/androidide/activities/editor/EditorHandlerActivity.kt index cbda2c8e2b..99fe23304b 100644 --- a/core/app/src/main/java/dev/mutwakil/androidide/activities/editor/EditorHandlerActivity.kt +++ b/core/app/src/main/java/dev/mutwakil/androidide/activities/editor/EditorHandlerActivity.kt @@ -82,6 +82,11 @@ open class EditorHandlerActivity : ProjectHandlerActivity(), IEditorHandler { protected val isOpenedFilesSaved = AtomicBoolean(false) private val fileTimestamps = ConcurrentHashMap() + + // True once onCreate() has completed past its isFinishing check -- see there and preDestroy() + // for why a doomed, finishing-from-birth instance must not run teardown meant only for an + // instance that actually became the live one. + private var didCompleteLiveOnCreate = false override fun doOpenFile(file: File, selection: Range?) { openFileAndSelect(file, selection) @@ -101,13 +106,21 @@ open class EditorHandlerActivity : ProjectHandlerActivity(), IEditorHandler { override fun preDestroy() { super.preDestroy() - TSLanguageRegistry.instance.destroy() + if (didCompleteLiveOnCreate){ + TSLanguageRegistry.instance.destroy() + } editorViewModel.removeAllFiles() } override fun onCreate(savedInstanceState: Bundle?) { mBuildEventListener.setActivity(this) super.onCreate(savedInstanceState) + + if (isFinishing) { + return + } + + didCompleteLiveOnCreate = true editorViewModel._displayedFile.observe( this) { this.content.editorContainer.displayedChild = it } diff --git a/core/app/src/main/java/dev/mutwakil/androidide/activities/editor/ProjectHandlerActivity.kt b/core/app/src/main/java/dev/mutwakil/androidide/activities/editor/ProjectHandlerActivity.kt index fa5c83e9df..cb4b448e0a 100644 --- a/core/app/src/main/java/dev/mutwakil/androidide/activities/editor/ProjectHandlerActivity.kt +++ b/core/app/src/main/java/dev/mutwakil/androidide/activities/editor/ProjectHandlerActivity.kt @@ -112,6 +112,12 @@ abstract class ProjectHandlerActivity : private val buildViewModel by viewModels() protected var initializingFuture: CompletableFuture? = null + + private val sessionCloser = + ProjectSessionCloser( + currentSession = { ProjectManagerImpl.getInstance().currentIndexingServiceManager }, + teardown = ::closeProjectSession, + ) val findInProjectDialog: AlertDialog? get() = createFindInProjectDialog() @@ -120,6 +126,14 @@ abstract class ProjectHandlerActivity : get() = createFindInProjectDialog(SearchMode.REPLACE) protected val mBuildEventListener = EditorBuildEventListener() + + // True once onCreate() has completed past its isFinishing check -- mirrors + // EditorHandlerActivity.didCompleteLiveOnCreate. super.onCreate() (BaseEditorActivity) may + // already have called finish() for a doomed instance spun up by a stale deep-link liveness + // check; finish() doesn't stop execution, so without this flag preDestroy() would unregister + // the process-wide build-service Lookup entry and shut down the LSP singleton that an + // actually-live sibling instance still depends on. + private var didCompleteLiveOnCreate = false companion object { const val STATE_KEY_FROM_SAVED_INSTANACE = "ide.editor.isFromSavedInstance" @@ -138,6 +152,12 @@ abstract class ProjectHandlerActivity : override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) + + if (isFinishing) { + return + } + + didCompleteLiveOnCreate = true editorViewModel._isSyncNeeded.observe(this) { isSyncNeeded -> if (!isSyncNeeded) { @@ -214,16 +234,32 @@ abstract class ProjectHandlerActivity : override fun onPause() { super.onPause() - if (isDestroying) { - // reset these values here - // sometimes, when the IDE closed and reopened instantly, these values prevent initialization - // of the project - ProjectManagerImpl.getInstance().destroy() - - editorViewModel.isInitializing = false - editorViewModel.isBuildInProgress = false - } + if (!isDestroying) return + if (didCompleteLiveOnCreate) { + // The teardown below destroys the project, so a sync finishing after it must not set one up again. + initializingFuture?.cancel(true) + initializingFuture = null + sessionCloser.close() + } else { + // A doomed instance must not stop the servers a live sibling uses; preDestroy gates them the same way. + closeProjectState() + } } + + private fun closeProjectSession() { + stopLanguageServers() + closeProjectState() + } + + private fun closeProjectState() { + // reset these values here + // sometimes, when the IDE closed and reopened instantly, these values prevent initialization + // of the project + ProjectManagerImpl.getInstance().destroy() + + editorViewModel.isInitializing = false + editorViewModel.isBuildInProgress = false + } override fun onResume() { super.onResume() @@ -241,7 +277,7 @@ abstract class ProjectHandlerActivity : syncNotificationFlashbar = null discardReplaceUndo() - if (isDestroying) { + if (didCompleteLiveOnCreate && isDestroying) { releaseServerListener() this.initializingFuture?.cancel(true) this.initializingFuture = null @@ -249,7 +285,7 @@ abstract class ProjectHandlerActivity : doCloseAll() } - if (IDELanguageClientImpl.isInitialized()) { + if (didCompleteLiveOnCreate && IDELanguageClientImpl.isInitialized()) { if (isDestroying) { IDELanguageClientImpl.shutdown() } else { @@ -259,16 +295,12 @@ abstract class ProjectHandlerActivity : super.preDestroy() - if (!isDestroying) { + if (didCompleteLiveOnCreate && !isDestroying) { editorViewModel.clearBuildServiceCallback() } - if (isDestroying) { - try { - stopLanguageServers() - } catch (_: Exception) { - log.error("Failed to stop editor services.") - } + if (didCompleteLiveOnCreate && isDestroying) { + sessionCloser.close() try { editorViewModel.unbindBuildService() @@ -308,6 +340,7 @@ abstract class ProjectHandlerActivity : } fun appendBuildOutput(str: String) { + if (_binding == null || isDestroyed || isFinishing) return content.bottomSheet.appendBuildOut(str) } @@ -562,6 +595,11 @@ abstract class ProjectHandlerActivity : } protected open fun onProjectInitialized(result: InitializeResult.Success) { + // A callback queued before onPause cancelled the future still lands here after the teardown. + if (!sessionCloser.record { ProjectManagerImpl.getInstance().indexingServiceManager }) { + log.info("Project closed before its initialization finished, skipping its setup") + return + } Memprof.mark("sync_complete") editorActivityScope.launch(Dispatchers.IO) { val manager = ProjectManagerImpl.getInstance() diff --git a/core/app/src/main/java/dev/mutwakil/androidide/activities/editor/ProjectHandlerActivity.kt.bak b/core/app/src/main/java/dev/mutwakil/androidide/activities/editor/ProjectHandlerActivity.kt.bak new file mode 100644 index 0000000000..7d28378b36 --- /dev/null +++ b/core/app/src/main/java/dev/mutwakil/androidide/activities/editor/ProjectHandlerActivity.kt.bak @@ -0,0 +1,1058 @@ +/* + * 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 dev.mutwakil.androidide.activities.editor + +//import io.sentry.Sentry +import android.content.Intent +import android.os.Bundle +import android.view.Gravity +import android.view.ViewGroup.MarginLayoutParams +import android.widget.CheckBox +import androidx.activity.viewModels +import androidx.annotation.GravityInt +import androidx.appcompat.app.AlertDialog +import androidx.core.view.isVisible +import androidx.lifecycle.Lifecycle +import androidx.lifecycle.lifecycleScope +import androidx.lifecycle.repeatOnLifecycle +import dev.mutwakil.androidide.R +import dev.mutwakil.androidide.R.string +import dev.mutwakil.androidide.databinding.LayoutSearchProjectBinding +import dev.mutwakil.androidide.flashbar.Flashbar +import dev.mutwakil.androidide.fragments.sheets.ProgressSheet +import dev.mutwakil.androidide.handlers.EditorBuildEventListener +import dev.mutwakil.androidide.handlers.LspHandler.connectClient +import dev.mutwakil.androidide.handlers.LspHandler.destroyLanguageServers +import dev.mutwakil.androidide.lookup.Lookup +import dev.mutwakil.androidide.lsp.IDELanguageClientImpl +import dev.mutwakil.androidide.lsp.java.utils.CancelChecker +import dev.mutwakil.androidide.memprof.Memprof +import dev.mutwakil.androidide.models.SearchResult +import dev.mutwakil.androidide.preferences.internal.GeneralPreferences +import dev.mutwakil.androidide.projects.ProjectManagerImpl +import dev.mutwakil.androidide.projects.builder.BuildService +import dev.mutwakil.androidide.projects.models.projectDir +import dev.mutwakil.androidide.search.replace.ReplaceCoordinator +import dev.mutwakil.androidide.search.replace.ReplaceHost +import dev.mutwakil.androidide.search.replace.ReplaceSession +import dev.mutwakil.androidide.search.replace.SkipReason +import dev.mutwakil.androidide.services.builder.GradleBuildService +import dev.mutwakil.androidide.services.builder.gradleDistributionParams +import dev.mutwakil.androidide.tooling.api.messages.AndroidInitializationParams +import dev.mutwakil.androidide.tooling.api.messages.InitializeProjectParams +import dev.mutwakil.androidide.tooling.api.messages.result.InitializeResult +import dev.mutwakil.androidide.tooling.api.messages.result.TaskExecutionResult +import dev.mutwakil.androidide.tooling.api.messages.result.TaskExecutionResult.Failure.CACHE_READ_ERROR +import dev.mutwakil.androidide.tooling.api.messages.result.TaskExecutionResult.Failure.PROJECT_DIRECTORY_INACCESSIBLE +import dev.mutwakil.androidide.tooling.api.messages.result.TaskExecutionResult.Failure.PROJECT_NOT_DIRECTORY +import dev.mutwakil.androidide.tooling.api.messages.result.TaskExecutionResult.Failure.PROJECT_NOT_FOUND +import dev.mutwakil.androidide.tooling.api.messages.result.failure +import dev.mutwakil.androidide.tooling.api.messages.result.isSuccessful +import dev.mutwakil.androidide.tooling.api.models.BuildVariantInfo +import dev.mutwakil.androidide.tooling.api.models.mapToSelectedVariants +import dev.mutwakil.androidide.tooling.api.sync.ProjectSyncHelper +import dev.mutwakil.androidide.ui.CodeEditorView +import dev.mutwakil.androidide.utils.DURATION_INDEFINITE +import dev.mutwakil.androidide.utils.DURATION_LONG +import dev.mutwakil.androidide.utils.DialogUtils.newMaterialDialogBuilder +import dev.mutwakil.androidide.utils.ProjectSearchOptions +import dev.mutwakil.androidide.utils.RecursiveFileSearcher +import dev.mutwakil.androidide.utils.dpToPx +import dev.mutwakil.androidide.utils.flashError +import dev.mutwakil.androidide.utils.flashSuccess +import dev.mutwakil.androidide.utils.flashbarBuilder +import dev.mutwakil.androidide.utils.resolveAttr +import dev.mutwakil.androidide.utils.showOnUiThread +import dev.mutwakil.androidide.utils.withIcon +import dev.mutwakil.androidide.viewmodel.BuildState +import dev.mutwakil.androidide.viewmodel.BuildVariantsViewModel +import dev.mutwakil.androidide.viewmodel.BuildViewModel +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.launch +import kotlinx.coroutines.withContext +import java.io.File +import java.util.concurrent.CompletableFuture +import java.util.regex.Pattern +import java.util.stream.Collectors + +/** @author Akash Yadav */ +@Suppress("MemberVisibilityCanBePrivate") +abstract class ProjectHandlerActivity : + BaseEditorActivity(), + ReplaceHost { + protected val buildVariantsViewModel by viewModels() + + protected var mSearchingProgress: ProgressSheet? = null + protected var mFindInProjectDialog: AlertDialog? = null + protected var mReplaceInProjectDialog: AlertDialog? = null + private val replaceCoordinator by lazy { + ReplaceCoordinator(editorFor = { file -> + getEditorForFile( + file + )?.editor + }) + } + protected var syncNotificationFlashbar: Flashbar? = null + private var replaceReportFlashbar: Flashbar? = null + + private val buildViewModel by viewModels() + protected var initializingFuture: CompletableFuture? = null + + private val sessionCloser = + ProjectSessionCloser( + currentSession = { ProjectManagerImpl.getInstance().currentIndexingServiceManager }, + teardown = ::closeProjectSession, + ) + + val findInProjectDialog: AlertDialog? + get() = createFindInProjectDialog() + + val replaceInProjectDialog: AlertDialog? + get() = createFindInProjectDialog(SearchMode.REPLACE) + + protected val mBuildEventListener = EditorBuildEventListener() + + // True once onCreate() has completed past its isFinishing check -- mirrors + // EditorHandlerActivity.didCompleteLiveOnCreate. super.onCreate() (BaseEditorActivity) may + // already have called finish() for a doomed instance spun up by a stale deep-link liveness + // check; finish() doesn't stop execution, so without this flag preDestroy() would unregister + // the process-wide build-service Lookup entry and shut down the LSP singleton that an + // actually-live sibling instance still depends on. + private var didCompleteLiveOnCreate = false + + companion object { + const val STATE_KEY_FROM_SAVED_INSTANACE = "ide.editor.isFromSavedInstance" + const val STATE_KEY_SHOULD_INITIALIZE = "ide.editor.isInitializing" + } + + abstract fun doCloseAll() + + abstract fun saveOpenedFiles() + + override fun doDismissSearchProgress() { + if (mSearchingProgress?.isShowing == true) { + mSearchingProgress!!.dismiss() + } + } + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + + if (isFinishing) { + return + } + + didCompleteLiveOnCreate = true + + editorViewModel._isSyncNeeded.observe(this) { isSyncNeeded -> + if (!isSyncNeeded) { + // dismiss if already showing + syncNotificationFlashbar?.dismiss() + return@observe + } + + if (syncNotificationFlashbar?.isShowing() == true) { + // already shown + return@observe + } + + notifySyncNeeded() + } + + observeStates() + startServices() + } + + private fun observeStates() { + lifecycleScope.launch { + repeatOnLifecycle(Lifecycle.State.STARTED) { + launch { + buildViewModel.buildState.collect { onBuildStateChanged(it) } + } + } + } + } + + private fun onBuildStateChanged(state: BuildState) { + editorViewModel.isBuildInProgress = (state is BuildState.InProgress) + when (state) { + is BuildState.Idle -> { + // Nothing to do, build is finished or not started. + } + + is BuildState.InProgress -> { + setStatus(getString(R.string.status_building)) + } + + is BuildState.Success -> { + flashSuccess(state.message) + } + + is BuildState.Error -> { + flashError(state.reason) + } + + is BuildState.AwaitingInstall -> { + installApk(state) + buildViewModel.installationAttempted() + } + } + // Refresh the toolbar icons (e.g., the run/stop button). + invalidateOptionsMenu() + } + + private fun installApk(state: BuildState.AwaitingInstall) { + apkInstallationViewModel.installApk( + context = this, + apk = state.apkFile, + launchInDebugMode = state.launchInDebugMode, + ) + } + + override fun onSaveInstanceState(outState: Bundle) { + super.onSaveInstanceState(outState) + outState.apply { + putBoolean(STATE_KEY_SHOULD_INITIALIZE, !editorViewModel.isInitializing) + putBoolean(STATE_KEY_FROM_SAVED_INSTANACE, true) + } + } + + override fun onPause() { + super.onPause() + if (!isDestroying) return + if (didCompleteLiveOnCreate) { + // The teardown below destroys the project, so a sync finishing after it must not set one up again. + initializingFuture?.cancel(true) + initializingFuture = null + sessionCloser.close() + } else { + // A doomed instance must not stop the servers a live sibling uses; preDestroy gates them the same way. + closeProjectState() + } + } + + private fun closeProjectSession() { + stopLanguageServers() + closeProjectState() + } + + private fun closeProjectState() { + // reset these values here + // sometimes, when the IDE closed and reopened instantly, these values prevent initialization + // of the project + ProjectManagerImpl.getInstance().destroy() + + editorViewModel.isInitializing = false + editorViewModel.isBuildInProgress = false + } + + override fun onResume() { + super.onResume() + + val service = + Lookup.getDefault().lookup(BuildService.KEY_BUILD_SERVICE) as? GradleBuildService + editorViewModel.isBuildInProgress = service?.isBuildInProgress == true + editorViewModel.isInitializing = initializingFuture?.isDone == false + + invalidateOptionsMenu() + } + + override fun preDestroy() { + syncNotificationFlashbar?.dismiss() + syncNotificationFlashbar = null + discardReplaceUndo() + + if (didCompleteLiveOnCreate && isDestroying) { + releaseServerListener() + this.initializingFuture?.cancel(true) + this.initializingFuture = null + + doCloseAll() + } + + if (didCompleteLiveOnCreate && IDELanguageClientImpl.isInitialized()) { + if (isDestroying) { + IDELanguageClientImpl.shutdown() + } else { + IDELanguageClientImpl.getInstance().setActivity(null) + } + } + + super.preDestroy() + + if (didCompleteLiveOnCreate && !isDestroying) { + editorViewModel.clearBuildServiceCallback() + } + + if (didCompleteLiveOnCreate && isDestroying) { + sessionCloser.close() + + try { + editorViewModel.unbindBuildService() + } catch (err: IllegalArgumentException) { + log.error("Unable to unbind service", err) + } finally { + Lookup.getDefault().apply { + (lookup(BuildService.KEY_BUILD_SERVICE) as? GradleBuildService?) + ?.setEventListener(null) + + unregister(BuildService.KEY_BUILD_SERVICE) + } + + mBuildEventListener.release() + } + } + if (mFindInProjectDialog?.isShowing == true) { + mFindInProjectDialog!!.dismiss() + } + if (mReplaceInProjectDialog?.isShowing == true) { + mReplaceInProjectDialog!!.dismiss() + } + + mFindInProjectDialog = null // Create the dialog again if needed + mReplaceInProjectDialog = null + } + + fun setStatus(status: CharSequence) { + setStatus(status, Gravity.CENTER) + } + + fun setStatus( + status: CharSequence, + @GravityInt gravity: Int, + ) { + doSetStatus(status, gravity) + } + + fun appendBuildOutput(str: String) { + content.bottomSheet.appendBuildOut(str) + } + + fun notifySyncNeeded() { + notifySyncNeeded { initializeProject(forceSync = true) } + } + + private fun notifySyncNeeded(onConfirm: () -> Unit) { + val buildService = Lookup.getDefault().lookup(BuildService.KEY_BUILD_SERVICE) + if (buildService == null || editorViewModel.isInitializing || buildService.isBuildInProgress) return + + activityScope.launch(Dispatchers.Main.immediate) { + syncNotificationFlashbar?.dismiss() + syncNotificationFlashbar = + flashbarBuilder( + duration = DURATION_INDEFINITE, + backgroundColor = resolveAttr(R.attr.colorSecondaryContainer), + messageColor = resolveAttr(R.attr.colorOnSecondaryContainer), + ).withIcon( + R.drawable.ic_sync, + colorFilter = resolveAttr(R.attr.colorOnSecondaryContainer), + ).message(string.msg_sync_needed) + .positiveActionText(string.btn_sync) + .positiveActionTapListener { + onConfirm() + it.dismiss() + }.negativeActionText(string.btn_ignore_changes) + .negativeActionTapListener(Flashbar::dismiss) + .build() + + syncNotificationFlashbar?.showOnUiThread() + } + } + + fun startServices() { + val service = + Lookup.getDefault().lookup(BuildService.KEY_BUILD_SERVICE) as GradleBuildService? + if (editorViewModel.isBoundToBuildSerice && service != null) { + log.info("Reusing already started Gradle build service") + attachLanguageClient() + onGradleBuildServiceConnected(service) + return + } else { + log.info("Binding to Gradle build service...") + } + + if (editorViewModel.bindBuildService(this, this::onGradleBuildServiceConnected)) { + log.info("Bind request for Gradle build service was successful...") + } else { + log.error("Gradle build service doesn't exist or the IDE is not allowed to access it.") + } + + initLspClient() + } + + fun initializeProject(forceSync: Boolean = false) { + val currentVariants = buildVariantsViewModel._buildVariants.value + + // no information about the build variants is available + // use the default variant selections + if (currentVariants == null) { + log.debug( + "No variant selection information available. " + + "Default build variants will be selected.", + ) + initializeProject(buildVariants = emptyMap(), forceSync = forceSync) + return + } + + // variant selection information is available + // but there are updated & unsaved variant selections + // use the updated variant selections to initialize the project + if (buildVariantsViewModel.updatedBuildVariants.isNotEmpty()) { + val newSelections = currentVariants.toMutableMap() + newSelections.putAll(buildVariantsViewModel.updatedBuildVariants) + + val selectedVariants = newSelections.mapToSelectedVariants() + log.debug( + "Initializing project with new build variant selections: {}", + selectedVariants + ) + + initializeProject(buildVariants = selectedVariants, forceSync = forceSync) + return + } + + // variant selection information is available but no variant selections have been updated + // the user might be trying to sync the project from options menu + // initialize the project with the existing selected variants + val selectedVariants = currentVariants.mapToSelectedVariants() + log.debug("Re-initializing project with existing build variant selections") + initializeProject(buildVariants = selectedVariants, forceSync = forceSync) + } + + /** + * Initialize (sync) the project. + * + * @param buildVariants A map of project paths to the selected build variants. + */ + fun initializeProject( + buildVariants: Map, + forceSync: Boolean = false, + ) = activityScope.launch { + val manager = ProjectManagerImpl.getInstance() + val projectDir = File(manager.projectPath) + if (!projectDir.exists()) { + log.error("GradleProject directory does not exist. Cannot initialize project") + return@launch + } + + val needsSync = forceSync || manager.isGradleSyncNeeded(projectDir) + + withContext(Dispatchers.Main.immediate) { + preProjectInit() + } + + val buildService = Lookup.getDefault().lookup(BuildService.KEY_BUILD_SERVICE) + if (buildService == null) { + log.error("No build service found. Cannot initialize project.") + return@launch + } + + if (!buildService.isToolingServerStarted()) { + flashError(string.msg_tooling_server_unavailable) + return@launch + } + + log.info("Sending init request to tooling server (needs sync: {})...", needsSync) + initializingFuture = buildService.initializeProject( + params = createProjectInitParams( + projectDir, + buildVariants, + needsSync + ) + ) + + initializingFuture!!.whenCompleteAsync { result, error -> + releaseServerListener() + + if (result == null || !result.isSuccessful || error != null) { + if (!CancelChecker.isCancelled(error)) { + log.error("An error occurred initializing the project with Tooling API", error) + } + + activityScope.launch(context = Dispatchers.Main) { + postProjectInit(isSuccessful = false, failure = result?.failure) + } + return@whenCompleteAsync + } + + onProjectInitialized(result as InitializeResult.Success) + } + } + + private fun createProjectInitParams( + projectDir: File, + buildVariants: Map, + needsGradleSync: Boolean, + ): InitializeProjectParams = + InitializeProjectParams( + directory = projectDir.absolutePath, + gradleDistribution = gradleDistributionParams, + androidParams = createAndroidParams(buildVariants), + needsGradleSync = needsGradleSync, + ) + + private fun createAndroidParams(buildVariants: Map): AndroidInitializationParams { + if (buildVariants.isEmpty()) { + return AndroidInitializationParams.DEFAULT + } + + return AndroidInitializationParams(buildVariants) + } + + private fun releaseServerListener() { + // Release reference to server listener in order to prevent memory leak + (Lookup.getDefault().lookup(BuildService.KEY_BUILD_SERVICE) as? GradleBuildService?) + ?.setServerListener(null) + } + + fun stopLanguageServers() { + try { + destroyLanguageServers(isChangingConfigurations) + } catch (err: Throwable) { + log.error("Unable to stop editor services. Please report this issue.", err) + } + } + + /** + * Re-adds the processes the service already knows about to this activity's memory watcher. + * + * A configuration change replaces the activity and its [MemoryUsageWatcher] but not the service + * or the processes it is driving, and both pids are reported on one-shot callbacks that a + * replacement listener has already missed -- the tooling server's on the start it did not + * request, the daemon's on the build that spawned it. Without this the chart came back after a + * rotation plotting the IDE alone, which is the smallest of the three. + */ + private fun readoptWatchedProcesses(service: GradleBuildService) { + val tooling = service.toolingServerPid + val daemon = service.gradleDaemonPid + if (tooling == null && daemon == null) { + return + } + + log.info( + "Re-adopting watched processes: tooling server {}, Gradle daemon {}", + tooling, + daemon + ) + tooling?.let { memoryUsageWatcher.watchProcess(it, PROC_GRADLE_TOOLING) } + daemon?.let { memoryUsageWatcher.watchProcess(it, PROC_GRADLE_DAEMON) } + resetMemUsageChart() + } + + protected fun onGradleBuildServiceConnected(service: GradleBuildService) { + log.info("Connected to Gradle build service") + + editorViewModel.clearBuildServiceCallback() + editorViewModel.isBoundToBuildSerice = true + Lookup.getDefault().update(BuildService.KEY_BUILD_SERVICE, service) + service.setEventListener(mBuildEventListener) + readoptWatchedProcesses(service) + + if (service.isToolingServerStarted()) { + initializeProject() + return + } + + service.startToolingServer { pid -> + memoryUsageWatcher.watchProcess(pid, PROC_GRADLE_TOOLING) + resetMemUsageChart() + + service.metadata().whenComplete { metadata, err -> + if (metadata == null || err != null) { + log.error("Failed to get tooling server metadata") + return@whenComplete + } + + if (pid != metadata.pid) { + log.warn( + "Tooling server pid mismatch. Expected: {}, Actual: {}. Replacing memory watcher...", + pid, + metadata.pid, + ) + memoryUsageWatcher.watchProcess(metadata.pid, PROC_GRADLE_TOOLING) + resetMemUsageChart() + } + } + + initializeProject() + } + } + + protected open fun onProjectInitialized(result: InitializeResult.Success) { + // A callback queued before onPause cancelled the future still lands here after the teardown. + if (!sessionCloser.record { ProjectManagerImpl.getInstance().indexingServiceManager }) { + log.info("Project closed before its initialization finished, skipping its setup") + return + } + Memprof.mark("sync_complete") + editorActivityScope.launch(Dispatchers.IO) { + val manager = ProjectManagerImpl.getInstance() + val gradleBuildResult = + Memprof.phase("Parse project model", "cache_parsed") { span -> + val startMs = if (span.isRecording) System.currentTimeMillis() else 0L + val parsed = ProjectSyncHelper.readGradleBuild(result.cacheFile) + if (span.isRecording) { + span.put("bytes", result.cacheFile.length()) + span.put("durationMs", System.currentTimeMillis() - startMs) + if (parsed.isFailure) { + span.put("failed", 1) + } + } + // readGradleBuild returns its failure rather than throwing, so the phase would end as finished. + if (parsed.isFailure) { + span.abandon() + } + parsed + } + if (gradleBuildResult.isFailure) { + val error = gradleBuildResult.exceptionOrNull() + log.error("Failed to read project cache", error) + if (error != null) { +// Sentry.captureException(error) + } + + withContext(Dispatchers.Main) { postProjectInit(false, CACHE_READ_ERROR) } + return@launch + } + + manager.setup(gradleBuildResult.getOrThrow()) + manager.notifyProjectUpdate() + updateBuildVariants(manager.androidBuildVariants) + + withContext(Dispatchers.Main) { + postProjectInit(isSuccessful = true, failure = null) + } + } + } + + protected open fun preProjectInit() { + setStatus(getString(string.msg_initializing_project)) + editorViewModel.isInitializing = true + } + + protected open fun postProjectInit( + isSuccessful: Boolean, + failure: TaskExecutionResult.Failure?, + ) { + val manager = ProjectManagerImpl.getInstance() + if (!isSuccessful) { + // Get project name for error message + val projectName = + try { + val project = manager.workspace?.rootProject + if (project != null) { + project.name.takeIf { it.isNotEmpty() } + ?: manager.projectDir.name + } else { + manager.projectDir.name + } + } catch (th: Throwable) { + manager.projectDir.name + } + + val initFailed = + if (projectName.isNotEmpty()) { + getString(string.msg_project_initialization_failed_with_name, projectName) + } else { + getString(string.msg_project_initialization_failed) + } + setStatus(initFailed) + + val msg = + when (failure) { + PROJECT_DIRECTORY_INACCESSIBLE -> string.msg_project_dir_inaccessible + PROJECT_NOT_DIRECTORY -> string.msg_file_is_not_dir + PROJECT_NOT_FOUND -> string.msg_project_dir_doesnt_exist + CACHE_READ_ERROR -> string.msg_project_cache_read_failure + else -> null + }?.let { + "$initFailed: ${getString(it)}" + } + + flashError(msg ?: initFailed) + + editorViewModel.isInitializing = false + return + } + + initialSetup() + setStatus(getString(string.msg_project_initialized)) + editorViewModel.isInitializing = false + + if (mFindInProjectDialog?.isShowing == true) { + mFindInProjectDialog!!.dismiss() + } + + mFindInProjectDialog = null // Create the dialog again if needed + } + + private fun updateBuildVariants(buildVariants: Map) { + // avoid using the 'runOnUiThread' method defined in the activity + dev.mutwakil.androidide.tasks.runOnUiThread { + buildVariantsViewModel.buildVariants = buildVariants + buildVariantsViewModel.resetUpdatedSelections() + } + } + + protected open fun createFindInProjectDialog(mode: SearchMode = SearchMode.FIND): AlertDialog? { + val manager = ProjectManagerImpl.getInstance() + if (manager.workspace == null) { + log.warn("No root project model found. Is the project initialized?") + flashError(getString(string.msg_project_not_initialized)) + return null + } + + val moduleDirs = + try { + manager.gradleBuild!! + .subProjectList + .stream() + .map { project -> project.projectDir } + .collect(Collectors.toList()) + } catch (_: Throwable) { + flashError(getString(string.msg_no_modules)) + emptyList() + } + + return createFindInProjectDialog(moduleDirs, manager.projectDir, mode) + } + + protected open fun createFindInProjectDialog( + moduleDirs: List, + projectRoot: File, + mode: SearchMode, + ): AlertDialog? { + val isReplace = mode == SearchMode.REPLACE + val srcDirs = mutableListOf() + val binding = LayoutSearchProjectBinding.inflate(layoutInflater) + binding.modulesContainer.removeAllViews() + binding.replacement.isVisible = isReplace + binding.matchCase.isChecked = isReplace + binding.wholeWord.isChecked = false + binding.projectFiles.isChecked = isReplace + + for (i in moduleDirs.indices) { + val module = moduleDirs[i] + val src = File(module, "src") + + if (!module.exists() || !module.isDirectory || !src.exists() || !src.isDirectory) { + continue + } + + val check = CheckBox(this) + check.text = module.name + check.isChecked = true + + val params = MarginLayoutParams(-2, -2) + params.bottomMargin = dpToPx(4f) + binding.modulesContainer.addView(check, params) + srcDirs.add(src) + } + + val builder = newMaterialDialogBuilder(this) + builder.setTitle(if (isReplace) string.menu_replace_project else string.menu_find_project) + builder.setView(binding.root) + builder.setCancelable(false) + builder.setPositiveButton(if (isReplace) string.btn_find_matches else string.menu_find) { dialog, _ -> + val text = + binding.input.editText!! + .text + .toString() + .trim() + if (text.isEmpty()) { + flashError(string.msg_empty_search_query) + return@setPositiveButton + } + + val searchDirs = mutableListOf() + for (i in 0 until binding.modulesContainer.childCount) { + val check = binding.modulesContainer.getChildAt(i) as CheckBox + if (check.isChecked) { + searchDirs.add(srcDirs[i]) + } + } + + val extensions = + binding.filter.editText!! + .text + .toString() + .trim() + val extensionList = mutableListOf() + if (extensions.isNotEmpty()) { + if (extensions.contains("|")) { + for ( + str in + extensions + .split(Pattern.quote("|").toRegex()) + .dropLastWhile { it.isEmpty() } + .toTypedArray() + ) { + val token = str.trim() + if (token.isEmpty()) { + continue + } + // Trim so a pipe-split token keeps no surrounding space; the file-name + // suffix test is endsWith(), which a stray " kt" would never satisfy. + extensionList.add(token) + } + } else { + extensionList.add(extensions) + } + } + + if (binding.projectFiles.isChecked) { + searchDirs.add(projectRoot) + } + + if (searchDirs.isEmpty()) { + flashError(string.msg_select_search_modules) + return@setPositiveButton + } + + val options = + ProjectSearchOptions( + matchCase = binding.matchCase.isChecked, + wholeWord = binding.wholeWord.isChecked, + bufferOverrides = openBufferSnapshots(), + excludedDirNames = + if (binding.projectFiles.isChecked) ProjectSearchOptions.PROJECT_ROOT_EXCLUDED_DIR_NAMES else emptySet(), + nameExclusionRoot = if (binding.projectFiles.isChecked) projectRoot else null, + excludedDirs = if (binding.projectFiles.isChecked) moduleDirs.map { + File( + it, + "src" + ) + }.toSet() else emptySet(), + ) + val replacement = + binding.replacement.editText!! + .text + .toString() + dialog.dismiss() + discardReplaceUndo() + + getProgressSheet(string.msg_searching_project)?.apply { + show(supportFragmentManager, "search_in_project_progress") + } + + RecursiveFileSearcher.searchRecursiveAsync( + text, + extensionList, + searchDirs, + options, + ) { results -> + if (isReplace) { + onReplaceSearchResults(text, replacement, options, results) + return@searchRecursiveAsync + } + handleSearchResults(results) + } + } + + builder.setNegativeButton(android.R.string.cancel) { dialog, _ -> dialog.dismiss() } + val dialog = builder.create() + + if (isReplace) { + mReplaceInProjectDialog = dialog + } else { + mFindInProjectDialog = dialog + } + return dialog + } + + abstract fun getEditorForFile(file: File): CodeEditorView? + + protected fun openBufferSnapshots(): Map = + editorViewModel + .getOpenedFiles() + .mapNotNull { file -> + getEditorForFile(file) + ?.editor + ?.text + ?.toString() + ?.let { file.absoluteFile to it } + }.toMap() + + private fun onReplaceSearchResults( + query: String, + replacement: String, + options: ProjectSearchOptions, + results: Map>, + ) { + handleSearchResults(results) + if (results.isNotEmpty()) { + editorViewModel.startReplaceSession( + ReplaceSession( + query, + replacement, + options, + results + ) + ) + } + } + + override fun onReplaceRequested(session: ReplaceSession): Boolean { + if (replaceCoordinator.isBusy) { + flashError(string.msg_replace_busy) + return false + } + editorViewModel.onSearchResultsReady(emptyMap()) + lifecycleScope.launch { + val report = replaceCoordinator.replace(session) + showReplaceReport(report, undone = false) + } + return true + } + + private fun discardReplaceUndo() { + replaceReportFlashbar?.dismiss() + replaceReportFlashbar = null + replaceCoordinator.discardUndo() + } + + private fun showReplaceReport( + report: ReplaceCoordinator.Report, + undone: Boolean, + ) { + val issues = report.skipped.size + report.failed.size + val message = + when { + undone -> { + getString(string.msg_replace_undone, report.changedFiles.size) + } + + issues == 0 -> { + getString( + string.msg_replace_done, + report.replacedMatches, + report.changedFiles.size + ) + } + + else -> { + getString( + string.msg_replace_done_with_issues, + report.replacedMatches, + report.changedFiles.size, + report.skipped.size, + report.failed.size, + ) + } + } + val canUndo = !undone && replaceCoordinator.canUndo + val builder = + flashbarBuilder(duration = if (canUndo) DURATION_INDEFINITE else DURATION_LONG).message( + message + ) + if (canUndo) { + builder + .positiveActionText(string.undo) + .positiveActionTapListener { bar -> + if (replaceCoordinator.isBusy) { + flashError(string.msg_replace_busy) + return@positiveActionTapListener + } + bar.dismiss() + replaceReportFlashbar = null + lifecycleScope.launch { + val undoReport = replaceCoordinator.undo() + showReplaceReport(undoReport, undone = true) + } + }.negativeActionText(android.R.string.ok) + .negativeActionTapListener { _ -> + discardReplaceUndo() + } + } + replaceReportFlashbar?.dismiss() + replaceReportFlashbar = builder.build().also { it.showOnUiThread() } + if (issues > 0) { + showReplaceIssues(report) + } + } + + private fun showReplaceIssues(report: ReplaceCoordinator.Report) { + val lines = + report.skipped.map { (file, reason) -> + val reasonText = + when (reason) { + SkipReason.CHANGED_SINCE_SEARCH -> string.reason_changed_since_search + SkipReason.CHANGED_SINCE_REPLACE -> string.reason_changed_since_replace + SkipReason.TAB_CLOSED -> string.reason_tab_closed + } + "${file.name}: ${getString(reasonText)}" + } + report.failed.map { "${it.file.name}: ${it.message}" } + newMaterialDialogBuilder(this) + .setTitle(string.title_replace_report) + .setMessage(lines.joinToString("\n")) + .setPositiveButton(android.R.string.ok, null) + .show() + } + + enum class SearchMode { FIND, REPLACE } + + private fun initialSetup() { + val manager = ProjectManagerImpl.getInstance() + GeneralPreferences.lastOpenedProject = manager.projectDirPath + try { + val project = manager.workspace?.rootProject + if (project == null) { + log.warn("GradleProject not initialized. Skipping initial setup...") + return + } + + var projectName = project.name + if (projectName.isEmpty()) { + projectName = manager.projectDir.name + } + + supportActionBar!!.subtitle = projectName + } catch (_: Throwable) { + // ignored + } + } + + private fun attachLanguageClient() { + val activity = this as EditorHandlerActivity + if (IDELanguageClientImpl.isInitialized()) { + IDELanguageClientImpl.getInstance().setActivity(activity) + } else { + IDELanguageClientImpl.initialize(activity) + } + + connectClient(IDELanguageClientImpl.getInstance()) + } + + private fun initLspClient() { + attachLanguageClient() + connectClient(IDELanguageClientImpl.getInstance()) + } + + open fun getProgressSheet(msg: Int): ProgressSheet? { + doDismissSearchProgress() + + mSearchingProgress = + ProgressSheet().also { + it.isCancelable = false + it.setMessage(getString(msg)) + it.setSubMessageEnabled(false) + } + + return mSearchingProgress + } +} \ No newline at end of file diff --git a/core/app/src/main/java/dev/mutwakil/androidide/activities/editor/ProjectSessionCloser.kt b/core/app/src/main/java/dev/mutwakil/androidide/activities/editor/ProjectSessionCloser.kt new file mode 100644 index 0000000000..14b0888067 --- /dev/null +++ b/core/app/src/main/java/dev/mutwakil/androidide/activities/editor/ProjectSessionCloser.kt @@ -0,0 +1,66 @@ +package dev.mutwakil.androidide.activities.editor + +import org.slf4j.LoggerFactory + +/** + * Runs an editor's project-session teardown at most once, and only for the session it opened. + * + * The teardown stops the language servers before it destroys the project: a stopped server can no + * longer pick up the next project's indexing manager, and the indexes it still holds close quietly. + * It runs from `onPause` while finishing, because `isFinishing` is reliable there and the next + * editor may open a project before this one's `onDestroy`. A configuration change never runs it: + * `isFinishing` is false then, and the servers must survive the recreation. `preDestroy` calls it + * too, for a `finish()` that arrives while already paused. + * + * Servers, the project manager and Quick Build are process-wide, so the teardown is skipped when the + * current session is not the one [record]ed, which means another editor already owns them. With + * nothing recorded (the project never finished opening, or a recreated editor skipped it) it tears + * down as before recording existed. The check only tells sessions apart when a new manager was + * created between them. + * + * [record] runs on the project initialization callback's thread and [close] on the main thread, so + * both hold the lock: a session recorded after the teardown would never be closed. + * + * @param currentSession Returns the current session without creating one. + * @param teardown Stops the servers and destroys the project. + */ +internal class ProjectSessionCloser( + private val currentSession: () -> S?, + private val teardown: () -> Unit, +) { + private companion object { + private val log = LoggerFactory.getLogger(ProjectSessionCloser::class.java) + } + + private var recorded: S? = null + private var tornDown = false + + /** + * Records the session [session] returns as the one this editor opened, and returns whether it did. + * + * Once the teardown has run it returns false without calling [session], since resolving a session + * may create one that nothing would close. + */ + @Synchronized + fun record(session: () -> S): Boolean { + if (tornDown) return false + recorded = session() + return true + } + + /** Tears down when nothing was recorded or this editor still owns the current session. */ + @Synchronized + fun close() { + if (recorded == null || currentSession() === recorded) runTeardown() else skip() + } + + private fun runTeardown() { + if (tornDown) return + tornDown = true + teardown() + } + + private fun skip() { + if (!tornDown) log.info("Skipping project teardown: this editor does not own the current session") + } +} \ No newline at end of file diff --git a/core/app/src/main/java/dev/mutwakil/androidide/services/builder/ToolingMessageTap.kt b/core/app/src/main/java/dev/mutwakil/androidide/services/builder/ToolingMessageTap.kt new file mode 100644 index 0000000000..0ea8342c16 --- /dev/null +++ b/core/app/src/main/java/dev/mutwakil/androidide/services/builder/ToolingMessageTap.kt @@ -0,0 +1,45 @@ +/* + * 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 dev.mutwakil.androidide.services.builder + +import org.eclipse.lsp4j.jsonrpc.MessageConsumer +import java.io.InputStream + +/** + * Observes what one tooling server process sends the IDE. + * + * Only the profileable variant installs a [factory], so debug and release builds carry this + * interface and nothing behind it. + */ +interface ToolingMessageTap { + /** Wraps the server's raw output before the JSON-RPC reader consumes it. */ + fun wrapInput(input: InputStream): InputStream + + /** Wraps the JSON-RPC consumer of messages the server sends. */ + fun wrapMessages(consumer: MessageConsumer): MessageConsumer + + /** Called once the server's message reader has stopped, so no further message reaches [wrapMessages]. */ + fun onServerStopped() + + companion object { + /** Creates a tap per server process, or null to observe nothing. */ + @JvmStatic + @Volatile + var factory: (() -> ToolingMessageTap)? = null + } +} \ No newline at end of file diff --git a/core/app/src/main/java/dev/mutwakil/androidide/services/builder/ToolingServerRunner.kt b/core/app/src/main/java/dev/mutwakil/androidide/services/builder/ToolingServerRunner.kt index 973f69ff69..c9a1d99675 100644 --- a/core/app/src/main/java/dev/mutwakil/androidide/services/builder/ToolingServerRunner.kt +++ b/core/app/src/main/java/dev/mutwakil/androidide/services/builder/ToolingServerRunner.kt @@ -31,6 +31,8 @@ import dev.mutwakil.androidide.logging.provider.IdeLogRouter import kotlinx.coroutines.CancellationException import kotlinx.coroutines.CoroutineName import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.CoroutineStart +import kotlinx.coroutines.DelicateCoroutinesApi import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Job import kotlinx.coroutines.joinAll @@ -93,6 +95,7 @@ internal class ToolingServerRunner( this.listener = listener } + @OptIn(DelicateCoroutinesApi::class) fun startAsync(envs: Map) = runnerScope .launch { @@ -149,7 +152,8 @@ internal class ToolingServerRunner( log.info("Tooling API server running with PID: {}", pid) - val inputStream = process.inputStream + val messageTap = ToolingMessageTap.factory?.invoke() + val inputStream = messageTap?.wrapInput(process.inputStream) ?: process.inputStream val outputStream = process.outputStream val errorStream = process.errorStream @@ -173,6 +177,7 @@ internal class ToolingServerRunner( observer!!.getClient(), inputStream, outputStream, + wrapMessages = { consumer -> messageTap?.wrapMessages(consumer) ?: consumer }, ) val future = launcher.startListening() @@ -191,8 +196,9 @@ internal class ToolingServerRunner( listener = null // Wait(block) until the process terminates + // ATOMIC so a release() racing this launch still runs the body, and the finally with it. val serverJob = - launch(Dispatchers.IO) { + launch(Dispatchers.IO, start = CoroutineStart.ATOMIC) { try { future.get() } catch (err: Throwable) { @@ -202,6 +208,10 @@ internal class ToolingServerRunner( // rethrow the error throw err + } finally { + // Here, not after joinAll: a cancel ends joinAll at once, while the + // blocking get() above returns only once the reader has stopped. + messageTap?.onServerStopped() } } diff --git a/core/app/src/profileable/java/dev/mutwakil/androidide/memprof/AllocationSampler.kt b/core/app/src/profileable/java/dev/mutwakil/androidide/memprof/AllocationSampler.kt index 1aee4f230f..5d17d2cebf 100644 --- a/core/app/src/profileable/java/dev/mutwakil/androidide/memprof/AllocationSampler.kt +++ b/core/app/src/profileable/java/dev/mutwakil/androidide/memprof/AllocationSampler.kt @@ -18,7 +18,6 @@ package dev.mutwakil.androidide.memprof import android.os.Debug -import org.slf4j.LoggerFactory import java.io.File import java.util.concurrent.atomic.AtomicBoolean @@ -31,7 +30,7 @@ import java.util.concurrent.atomic.AtomicBoolean * between two samples is exactly what was allocated between them. */ object AllocationSampler { - private val logger = LoggerFactory.getLogger(AllocationSampler::class.java) + private val logger = MemprofLog("AllocationSampler") /** Fine enough to separate a completion request from its neighbours, cheap enough to leave on. */ const val DEFAULT_INTERVAL_MS = 250L @@ -68,7 +67,7 @@ object AllocationSampler { @JvmOverloads fun start(intervalMs: Long = DEFAULT_INTERVAL_MS) { if (!running.compareAndSet(false, true)) { - logger.info("MEMPROF|sampler|{}|state=already_running", System.currentTimeMillis()) + logger.i("MEMPROF|sampler|{}|state=already_running", System.currentTimeMillis()) return } @@ -77,7 +76,7 @@ object AllocationSampler { thread.priority = Thread.MAX_PRIORITY worker = thread thread.start() - logger.info("MEMPROF|sampler|{}|state=started|intervalMs={}", System.currentTimeMillis(), intervalMs) + logger.i("MEMPROF|sampler|{}|state=started|intervalMs={}", System.currentTimeMillis(), intervalMs) } /** Stops sampling. Safe to call when not running. */ @@ -87,17 +86,17 @@ object AllocationSampler { } worker?.interrupt() worker = null - logger.info("MEMPROF|sampler|{}|state=stopped", System.currentTimeMillis()) + logger.i("MEMPROF|sampler|{}|state=stopped", System.currentTimeMillis()) } /** Emits one sample immediately, tagged with [reason]. */ fun sampleNow(reason: String) { - logger.info(sample(reason, RuntimeHeapCounters.read())) + logger.i(sample(reason, RuntimeHeapCounters.read())) } /** Emits a named marker plus a sample, so a phase boundary and its counters share a timestamp. */ fun mark(name: String) { - logger.info("MEMPROF|mark|{}|name={}", System.currentTimeMillis(), name) + logger.i("MEMPROF|mark|{}|name={}", System.currentTimeMillis(), name) sampleNow(name) } @@ -106,7 +105,7 @@ object AllocationSampler { val counters = RuntimeHeapCounters.read() // DEBUG, not INFO: profileable inherits release's Sentry setup, which turns an INFO // line into a breadcrumb, and this fires up to 4 times a second. - logger.debug(sample("tick", counters)) + logger.d(sample("tick", counters)) onTick?.invoke(counters.usedBytes) dumpIfAboveThreshold() try { @@ -141,12 +140,12 @@ object AllocationSampler { } val path = "$dumpDir/memprof-peak-${System.currentTimeMillis()}.hprof" - logger.info("MEMPROF|hprof_start|{}|path={}|usedMb={}", System.currentTimeMillis(), path, used shr 20) + logger.i("MEMPROF|hprof_start|{}|path={}|usedMb={}", System.currentTimeMillis(), path, used shr 20) runCatching { Debug.dumpHprofData(path) } .onSuccess { - logger.info("MEMPROF|hprof|{}|path={}|bytes={}", System.currentTimeMillis(), path, File(path).length()) + logger.i("MEMPROF|hprof|{}|path={}|bytes={}", System.currentTimeMillis(), path, File(path).length()) }.onFailure { failure -> - logger.error("MEMPROF|hprof_failed|{}|path={}", System.currentTimeMillis(), path, failure) + logger.e("MEMPROF|hprof_failed|{}|path={}", System.currentTimeMillis(), path, failure) } } diff --git a/core/app/src/profileable/java/dev/mutwakil/androidide/memprof/MemprofLog.kt b/core/app/src/profileable/java/dev/mutwakil/androidide/memprof/MemprofLog.kt new file mode 100644 index 0000000000..5e6f8463e0 --- /dev/null +++ b/core/app/src/profileable/java/dev/mutwakil/androidide/memprof/MemprofLog.kt @@ -0,0 +1,71 @@ +/* + * 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 dev.mutwakil.androidide.memprof + +import android.util.Log +import org.slf4j.helpers.MessageFormatter + +/** + * Writes memprof lines straight to logcat under [tag], bypassing the slf4j logger. + * + * The IDE's slf4j provider also hands every line to the IDE Logs pane. The allocation sampler alone + * writes a line every 250 ms, so routed through slf4j the measurement lines flood the pane the user + * reads, and the pane's buffering adds heap and CPU work to the very process being measured. The + * harness scripts read logcat, which is the only place these lines are meant for. + * + * Messages are formatted by slf4j's [MessageFormatter], placeholders and trailing [Throwable] alike, + * so call sites read the same as the slf4j calls they replaced. + */ +class MemprofLog( + private val tag: String, +) { + /** Logs at debug priority. */ + fun d( + format: String, + vararg args: Any?, + ) = write(Log.DEBUG, format, args) + + /** Logs at info priority. */ + fun i( + format: String, + vararg args: Any?, + ) = write(Log.INFO, format, args) + + /** Logs at warn priority. */ + fun w( + format: String, + vararg args: Any?, + ) = write(Log.WARN, format, args) + + /** Logs at error priority. */ + fun e( + format: String, + vararg args: Any?, + ) = write(Log.ERROR, format, args) + + private fun write( + priority: Int, + format: String, + args: Array, + ) { + val formatted = MessageFormatter.arrayFormat(format, args) + val throwable = formatted.throwable + val message = formatted.message + Log.println(priority, tag, if (throwable == null) message else message + '\n' + Log.getStackTraceString(throwable)) + } +} diff --git a/core/app/src/profileable/java/dev/mutwakil/androidide/memprof/MemprofReceiver.kt b/core/app/src/profileable/java/dev/mutwakil/androidide/memprof/MemprofReceiver.kt index d2703a9e54..92054d18bc 100644 --- a/core/app/src/profileable/java/dev/mutwakil/androidide/memprof/MemprofReceiver.kt +++ b/core/app/src/profileable/java/dev/mutwakil/androidide/memprof/MemprofReceiver.kt @@ -28,7 +28,6 @@ import dev.mutwakil.androidide.lsp.models.CompletionParams import dev.mutwakil.androidide.lsp.xml.XMLLanguageServer import dev.mutwakil.androidide.models.Position import dev.mutwakil.androidide.progress.ICancelChecker -import org.slf4j.LoggerFactory import java.io.File import java.util.concurrent.Executors @@ -56,7 +55,7 @@ class MemprofReceiver : BroadcastReceiver() { ) { val op = intent.getStringExtra(EXTRA_OP) if (op == null) { - logger.warn("MEMPROF|error|{}|reason=missing_op", System.currentTimeMillis()) + logger.w("MEMPROF|error|{}|reason=missing_op", System.currentTimeMillis()) return } @@ -66,7 +65,7 @@ class MemprofReceiver : BroadcastReceiver() { try { dispatch(op, intent) } catch (failure: Throwable) { - logger.error("MEMPROF|error|{}|op={}", System.currentTimeMillis(), op, failure) + logger.e("MEMPROF|error|{}|op={}", System.currentTimeMillis(), op, failure) } } // Nothing reads the broadcast result, and holding it through an hprof dump or repeated @@ -111,7 +110,7 @@ class MemprofReceiver : BroadcastReceiver() { "dumpat" -> { val fraction = intent.getFloatExtra("fraction", 0.85f).toDouble() AllocationSampler.dumpAtFraction = fraction - logger.info("MEMPROF|dumpat|{}|fraction={}", System.currentTimeMillis(), fraction) + logger.i("MEMPROF|dumpat|{}|fraction={}", System.currentTimeMillis(), fraction) } "completion" -> { @@ -124,7 +123,7 @@ class MemprofReceiver : BroadcastReceiver() { } else -> { - logger.warn("MEMPROF|error|{}|reason=unknown_op|op={}", System.currentTimeMillis(), op) + logger.w("MEMPROF|error|{}|reason=unknown_op|op={}", System.currentTimeMillis(), op) } } } @@ -134,7 +133,7 @@ class MemprofReceiver : BroadcastReceiver() { AllocationSampler.sampleNow("pre_hprof") val started = System.currentTimeMillis() Debug.dumpHprofData(target) - logger.info( + logger.i( "MEMPROF|hprof|{}|path={}|durationMs={}|bytes={}", System.currentTimeMillis(), target, @@ -152,19 +151,19 @@ class MemprofReceiver : BroadcastReceiver() { ) { val source = File(file) if (!source.isFile) { - logger.warn("MEMPROF|error|{}|reason=no_such_file|file={}", System.currentTimeMillis(), file) + logger.w("MEMPROF|error|{}|reason=no_such_file|file={}", System.currentTimeMillis(), file) return } val serverId = serverIdFor(source) if (serverId == null) { - logger.warn("MEMPROF|error|{}|reason=no_server_for|file={}", System.currentTimeMillis(), file) + logger.w("MEMPROF|error|{}|reason=no_server_for|file={}", System.currentTimeMillis(), file) return } val server = ILanguageServerRegistry.default.getServer(serverId) if (server == null) { - logger.warn("MEMPROF|error|{}|reason=server_absent|server={}", System.currentTimeMillis(), serverId) + logger.w("MEMPROF|error|{}|reason=server_absent|server={}", System.currentTimeMillis(), serverId) return } @@ -183,7 +182,7 @@ class MemprofReceiver : BroadcastReceiver() { val elapsed = System.currentTimeMillis() - started AllocationSampler.sampleNow("post_completion_$iteration") - logger.info( + logger.i( "MEMPROF|completion|{}|server={}|iteration={}|prefix={}|items={}|incomplete={}|durationMs={}", System.currentTimeMillis(), serverId, @@ -234,7 +233,7 @@ class MemprofReceiver : BroadcastReceiver() { } companion object { - private val logger = LoggerFactory.getLogger(MemprofReceiver::class.java) + private val logger = MemprofLog("MemprofReceiver") private val worker = Executors.newSingleThreadExecutor { runnable -> Thread(runnable, "memprof-receiver").apply { isDaemon = true } diff --git a/core/app/src/profileable/java/dev/mutwakil/androidide/memprof/MemprofReportWriter.kt b/core/app/src/profileable/java/dev/mutwakil/androidide/memprof/MemprofReportWriter.kt index fdf917e5f7..21a12acf82 100644 --- a/core/app/src/profileable/java/dev/mutwakil/androidide/memprof/MemprofReportWriter.kt +++ b/core/app/src/profileable/java/dev/mutwakil/androidide/memprof/MemprofReportWriter.kt @@ -17,7 +17,6 @@ package dev.mutwakil.androidide.memprof -import org.slf4j.LoggerFactory import java.io.File import java.util.concurrent.Executors import java.util.concurrent.atomic.AtomicBoolean @@ -65,7 +64,7 @@ internal class MemprofReportWriter( /** Prints the report to logcat, one line per log entry, so a reader sees the table intact. */ fun log() { // DEBUG, not INFO: an INFO line becomes a Sentry breadcrumb, and the report is dozens of lines. - render().lineSequence().forEach { line -> logger.debug("MEMPROF|report| {}", line) } + render().lineSequence().forEach { line -> logger.d("MEMPROF|report| {}", line) } } private fun render(): String = report.render(System.currentTimeMillis(), RuntimeHeapCounters.read()) @@ -78,11 +77,11 @@ internal class MemprofReportWriter( val temporary = File(target.parentFile, target.name + ".tmp") temporary.writeText(text) check(temporary.renameTo(target)) { "rename to $target failed" } - }.onFailure { failure -> logger.error("MEMPROF|report_write_failed|{}", lastWriteMs, failure) } + }.onFailure { failure -> logger.e("MEMPROF|report_write_failed|{}", lastWriteMs, failure) } } private companion object { - val logger = LoggerFactory.getLogger(MemprofReportWriter::class.java) + val logger = MemprofLog("MemprofReportWriter") val io = Executors.newSingleThreadExecutor { runnable -> diff --git a/core/app/src/profileable/java/dev/mutwakil/androidide/memprof/MemprofSession.kt b/core/app/src/profileable/java/dev/mutwakil/androidide/memprof/MemprofSession.kt index cca67ca4f1..7058fe69e8 100644 --- a/core/app/src/profileable/java/dev/mutwakil/androidide/memprof/MemprofSession.kt +++ b/core/app/src/profileable/java/dev/mutwakil/androidide/memprof/MemprofSession.kt @@ -20,6 +20,7 @@ package dev.mutwakil.androidide.memprof import android.content.Context import android.os.Process import android.os.SystemClock +import dev.mutwakil.androidide.services.builder.ToolingMessageTap import java.io.File import java.text.SimpleDateFormat import java.util.Date @@ -36,7 +37,7 @@ internal object MemprofSession { private set /** - * Installs the [Memprof] sink and starts the allocation sampler. + * Installs the [Memprof] sink and the tooling message probe, and starts the allocation sampler. * * Safe on the main thread: resolving the files directory touches the disk, so it happens on a * background thread, and the report writer does its own I/O on its own thread. @@ -50,6 +51,7 @@ internal object MemprofSession { writer = reportWriter Memprof.sink = ProfileableMemprofSink(report, reportWriter) + ToolingMessageTap.factory = ::ToolingMessageProbe AllocationSampler.onTick = { usedBytes -> report.sampled(usedBytes) /* diff --git a/core/app/src/profileable/java/dev/mutwakil/androidide/memprof/MessageBoundaryInputStream.kt b/core/app/src/profileable/java/dev/mutwakil/androidide/memprof/MessageBoundaryInputStream.kt new file mode 100644 index 0000000000..5a795e008d --- /dev/null +++ b/core/app/src/profileable/java/dev/mutwakil/androidide/memprof/MessageBoundaryInputStream.kt @@ -0,0 +1,98 @@ +/* + * 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 dev.mutwakil.androidide.memprof + +import java.io.FilterInputStream +import java.io.InputStream + +/** + * Follows the `Content-Length` framing of a JSON-RPC stream and calls [onContentStart] with each + * message's content length as soon as its header block has been read. + * + * lsp4j reads the header block a byte at a time, so the callback runs before the reader has read + * any of the content, let alone decoded or parsed it. + */ +internal class MessageBoundaryInputStream( + input: InputStream, + private val onContentStart: (contentLength: Long) -> Unit, +) : FilterInputStream(input) { + private val headerLine = StringBuilder() + private var contentLength = -1L + private var contentRemaining = 0L + + override fun read(): Int = + super.read().also { byte -> + if (byte >= 0) observe(byte.toByte()) + } + + override fun read( + buffer: ByteArray, + offset: Int, + length: Int, + ): Int = + super.read(buffer, offset, length).also { n -> + var i = offset + val end = offset + maxOf(n, 0) + while (i < end) { + if (contentRemaining > 0) { + val skipped = minOf(contentRemaining, (end - i).toLong()) + contentRemaining -= skipped + i += skipped.toInt() + } else { + observeHeader(buffer[i++]) + } + } + } + + private fun observe(byte: Byte) { + if (contentRemaining > 0) { + contentRemaining-- + } else { + observeHeader(byte) + } + } + + private fun observeHeader(byte: Byte) { + val c = (byte.toInt() and 0xff).toChar() + if (c != '\n') { + headerLine.append(c) + return + } + val line = headerLine.trimEnd('\r') + headerLine.setLength(0) + if (line.isNotEmpty()) { + parseHeader(line) + } else if (contentLength >= 0) { + contentRemaining = contentLength + val length = contentLength + contentLength = -1 + onContentStart(length) + } + } + + private fun parseHeader(line: CharSequence) { + val colon = line.indexOf(':') + if (colon > 0 && line.substring(0, colon).trim().equals(CONTENT_LENGTH, ignoreCase = true)) { + contentLength = line.substring(colon + 1).trim().toLongOrNull() ?: -1 + } + } + + private companion object { + const val CONTENT_LENGTH = "Content-Length" + } +} diff --git a/core/app/src/profileable/java/dev/mutwakil/androidide/memprof/ProfileableMemprofSink.kt b/core/app/src/profileable/java/dev/mutwakil/androidide/memprof/ProfileableMemprofSink.kt index 29b8125cf2..4245df4731 100644 --- a/core/app/src/profileable/java/dev/mutwakil/androidide/memprof/ProfileableMemprofSink.kt +++ b/core/app/src/profileable/java/dev/mutwakil/androidide/memprof/ProfileableMemprofSink.kt @@ -17,7 +17,6 @@ package dev.mutwakil.androidide.memprof -import org.slf4j.LoggerFactory import java.util.Collections import java.util.concurrent.atomic.AtomicBoolean @@ -42,7 +41,7 @@ internal class ProfileableMemprofSink( guarded("beginPhase", marker) { val start = Start.now() val phase = report.phaseStarted(title, start.epochMs, start.counters) - logger.info("MEMPROF|phase_begin|{}|marker={}|title={}", start.epochMs, marker, title) + logger.i("MEMPROF|phase_begin|{}|marker={}|title={}", start.epochMs, marker, title) writer.write() PhaseSpan(marker, phase, start, AsyncTraceSection(title)) } @@ -57,7 +56,7 @@ internal class ProfileableMemprofSink( } override fun mark(marker: String) { - logger.info("PHASE|{}|{}", marker, System.currentTimeMillis()) + logger.i("PHASE|{}|{}", marker, System.currentTimeMillis()) } /** @@ -72,7 +71,7 @@ internal class ProfileableMemprofSink( try { block() } catch (failure: Throwable) { - logger.error("MEMPROF|sink_failed|{}|op={}|label={}", System.currentTimeMillis(), op, label, failure) + logger.e("MEMPROF|sink_failed|{}|op={}|label={}", System.currentTimeMillis(), op, label, failure) MemprofSpan.None } @@ -115,7 +114,7 @@ internal class ProfileableMemprofSink( try { onEnd(System.currentTimeMillis(), RuntimeHeapCounters.read(), completed) } catch (failure: Throwable) { - logger.error("MEMPROF|sink_failed|{}|op=end|completed={}", System.currentTimeMillis(), completed, failure) + logger.e("MEMPROF|sink_failed|{}|op=end|completed={}", System.currentTimeMillis(), completed, failure) } } @@ -140,14 +139,14 @@ internal class ProfileableMemprofSink( trace.end() val putDetails = detailsSnapshot() report.phaseEnded(phase, nowMs, counters, putDetails, completed) - logger.info( + logger.i( if (completed) { MemprofLines.phaseLine(marker, nowMs, putDetails) } else { MemprofLines.phaseAbandonedLine(marker, nowMs, putDetails) }, ) - logger.info( + logger.i( MemprofLines.phaseEndLine( marker, nowMs, @@ -185,12 +184,12 @@ internal class ProfileableMemprofSink( report.sectionEnded(name, detail, durationMs, allocatedBytes) } // DEBUG, not INFO: an INFO line becomes a Sentry breadcrumb, and this fires once per file. - logger.debug(MemprofLines.fileLine(nowMs, allocatedBytes, durationMs, detail, name, completed)) + logger.d(MemprofLines.fileLine(nowMs, allocatedBytes, durationMs, detail, name, completed, detailsSnapshot())) writer.markDirty() } } private companion object { - val logger = LoggerFactory.getLogger(ProfileableMemprofSink::class.java) + val logger = MemprofLog("ProfileableMemprofSink") } } diff --git a/core/app/src/profileable/java/dev/mutwakil/androidide/memprof/ToolingMessageProbe.kt b/core/app/src/profileable/java/dev/mutwakil/androidide/memprof/ToolingMessageProbe.kt new file mode 100644 index 0000000000..ae1af603f7 --- /dev/null +++ b/core/app/src/profileable/java/dev/mutwakil/androidide/memprof/ToolingMessageProbe.kt @@ -0,0 +1,201 @@ +/* + * 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 dev.mutwakil.androidide.memprof + +import dev.mutwakil.androidide.services.builder.ToolingMessageTap +import org.eclipse.lsp4j.jsonrpc.MessageConsumer +import org.eclipse.lsp4j.jsonrpc.RemoteEndpoint +import org.eclipse.lsp4j.jsonrpc.messages.Message +import org.eclipse.lsp4j.jsonrpc.messages.NotificationMessage +import org.eclipse.lsp4j.jsonrpc.messages.RequestMessage +import java.io.InputStream + +/** + * Measures what the tooling server sends the IDE, so the cost of a build in the IDE's heap can be + * told apart from the Gradle daemon's. + * + * Each build is a [Memprof] phase from `client/prepareBuild` to `client/onBuildSuccessful` or + * `client/onBuildFailed`, reporting message counts and content bytes per JSON-RPC method. Every + * message of at least [LARGE_MESSAGE_BYTES] is also a [Memprof] section of its own, opened once its + * headers are read so it covers reading, decoding and parsing the content as well as handling it. + * + * [MemprofSession] installs it as the [ToolingMessageTap] factory. It logs a line per + * [PROGRESS_EVERY] messages to logcat (see [MemprofLog] for why not slf4j). + */ +internal class ToolingMessageProbe : ToolingMessageTap { + private var size = 0L + + @Volatile + private var largeMessage: MemprofSpan? = null + + @Volatile + private var build: BuildStats? = null + + /** Follows the server's message framing, to size each message before it is read. */ + override fun wrapInput(input: InputStream): InputStream = MessageBoundaryInputStream(input, ::onContentStart) + + /** Wraps the consumer of incoming messages; outgoing ones pass through untouched. */ + override fun wrapMessages(consumer: MessageConsumer): MessageConsumer = + if (consumer is RemoteEndpoint) { + MessageConsumer { message -> receive(message, consumer) } + } else { + consumer + } + + /** Abandons the open spans, in case the server exited mid-build or mid-message. */ + override fun onServerStopped() { + abandonLargeMessage() + abandonBuild() + } + + private fun abandonLargeMessage() { + val open = largeMessage + largeMessage = null + open?.abandon() + } + + private fun abandonBuild() { + val open = build + build = null + open?.abandon() + } + + /* + * Runs on the launcher's single reader thread, as does receive(), so each message's start is + * seen before that message is handed over. + */ + private fun onContentStart(contentLength: Long) { + // A message that failed to parse never reached receive(), so its section is still open. + abandonLargeMessage() + size = contentLength + if (contentLength >= LARGE_MESSAGE_BYTES) { + largeMessage = Memprof.beginSection("Tooling message", "bytes=$contentLength") + } + } + + private fun receive( + message: Message, + delegate: MessageConsumer, + ) { + val method = methodOf(message) + val section = largeMessage + largeMessage = null + + if (method == PREPARE_BUILD) { + abandonBuild() + build = BuildStats(Memprof.beginPhase("Run Gradle build", "build_complete")) + } + build?.record(method, size) + + if (section != null) { + log.i("MEMPROF|tooling_large_message|{}|method={}|bytes={}", System.currentTimeMillis(), method, size) + section.put("bytes", size) + try { + delegate.consume(message) + section.end() + } finally { + section.abandon() + } + } else { + delegate.consume(message) + } + + if (method == BUILD_SUCCESSFUL || method == BUILD_FAILED) { + build?.finish() + build = null + } + } + + private fun methodOf(message: Message): String = + when (message) { + is NotificationMessage -> message.method + is RequestMessage -> message.method + else -> "response" + } + + private class BuildStats( + private val span: MemprofSpan, + ) { + private val perMethod = LinkedHashMap() + private var messages = 0L + private var bytes = 0L + private var maxBytes = 0L + private var maxMethod = "" + + fun record( + method: String, + size: Long, + ) { + messages++ + bytes += size + if (size > maxBytes) { + maxBytes = size + maxMethod = method + } + val counts = perMethod.getOrPut(method) { LongArray(2) } + counts[0]++ + counts[1] += size + if (messages % PROGRESS_EVERY == 0L) { + log.i( + "MEMPROF|tooling_messages|{}|messages={}|bytes={}|maxBytes={}|maxMethod={}", + System.currentTimeMillis(), + messages, + bytes, + maxBytes, + maxMethod, + ) + } + } + + fun finish() { + putTotals() + span.end() + } + + /** A build the server dies in still reports what arrived, as that is the case this probe exists for. */ + fun abandon() { + putTotals() + span.abandon() + } + + private fun putTotals() { + span.put("messages", messages) + span.put("bytes", bytes) + span.put("maxMessageBytes", maxBytes) + for ((method, counts) in perMethod) { + val name = method.substringAfterLast('/') + span.put("$name.count", counts[0]) + span.put("$name.bytes", counts[1]) + } + } + } + + companion object { + private val log = MemprofLog("ToolingMessageProbe") + + private const val PREPARE_BUILD = "client/prepareBuild" + private const val BUILD_SUCCESSFUL = "client/onBuildSuccessful" + private const val BUILD_FAILED = "client/onBuildFailed" + + /** A message this big gets its own section; a log line is a few hundred bytes. */ + const val LARGE_MESSAGE_BYTES = 256L * 1024 + + /** How often, in messages, a build logs its running totals. */ + const val PROGRESS_EVERY = 1000L + } +} diff --git a/core/lsp-api/src/main/java/dev/mutwakil/androidide/lsp/api/ILanguageServer.kt b/core/lsp-api/src/main/java/dev/mutwakil/androidide/lsp/api/ILanguageServer.kt index e8d8e8d6cf..979105613e 100644 --- a/core/lsp-api/src/main/java/dev/mutwakil/androidide/lsp/api/ILanguageServer.kt +++ b/core/lsp-api/src/main/java/dev/mutwakil/androidide/lsp/api/ILanguageServer.kt @@ -62,8 +62,10 @@ interface ILanguageServer { * Called by client to notify the server to shutdown. Language servers must release all the * resources in use. * - * - * After this is called, clients must re-initialize the server. + * Called once when the project closes (normally from the editor's `onPause` while it finishes) or + * when the server is unregistered, and never on an activity recreation. It must not block. The project's indexes may close at any time after + * it returns; reads of a closed index return empty results. After this is called, clients must + * re-initialize the server. */ fun shutdown() diff --git a/editor/impl/src/main/java/dev/mutwakil/androidide/editor/ui/BaseEditorWindow.java b/editor/impl/src/main/java/dev/mutwakil/androidide/editor/ui/BaseEditorWindow.java index d674c3ef8d..2a3008d7d5 100644 --- a/editor/impl/src/main/java/dev/mutwakil/androidide/editor/ui/BaseEditorWindow.java +++ b/editor/impl/src/main/java/dev/mutwakil/androidide/editor/ui/BaseEditorWindow.java @@ -27,6 +27,7 @@ import android.util.TypedValue; import android.view.View; import android.view.ViewGroup; +import android.widget.ScrollView; import android.widget.TextView; import androidx.annotation.NonNull; import dev.mutwakil.androidide.resources.R; @@ -41,6 +42,7 @@ public abstract class BaseEditorWindow extends AbstractPopupWindow { protected final TextView text; + protected final ScrollView scrollView; /** * Create a popup window for editor @@ -54,29 +56,33 @@ public BaseEditorWindow(@NonNull IDEEditor editor) { super(editor, getFeatureFlags()); this.text = onCreateTextView(editor); - setContentView(onCreateContentView(editor.getContext())); + this.scrollView = onCreateContentView(editor.getContext()); + setContentView(this.scrollView); } private static int getFeatureFlags() { return FEATURE_SCROLL_AS_CONTENT | FEATURE_SHOW_OUTSIDE_VIEW_ALLOWED; } - protected View onCreateContentView(@NonNull Context context) { - return this.text; + protected ScrollView onCreateContentView(@NonNull Context context) { + final var dp4 = ContextUtilsKt.dpToPx(context, 4); + final var dp8 = dp4 * 2; + + final var scrollView = new ScrollView(context); + scrollView.setBackground(createBackground(context)); + scrollView.setPaddingRelative(dp8, dp4, dp8, dp4); + scrollView.addView(this.text); + return scrollView; } protected TextView onCreateTextView(@NonNull IDEEditor editor) { final var context = editor.getContext(); - final var dp4 = dp2px(4); - final var dp8 = dp4 * 2; final var text = new TextView(context); - text.setBackground(createBackground(context)); text.setTextColor(ContextUtilsKt.resolveAttr(context, R.attr.colorOnPrimaryContainer)); text.setTextSize(TypedValue.COMPLEX_UNIT_SP, 14); text.setClickable(false); text.setFocusable(false); - text.setPaddingRelative(dp8, dp4, dp8, dp4); text.setLayoutParams( new ViewGroup.LayoutParams( ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT)); @@ -95,9 +101,10 @@ protected Drawable createBackground(final Context context) { public void displayWindow() { final var dp16 = dp2px(16f); final int width = getEditor().getWidth() - dp16; - final int height = getEditor().getHeight() - dp16; + final int height = getEditor().getHeight() / 2; final var widthMeasureSpec = makeMeasureSpec(width, AT_MOST); final var heightMeasureSpec = makeMeasureSpec(height, AT_MOST); + this.scrollView.scrollTo(0, 0); this.getRootView().measure(widthMeasureSpec, heightMeasureSpec); this.setSize(this.getRootView().getMeasuredWidth(), this.getRootView().getMeasuredHeight()); @@ -110,7 +117,7 @@ public void displayWindow() { } protected View getRootView() { - return this.text; + return this.scrollView; } @NonNull diff --git a/editor/impl/src/main/java/dev/mutwakil/androidide/editor/ui/IDEEditor.kt b/editor/impl/src/main/java/dev/mutwakil/androidide/editor/ui/IDEEditor.kt index dbd51dd7da..346433be4f 100644 --- a/editor/impl/src/main/java/dev/mutwakil/androidide/editor/ui/IDEEditor.kt +++ b/editor/impl/src/main/java/dev/mutwakil/androidide/editor/ui/IDEEditor.kt @@ -490,6 +490,21 @@ open class IDEEditor @JvmOverloads constructor( override fun onCreateRenderer(): EditorRenderer { return TracingEditorRenderer(editor = this) } + + private var layoutRebuildPending = false + + /** Rebuilds the text layout on the next main-loop turn, coalescing repeat requests from + * consecutive skipped frames. See [TracingEditorRenderer.draw]. */ + internal fun rebuildLayout() { + if (layoutRebuildPending) return + layoutRebuildPending = true + post { + layoutRebuildPending = false + if (isReleased) return@post + createLayout() + invalidate() + } + } override fun release() { ensureWindowsDismissed() diff --git a/editor/impl/src/main/java/dev/mutwakil/androidide/editor/ui/SignatureHelpWindow.java b/editor/impl/src/main/java/dev/mutwakil/androidide/editor/ui/SignatureHelpWindow.java index 1208a2d051..5513d2b811 100644 --- a/editor/impl/src/main/java/dev/mutwakil/androidide/editor/ui/SignatureHelpWindow.java +++ b/editor/impl/src/main/java/dev/mutwakil/androidide/editor/ui/SignatureHelpWindow.java @@ -23,6 +23,7 @@ import android.text.style.ForegroundColorSpan; import androidx.annotation.NonNull; import androidx.annotation.Nullable; +import androidx.core.view.OneShotPreDrawListener; import dev.mutwakil.androidide.lsp.models.SignatureHelp; import dev.mutwakil.androidide.lsp.models.SignatureInformation; import dev.mutwakil.androidide.utils.ContextUtilsKt; @@ -63,6 +64,8 @@ static String signatureName(String label) { final int paren = label.indexOf('('); return paren < 0 ? label : label.substring(0, paren); } + + private int activeSignatureStart; /** * Create a signature help popup window for editor @@ -103,6 +106,12 @@ public void setupAndDisplay(SignatureHelp signature) { this.text.setText(signatureText); displayWindow(); + + final int activeStart = this.activeSignatureStart; + OneShotPreDrawListener.add(this.scrollView, () -> { + final var layout = this.text.getLayout(); + this.scrollView.scrollTo(0, layout.getLineTop(layout.getLineForOffset(activeStart))); + }); } @Nullable @@ -129,10 +138,15 @@ private CharSequence createSignatureText(@NonNull SignatureHelp signature) { if (applicable.isEmpty()) { return null; } - + + final var active = signatures.get(activeSignature); + activeSignatureStart = 0; count = applicable.size(); for (var i = 0; i < count; i++) { final var info = applicable.get(i); + if (info == active) { + activeSignatureStart = sb.length(); + } formatSignature(info, activeParameter, sb); if (i != count - 1) { sb.append('\n'); diff --git a/editor/impl/src/main/java/dev/mutwakil/androidide/editor/ui/TracingEditorRenderer.kt b/editor/impl/src/main/java/dev/mutwakil/androidide/editor/ui/TracingEditorRenderer.kt index 388fdbc17f..11b2e247bd 100644 --- a/editor/impl/src/main/java/dev/mutwakil/androidide/editor/ui/TracingEditorRenderer.kt +++ b/editor/impl/src/main/java/dev/mutwakil/androidide/editor/ui/TracingEditorRenderer.kt @@ -32,6 +32,7 @@ import io.github.rosemoe.sora.util.LongArrayList import io.github.rosemoe.sora.util.MutableInt import io.github.rosemoe.sora.widget.CodeEditor import io.github.rosemoe.sora.widget.EditorRenderer +import io.github.rosemoe.sora.widget.layout.WordwrapLayout import org.slf4j.LoggerFactory /** @@ -40,262 +41,521 @@ import org.slf4j.LoggerFactory * @author Akash Yadav */ open class TracingEditorRenderer( - private val enabled: Boolean = BuildConfig.DEBUG, - editor: CodeEditor + private val enabled: Boolean = BuildConfig.DEBUG, + private val editor: CodeEditor, ) : EditorRenderer(editor) { - - private companion object { - private val log = LoggerFactory.getLogger(TracingEditorRenderer::class.java) - } - - override fun draw(canvas: Canvas) = trace("draw") { - super.draw(canvas) - } - - @RequiresApi(Build.VERSION_CODES.Q) - override fun updateLineDisplayList(renderNode: RenderNode?, line: Int, spans: Spans.Reader?) = - trace("updateLineDisplayList") { - super.updateLineDisplayList(renderNode, line, spans) - } - - override fun drawSingleTextLine(canvas: Canvas?, line: Int, offsetX: Float, offsetY: Float, - spans: Spans.Reader?, visibleOnly: Boolean) = trace("drawSingleTextLine") { - super.drawSingleTextLine(canvas, line, offsetX, offsetY, spans, visibleOnly) - } - - override fun drawView(canvas: Canvas?) = trace("drawView") { - super.drawView(canvas) - } - - override fun drawUserGutterBackground(canvas: Canvas?, right: Int) = - trace("drawUserGutterBackground") { - super.drawUserGutterBackground(canvas, right) - } - - override fun drawStuckLineNumbers(canvas: Canvas?, candidates: MutableList?, - offset: Float, lineNumberWidth: Float, lineNumberColor: Int) = trace("drawStuckLineNumbers") { - super.drawStuckLineNumbers(canvas, candidates, offset, lineNumberWidth, lineNumberColor) - } - - override fun drawStuckLines(canvas: Canvas?, candidates: MutableList?, offset: Float) = - trace("drawStuckLines") { - super.drawStuckLines(canvas, candidates, offset) - } - - override fun drawHardwrapMarker(canvas: Canvas?, offset: Float) = trace("drawHardwrapMarker") { - super.drawHardwrapMarker(canvas, offset) - } - - override fun drawSideIcons(canvas: Canvas?, offset: Float) = trace("drawSideIcons") { - super.drawSideIcons(canvas, offset) - } - - override fun drawFormatTip(canvas: Canvas?) = trace("drawFormatTip") { - super.drawFormatTip(canvas) - } - - override fun drawColor(canvas: Canvas?, color: Int, rect: RectF?) = trace("drawColor") { - super.drawColor(canvas, color, rect) - } - - override fun drawColor(canvas: Canvas?, color: Int, rect: Rect?) = trace("drawColor") { - super.drawColor(canvas, color, rect) - } - - override fun drawColorRound(canvas: Canvas?, color: Int, rect: RectF?) = trace("drawColorRound") { - super.drawColorRound(canvas, color, rect) - } - - override fun drawRowBackground(canvas: Canvas?, color: Int, row: Int) = - trace("drawRowBackground") { - super.drawRowBackground(canvas, color, row) - } - - override fun drawRowBackground(canvas: Canvas?, color: Int, row: Int, right: Int) = - trace("drawRowBackground") { - super.drawRowBackground(canvas, color, row, right) - } - - override fun drawLineNumber(canvas: Canvas?, line: Int, row: Int, offsetX: Float, width: Float, - color: Int) = trace("drawLineNumber") { - super.drawLineNumber(canvas, line, row, offsetX, width, color) - } - - override fun drawLineNumberBackground(canvas: Canvas?, offsetX: Float, width: Float, color: Int) = - trace("drawLineNumberBackground") { - super.drawLineNumberBackground(canvas, offsetX, width, color) - } - - override fun drawDivider(canvas: Canvas?, offsetX: Float, color: Int) = trace("drawDivider") { - super.drawDivider(canvas, offsetX, color) - } - - override fun drawRows(canvas: Canvas?, offset: Float, postDrawLineNumbers: LongArrayList?, - postDrawCursor: MutableList?, postDrawCurrentLines: MutableIntList?, - requiredFirstLn: MutableInt?) = trace("drawRows") { - super.drawRows(canvas, offset, postDrawLineNumbers, postDrawCursor, postDrawCurrentLines, - requiredFirstLn) - } - - override fun drawDiagnosticIndicators(canvas: Canvas?, offset: Float) = - trace("drawDiagnosticIndicators") { - super.drawDiagnosticIndicators(canvas, offset) - } - - override fun drawWhitespaces(canvas: Canvas?, offset: Float, line: Int, row: Int, rowStart: Int, - rowEnd: Int, min: Int, max: Int) = trace("drawWhitespaces") { - super.drawWhitespaces(canvas, offset, line, row, rowStart, rowEnd, min, max) - } - - override fun drawMiniGraph(canvas: Canvas?, offset: Float, row: Int, graph: String?) = - trace("drawMiniGraph") { - super.drawMiniGraph(canvas, offset, row, graph) - } - - override fun getRowTopForBackground(row: Int) = trace("getRowTopForBackground") { - return@trace super.getRowTopForBackground(row) - } - - override fun getRowBottomForBackground(row: Int) = trace("getRowBottomForBackground") { - return@trace super.getRowBottomForBackground(row) - } - - override fun drawRowRegionBackground(canvas: Canvas?, row: Int, line: Int, highlightStart: Int, - highlightEnd: Int, rowStart: Int, rowEnd: Int, color: Int) = trace("drawRowRegionBackground") { - super.drawRowRegionBackground(canvas, row, line, highlightStart, highlightEnd, rowStart, rowEnd, - color) - } - - override fun drawRowBackgroundRect(canvas: Canvas?, rect: RectF?) = - trace("drawRowBackgroundRect") { - super.drawRowBackgroundRect(canvas, rect) - } - - override fun drawRegionText(canvas: Canvas?, offsetX: Float, baseline: Float, line: Int, - startIndex: Int, endIndex: Int, contextStart: Int, contextEnd: Int, isRtl: Boolean, - columnCount: Int, color: Int) = trace("drawRegionText") { - super.drawRegionText(canvas, offsetX, baseline, line, startIndex, endIndex, contextStart, - contextEnd, isRtl, columnCount, color) - } - - override fun drawRegionTextDirectional(canvas: Canvas?, offsetX: Float, baseline: Float, - line: Int, startIndex: Int, endIndex: Int, contextStart: Int, contextEnd: Int, columnCount: Int, - color: Int) = trace("drawRegionTextDirectional") { - super.drawRegionTextDirectional(canvas, offsetX, baseline, line, startIndex, endIndex, - contextStart, contextEnd, columnCount, color) - } - - override fun drawFunctionCharacter(canvas: Canvas?, offsetX: Float, offsetY: Float, width: Float, - ch: Char) = trace("drawFunctionCharacter") { - super.drawFunctionCharacter(canvas, offsetX, offsetY, width, ch) - } - - override fun drawText(canvas: Canvas?, line: ContentLine?, index: Int, count: Int, - contextStart: Int, contextCount: Int, isRtl: Boolean, offX: Float, offY: Float, - lineNumber: Int) = trace("drawText") { - super.drawText(canvas, line, index, count, contextStart, contextCount, isRtl, offX, offY, - lineNumber) - } - - override fun drawTextRunDirect(canvas: Canvas?, src: CharArray?, index: Int, count: Int, - contextStart: Int, contextCount: Int, offX: Float, offY: Float, isRtl: Boolean) = - trace("drawTextRunDirect") { - super.drawTextRunDirect(canvas, src, index, count, contextStart, contextCount, offX, offY, - isRtl) - } - - override fun drawEdgeEffect(canvas: Canvas?) = trace("drawEdgeEffect") { - super.drawEdgeEffect(canvas) - } - - override fun drawBlockLines(canvas: Canvas?, offsetX: Float) = trace("drawBlockLines") { - try { - super.drawBlockLines(canvas, offsetX) - } catch (e: IndexOutOfBoundsException) { - // styles.blocks was concurrently cleared by the analyzer worker thread. Skip block - // lines this frame; the next invalidate() redraws them. - log.warn("Skipped drawing block lines: styles.blocks was modified concurrently", e) - } - } - - override fun drawSideBlockLine(canvas: Canvas?) = trace("drawSideBlockLine") { - try { - super.drawSideBlockLine(canvas) - } catch (e: IndexOutOfBoundsException) { - log.warn("Skipped drawing side block line: styles.blocks was modified concurrently", e) - } - } - - override fun drawScrollBars(canvas: Canvas?) = trace("drawScrollBars") { - super.drawScrollBars(canvas) - } - - override fun drawScrollBarTrackVertical(canvas: Canvas?) = trace("drawScrollBarTrackVertical") { - super.drawScrollBarTrackVertical(canvas) - } - - override fun drawScrollBarVertical(canvas: Canvas?) = trace("drawScrollBarVertical") { - super.drawScrollBarVertical(canvas) - } - - override fun drawLineInfoPanel(canvas: Canvas?, topY: Float, length: Float) = - trace("drawLineInfoPanel") { - super.drawLineInfoPanel(canvas, topY, length) - } - - override fun drawScrollBarTrackHorizontal(canvas: Canvas?) = - trace("drawScrollBarTrackHorizontal") { - super.drawScrollBarTrackHorizontal(canvas) - } - - override fun patchSnippetRegions(canvas: Canvas?, textOffset: Float) = - trace("patchSnippetRegions") { - super.patchSnippetRegions(canvas, textOffset) - } - - override fun patchHighlightedDelimiters(canvas: Canvas?, textOffset: Float) = - trace("patchHighlightedDelimiters") { - super.patchHighlightedDelimiters(canvas, textOffset) - } - - override fun patchTextRegionWithColor(canvas: Canvas?, textOffset: Float, start: Int, end: Int, - color: Int, backgroundColor: Int, underlineColor: Int) = trace("patchTextRegionWithColor") { - super.patchTextRegionWithColor(canvas, textOffset, start, end, color, backgroundColor, - underlineColor) - } - - override fun patchTextRegions(canvas: Canvas?, textOffset: Float, - positions: MutableList?, patch: PatchDraw) = trace("patchTextRegions") { - super.patchTextRegions(canvas, textOffset, positions, patch) - } - - override fun drawSelectionOnAnimation(canvas: Canvas?) = trace("drawSelectionOnAnimation") { - super.drawSelectionOnAnimation(canvas) - } - - override fun drawScrollBarHorizontal(canvas: Canvas?) = trace("drawScrollBarHorizontal") { - super.drawScrollBarHorizontal(canvas) - } - - override fun buildMeasureCacheForLines(startLine: Int, endLine: Int, timestamp: Long, - useCachedContent: Boolean) = trace("buildMeasureCacheForLines") { - super.buildMeasureCacheForLines(startLine, endLine, timestamp, useCachedContent) - } - - override fun buildMeasureCacheForLines(startLine: Int, endLine: Int) = - trace("buildMeasureCacheForLines") { - super.buildMeasureCacheForLines(startLine, endLine) - } - - override fun measureText(text: ContentLine?, line: Int, index: Int, count: Int) = - trace("measureText") { - return@trace super.measureText(text, line, index, count) - } - - private inline fun trace(section: String, crossinline action: () -> T): T = - if (enabled) { - androidx.tracing.trace(section, action) - } else { - action() - } + private companion object { + private val log = LoggerFactory.getLogger(TracingEditorRenderer::class.java) + } + + override fun draw(canvas: Canvas) = + trace("draw") { + if (hasStaleWordwrapRows()) { + // Drawing would throw mid-frame (sora indexes the line's width cache past its end) and + // leak the span reader's line lock, so skip the frame instead. The stale rows persist + // until the next layout, so rebuild it. + (editor as? IDEEditor)?.rebuildLayout() + log.warn("Skipped a frame: word-wrap row table is stale") + } else { + super.draw(canvas) + } + } + + /** + * sora 0.23.6 WordwrapLayout race (Rosemoe/sora-editor#666): an async re-break can replace the row + * table with rows computed from text that has since shrunk. Only the visible rows are drawn, so + * only they need checking. + */ + private fun hasStaleWordwrapRows(): Boolean { + val layout = editor.layout as? WordwrapLayout ?: return false + val text = editor.text + for (i in editor.firstVisibleRow..editor.lastVisibleRow) { + val row = layout.getRowAt(i) + if (row.lineIndex >= text.lineCount || row.endColumn > text.getColumnCount(row.lineIndex)) { + return true + } + } + return false + } + + @RequiresApi(Build.VERSION_CODES.Q) + override fun updateLineDisplayList( + renderNode: RenderNode?, + line: Int, + spans: Spans.Reader?, + ) = trace("updateLineDisplayList") { + super.updateLineDisplayList(renderNode, line, spans) + } + + override fun drawSingleTextLine( + canvas: Canvas?, + line: Int, + offsetX: Float, + offsetY: Float, + spans: Spans.Reader?, + visibleOnly: Boolean, + ) = trace("drawSingleTextLine") { + super.drawSingleTextLine(canvas, line, offsetX, offsetY, spans, visibleOnly) + } + + override fun drawView(canvas: Canvas?) = + trace("drawView") { + super.drawView(canvas) + } + + override fun drawUserGutterBackground( + canvas: Canvas?, + right: Int, + ) = trace("drawUserGutterBackground") { + super.drawUserGutterBackground(canvas, right) + } + + override fun drawStuckLineNumbers( + canvas: Canvas?, + candidates: MutableList?, + offset: Float, + lineNumberWidth: Float, + lineNumberColor: Int, + ) = trace("drawStuckLineNumbers") { + super.drawStuckLineNumbers(canvas, candidates, offset, lineNumberWidth, lineNumberColor) + } + + override fun drawStuckLines( + canvas: Canvas?, + candidates: MutableList?, + offset: Float, + ) = trace("drawStuckLines") { + super.drawStuckLines(canvas, candidates, offset) + } + + override fun drawHardwrapMarker( + canvas: Canvas?, + offset: Float, + ) = trace("drawHardwrapMarker") { + super.drawHardwrapMarker(canvas, offset) + } + + override fun drawSideIcons( + canvas: Canvas?, + offset: Float, + ) = trace("drawSideIcons") { + super.drawSideIcons(canvas, offset) + } + + override fun drawFormatTip(canvas: Canvas?) = + trace("drawFormatTip") { + super.drawFormatTip(canvas) + } + + override fun drawColor( + canvas: Canvas?, + color: Int, + rect: RectF?, + ) = trace("drawColor") { + super.drawColor(canvas, color, rect) + } + + override fun drawColor( + canvas: Canvas?, + color: Int, + rect: Rect?, + ) = trace("drawColor") { + super.drawColor(canvas, color, rect) + } + + override fun drawColorRound( + canvas: Canvas?, + color: Int, + rect: RectF?, + ) = trace("drawColorRound") { + super.drawColorRound(canvas, color, rect) + } + + override fun drawRowBackground( + canvas: Canvas?, + color: Int, + row: Int, + ) = trace("drawRowBackground") { + super.drawRowBackground(canvas, color, row) + } + + override fun drawRowBackground( + canvas: Canvas?, + color: Int, + row: Int, + right: Int, + ) = trace("drawRowBackground") { + super.drawRowBackground(canvas, color, row, right) + } + + override fun drawLineNumber( + canvas: Canvas?, + line: Int, + row: Int, + offsetX: Float, + width: Float, + color: Int, + ) = trace("drawLineNumber") { + super.drawLineNumber(canvas, line, row, offsetX, width, color) + } + + override fun drawLineNumberBackground( + canvas: Canvas?, + offsetX: Float, + width: Float, + color: Int, + ) = trace("drawLineNumberBackground") { + super.drawLineNumberBackground(canvas, offsetX, width, color) + } + + override fun drawDivider( + canvas: Canvas?, + offsetX: Float, + color: Int, + ) = trace("drawDivider") { + super.drawDivider(canvas, offsetX, color) + } + + override fun drawRows( + canvas: Canvas?, + offset: Float, + postDrawLineNumbers: LongArrayList?, + postDrawCursor: MutableList?, + postDrawCurrentLines: MutableIntList?, + requiredFirstLn: MutableInt?, + ) = trace("drawRows") { + super.drawRows( + canvas, + offset, + postDrawLineNumbers, + postDrawCursor, + postDrawCurrentLines, + requiredFirstLn, + ) + } + + override fun drawDiagnosticIndicators( + canvas: Canvas?, + offset: Float, + ) = trace("drawDiagnosticIndicators") { + super.drawDiagnosticIndicators(canvas, offset) + } + + override fun drawWhitespaces( + canvas: Canvas?, + offset: Float, + line: Int, + row: Int, + rowStart: Int, + rowEnd: Int, + min: Int, + max: Int, + ) = trace("drawWhitespaces") { + super.drawWhitespaces(canvas, offset, line, row, rowStart, rowEnd, min, max) + } + + override fun drawMiniGraph( + canvas: Canvas?, + offset: Float, + row: Int, + graph: String?, + ) = trace("drawMiniGraph") { + super.drawMiniGraph(canvas, offset, row, graph) + } + + override fun getRowTopForBackground(row: Int) = + trace("getRowTopForBackground") { + return@trace super.getRowTopForBackground(row) + } + + override fun getRowBottomForBackground(row: Int) = + trace("getRowBottomForBackground") { + return@trace super.getRowBottomForBackground(row) + } + + override fun drawRowRegionBackground( + canvas: Canvas?, + row: Int, + line: Int, + highlightStart: Int, + highlightEnd: Int, + rowStart: Int, + rowEnd: Int, + color: Int, + ) = trace("drawRowRegionBackground") { + super.drawRowRegionBackground( + canvas, + row, + line, + highlightStart, + highlightEnd, + rowStart, + rowEnd, + color, + ) + } + + override fun drawRowBackgroundRect( + canvas: Canvas?, + rect: RectF?, + ) = trace("drawRowBackgroundRect") { + super.drawRowBackgroundRect(canvas, rect) + } + + override fun drawRegionText( + canvas: Canvas?, + offsetX: Float, + baseline: Float, + line: Int, + startIndex: Int, + endIndex: Int, + contextStart: Int, + contextEnd: Int, + isRtl: Boolean, + columnCount: Int, + color: Int, + ) = trace("drawRegionText") { + super.drawRegionText( + canvas, + offsetX, + baseline, + line, + startIndex, + endIndex, + contextStart, + contextEnd, + isRtl, + columnCount, + color, + ) + } + + override fun drawRegionTextDirectional( + canvas: Canvas?, + offsetX: Float, + baseline: Float, + line: Int, + startIndex: Int, + endIndex: Int, + contextStart: Int, + contextEnd: Int, + columnCount: Int, + color: Int, + ) = trace("drawRegionTextDirectional") { + super.drawRegionTextDirectional( + canvas, + offsetX, + baseline, + line, + startIndex, + endIndex, + contextStart, + contextEnd, + columnCount, + color, + ) + } + + override fun drawFunctionCharacter( + canvas: Canvas?, + offsetX: Float, + offsetY: Float, + width: Float, + ch: Char, + ) = trace("drawFunctionCharacter") { + super.drawFunctionCharacter(canvas, offsetX, offsetY, width, ch) + } + + override fun drawText( + canvas: Canvas?, + line: ContentLine?, + index: Int, + count: Int, + contextStart: Int, + contextCount: Int, + isRtl: Boolean, + offX: Float, + offY: Float, + lineNumber: Int, + ) = trace("drawText") { + super.drawText( + canvas, + line, + index, + count, + contextStart, + contextCount, + isRtl, + offX, + offY, + lineNumber, + ) + } + + override fun drawTextRunDirect( + canvas: Canvas?, + src: CharArray?, + index: Int, + count: Int, + contextStart: Int, + contextCount: Int, + offX: Float, + offY: Float, + isRtl: Boolean, + ) = trace("drawTextRunDirect") { + super.drawTextRunDirect( + canvas, + src, + index, + count, + contextStart, + contextCount, + offX, + offY, + isRtl, + ) + } + + override fun drawEdgeEffect(canvas: Canvas?) = + trace("drawEdgeEffect") { + super.drawEdgeEffect(canvas) + } + + override fun drawBlockLines( + canvas: Canvas?, + offsetX: Float, + ) = trace("drawBlockLines") { + try { + super.drawBlockLines(canvas, offsetX) + } catch (e: IndexOutOfBoundsException) { + // styles.blocks was concurrently cleared by the analyzer worker thread. Skip block + // lines this frame; the next invalidate() redraws them. + log.warn("Skipped drawing block lines: styles.blocks was modified concurrently", e) + } + } + + override fun drawSideBlockLine(canvas: Canvas?) = + trace("drawSideBlockLine") { + try { + super.drawSideBlockLine(canvas) + } catch (e: IndexOutOfBoundsException) { + log.warn("Skipped drawing side block line: styles.blocks was modified concurrently", e) + } + } + + override fun drawScrollBars(canvas: Canvas?) = + trace("drawScrollBars") { + super.drawScrollBars(canvas) + } + + override fun drawScrollBarTrackVertical(canvas: Canvas?) = + trace("drawScrollBarTrackVertical") { + super.drawScrollBarTrackVertical(canvas) + } + + override fun drawScrollBarVertical(canvas: Canvas?) = + trace("drawScrollBarVertical") { + super.drawScrollBarVertical(canvas) + } + + override fun drawLineInfoPanel( + canvas: Canvas?, + topY: Float, + length: Float, + ) = trace("drawLineInfoPanel") { + super.drawLineInfoPanel(canvas, topY, length) + } + + override fun drawScrollBarTrackHorizontal(canvas: Canvas?) = + trace("drawScrollBarTrackHorizontal") { + super.drawScrollBarTrackHorizontal(canvas) + } + + override fun patchSnippetRegions( + canvas: Canvas?, + textOffset: Float, + ) = trace("patchSnippetRegions") { + super.patchSnippetRegions(canvas, textOffset) + } + + override fun patchHighlightedDelimiters( + canvas: Canvas?, + textOffset: Float, + ) = trace("patchHighlightedDelimiters") { + super.patchHighlightedDelimiters(canvas, textOffset) + } + + override fun patchTextRegionWithColor( + canvas: Canvas?, + textOffset: Float, + start: Int, + end: Int, + color: Int, + backgroundColor: Int, + underlineColor: Int, + ) = trace("patchTextRegionWithColor") { + super.patchTextRegionWithColor( + canvas, + textOffset, + start, + end, + color, + backgroundColor, + underlineColor, + ) + } + + override fun patchTextRegions( + canvas: Canvas?, + textOffset: Float, + positions: MutableList?, + patch: PatchDraw, + ) = trace("patchTextRegions") { + super.patchTextRegions(canvas, textOffset, positions, patch) + } + + override fun drawSelectionOnAnimation(canvas: Canvas?) = + trace("drawSelectionOnAnimation") { + super.drawSelectionOnAnimation(canvas) + } + + override fun drawScrollBarHorizontal(canvas: Canvas?) = + trace("drawScrollBarHorizontal") { + super.drawScrollBarHorizontal(canvas) + } + + override fun buildMeasureCacheForLines( + startLine: Int, + endLine: Int, + timestamp: Long, + useCachedContent: Boolean, + ) = trace("buildMeasureCacheForLines") { + super.buildMeasureCacheForLines(startLine, endLine, timestamp, useCachedContent) + } + + override fun buildMeasureCacheForLines( + startLine: Int, + endLine: Int, + ) = trace("buildMeasureCacheForLines") { + super.buildMeasureCacheForLines(startLine, endLine) + } + + override fun measureText( + text: ContentLine?, + line: Int, + index: Int, + count: Int, + ) = trace("measureText") { + return@trace super.measureText(text, line, index, count) + } + + private inline fun trace( + section: String, + crossinline action: () -> T, + ): T = + if (enabled) { + androidx.tracing.trace(section, action) + } else { + action() + } } \ No newline at end of file diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index abf5061d1a..a0f15286ec 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -6,7 +6,7 @@ junit-jupiter = "5.10.2" kotlin = "2.3.21" kotlin-coroutines = "1.10.2" tree-sitter = "4.3.3" -editor = "0.23.7" +editor = "0.23.6" glide = "4.16.0" androidx-vectordrawable = "1.2.0" androidx-navigation = "2.9.7" @@ -92,16 +92,16 @@ sentry-logback = { module = "io.sentry:sentry-logback",version.ref = "sentry"} sentry-android-replay = { module = "io.sentry:sentry-android-replay", version.ref = "sentry" } # AndroidIDE -androidide-ts = { module = "io.github.wadamzmail.androidide.treesitter:android-tree-sitter", version.ref = "tree-sitter" } -androidide-ts-java = { module = "io.github.wadamzmail.androidide.treesitter:tree-sitter-java", version.ref = "tree-sitter" } -androidide-ts-json = { module = "io.github.wadamzmail.androidide.treesitter:tree-sitter-json", version.ref = "tree-sitter" } -androidide-ts-kotlin = { module = "io.github.wadamzmail.androidide.treesitter:tree-sitter-kotlin", version.ref = "tree-sitter" } -androidide-ts-log = { module = "io.github.wadamzmail.androidide.treesitter:tree-sitter-log", version.ref = "tree-sitter" } -androidide-ts-xml = { module = "io.github.wadamzmail.androidide.treesitter:tree-sitter-xml", version.ref = "tree-sitter" } +androidide-ts = { module = "com.itsaky.androidide.treesitter:android-tree-sitter", version.ref = "tree-sitter" } +androidide-ts-java = { module = "com.itsaky.androidide.treesitter:tree-sitter-java", version.ref = "tree-sitter" } +androidide-ts-json = { module = "com.itsaky.androidide.treesitter:tree-sitter-json", version.ref = "tree-sitter" } +androidide-ts-kotlin = { module = "com.itsaky.androidide.treesitter:tree-sitter-kotlin", version.ref = "tree-sitter" } +androidide-ts-log = { module = "com.itsaky.androidide.treesitter:tree-sitter-log", version.ref = "tree-sitter" } +androidide-ts-xml = { module = "com.itsaky.androidide.treesitter:tree-sitter-xml", version.ref = "tree-sitter" } # Common -common-editor = { module = "io.github.rosemoe:editor", version.ref = "editor" } -common-editor-textmate = { module = "io.github.rosemoe:language-textmate", version.ref = "editor" } +common-editor = { module = "io.github.Rosemoe.sora-editor:editor", version.ref = "editor" } +common-editor-textmate = { module = "io.github.Rosemoe.sora-editor:language-textmate", version.ref = "editor" } common-utilcode = { module = "com.blankj:utilcodex", version = "1.31.1" } common-glide = { module = "com.github.bumptech.glide:glide", version.ref = "glide" } common-glide_ap = { module = "com.github.bumptech.glide:compiler", version.ref = "glide" } diff --git a/java/javac-services/src/main/java/dev/mutwakil/androidide/javac/services/fs/CachedJarFileSystem.kt b/java/javac-services/src/main/java/dev/mutwakil/androidide/javac/services/fs/CachedJarFileSystem.kt index 962a96f5d9..679aa5dfea 100644 --- a/java/javac-services/src/main/java/dev/mutwakil/androidide/javac/services/fs/CachedJarFileSystem.kt +++ b/java/javac-services/src/main/java/dev/mutwakil/androidide/javac/services/fs/CachedJarFileSystem.kt @@ -19,63 +19,52 @@ package dev.mutwakil.androidide.javac.services.fs import dev.mutwakil.androidide.zipfs2.ZipFileSystem import dev.mutwakil.androidide.zipfs2.ZipFileSystemProvider -import jdkx.lang.model.SourceVersion +import dev.mutwakil.androidide.zipfs2.listing.JarListing import openjdk.tools.javac.file.RelativePath.RelativeDirectory import org.slf4j.LoggerFactory import java.io.IOException +import java.nio.channels.SeekableByteChannel import java.nio.file.Path /** - * A cached file system for JAR files. + * A cached, read-only file system for a JAR that reads its entries through the shared [JarListing]. * * @author Akash Yadav */ -class CachedJarFileSystem( - provider: ZipFileSystemProvider?, - zfpath: Path?, - env: MutableMap? -) : ZipFileSystem(provider, zfpath, env) { +class CachedJarFileSystem internal constructor( + provider: ZipFileSystemProvider, + zfpath: Path, + internal val listing: JarListing, + channel: SeekableByteChannel, +) : ZipFileSystem(provider, zfpath, listing, channel) { + companion object { + private val log = LoggerFactory.getLogger(CachedJarFileSystem::class.java) + } - companion object { - private val log = LoggerFactory.getLogger(CachedJarFileSystem::class.java) - } + private val packageIndex: Map by lazy(LazyThreadSafetyMode.SYNCHRONIZED) { + ListingPackageMap(this, listing) + } - internal val packages = mutableMapOf() + override fun close() { + // Do nothing + // This is called manually by the Java LSP + } - override fun close() { - // Do nothing - // This is called manually by the Java LSP - } + @Throws(IOException::class) + fun doClose() { + try { + super.close() + } catch (e: IOException) { + log.warn("IOException during CachedJarFileSystem close", e) + } catch (e: java.io.UncheckedIOException) { + log.warn("UncheckedIOException during CachedJarFileSystem close", e) + } + } - @Throws(IOException::class) - fun doClose() { - try { - super.close() - } catch (e: IOException) { - log.warn("IOException during CachedJarFileSystem class", e) - } catch (e: java.io.UncheckedIOException) { - log.warn("UncheckedIOException during CachedJarFileSystem close", e) - } - } - - fun storeJARPackageDir(dir: Path?): Boolean { - if (isValid(dir?.fileName)) { - packages[RelativeDirectory(rootDir.relativize(dir!!).toString())] = dir - return true - } - - return false - } - - private fun isValid(fileName: Path?): Boolean { - return if (fileName == null) { - true - } else { - var name = fileName.toString() - if (name.endsWith("/")) { - name = name.substring(0, name.length - 1) - } - SourceVersion.isIdentifier(name) - } - } -} + /** + * Returns the package directories of this JAR keyed the way javac's archive walk keys them. + * + * The map is a read-only view of the listing, resolved on demand, and is the same instance on every call. + */ + fun packageIndex(): Map = packageIndex +} \ No newline at end of file diff --git a/java/javac-services/src/main/java/dev/mutwakil/androidide/javac/services/fs/CachingJarFileSystemProvider.kt b/java/javac-services/src/main/java/dev/mutwakil/androidide/javac/services/fs/CachingJarFileSystemProvider.kt index 0462a19e1e..611ce20227 100644 --- a/java/javac-services/src/main/java/dev/mutwakil/androidide/javac/services/fs/CachingJarFileSystemProvider.kt +++ b/java/javac-services/src/main/java/dev/mutwakil/androidide/javac/services/fs/CachingJarFileSystemProvider.kt @@ -19,44 +19,130 @@ package dev.mutwakil.androidide.javac.services.fs import dev.mutwakil.androidide.zipfs2.JarFileSystemProvider import dev.mutwakil.androidide.zipfs2.ZipFileSystem +import dev.mutwakil.androidide.zipfs2.listing.JarListing +import dev.mutwakil.androidide.zipfs2.listing.JarListingCache import org.slf4j.LoggerFactory +import java.io.IOException import java.nio.file.FileSystem +import java.nio.file.FileSystemNotFoundException +import java.nio.file.Files +import java.nio.file.NoSuchFileException import java.nio.file.Path import java.nio.file.Paths +import java.nio.file.StandardOpenOption import java.util.concurrent.ConcurrentHashMap +import java.util.concurrent.ConcurrentLinkedQueue import kotlin.io.path.pathString /** * An implementation of [JarFileSystemProvider] that caches the created [CachedJarFileSystem] so * that it can be (re)used in multiple compilations. * + * Every open checks the JAR against [JarListingCache.SHARED]; when the JAR changed on disk, a new + * file system is opened on the new listing. The superseded one is retired, not closed: javac's + * archive containers keep the file system they opened until their file manager is closed, and a + * closed one throws an unchecked `ClosedFileSystemException` from `Files.exists`. Retired file + * systems are closed by [closeRetired] and [clearCache], once the file managers are gone. + * * @author Akash Yadav */ object CachingJarFileSystemProvider : JarFileSystemProvider() { private val cachedFs = ConcurrentHashMap() + private val retired = ConcurrentLinkedQueue() private val log = LoggerFactory.getLogger(CachingJarFileSystemProvider::class.java) + init { + /* + * Runs while the listing cache holds that JAR's lock. createFs never calls the cache from + * inside a map operation, and this listener only touches the map, so the two locks are + * always taken in the order cache lock -> map bin. + */ + JarListingCache.SHARED.addListener { path -> cachedFs.remove(keyOf(path))?.let(retired::add) } + } + + /* + * A cached file system is stale exactly when the listing cache no longer returns its listing. + * The map is read before that lookup, so a mismatch proves the cached one was superseded, never + * that a racing caller published a newer one. A caller that loses the publish race closes its + * own unseen file system and re-checks the winner on the next round. + */ override fun createFs( path: Path, env: MutableMap?, ): ZipFileSystem { - /* - * computeIfAbsent, not get-then-put: project setup opens the same JAR from many threads at - * once, and a check-then-act would build a file system per racing caller. Only the last would - * reach the map, so the others are never closed while a walk still holds them -- and the JARs - * most exposed to it are the most shared ones. - */ - return cachedFs.computeIfAbsent(path.normalize().pathString) { - CachedJarFileSystem(this, path, env) + val key = keyOf(path) + repeat(3) { + val cached = cachedFs[key] + val listing = currentListing(path) + if (cached != null) { + if (cached.listing === listing) { + return cached + } + if (cachedFs.remove(key, cached)) { + retired.add(cached) + } + } + val opened = openBound(path, listing) + if (cachedFs.putIfAbsent(key, opened) == null) { + return opened + } + closeFs(opened) + } + throw IOException("JAR kept changing on disk while it was being opened: $path") + } + + /* + * The channel must read the file the listing describes. Opening it between two lookups that + * return the same listing shows the path still matched the listing after the channel opened. A + * JAR replaced in between yields a new listing, and the open is retried once against it. + */ + private fun openBound( + path: Path, + first: JarListing, + ): CachedJarFileSystem { + var listing = first + repeat(2) { + val channel = Files.newByteChannel(path, StandardOpenOption.READ) + val current = + try { + currentListing(path) + } catch (e: Throwable) { + channel.close() + throw e + } + if (current === listing) { + return CachedJarFileSystem(this, path, listing, channel) + } + channel.close() + listing = current } + throw IOException("JAR changed on disk while it was being opened: $path") } + private fun currentListing(path: Path): JarListing = + try { + JarListingCache.SHARED.get(path) + } catch (e: NoSuchFileException) { + throw FileSystemNotFoundException(path.toString()).apply { initCause(e) } + } + + private fun keyOf(path: Path): String = path.toAbsolutePath().normalize().pathString + fun newFileSystem(path: Path): FileSystem? = newFileSystem(path, mutableMapOf()) + /** Closes every cached and retired file system. */ fun clearCache() { cachedFs.values.forEach(this::closeFs) cachedFs.clear() + closeRetired() + } + + /** Closes the file systems superseded by a newer listing of their JAR; call only once no file manager holds them. */ + fun closeRetired() { + while (true) { + closeFs(retired.poll() ?: return) + } } fun clearCaches(predicate: (Path) -> Boolean) = clearCachesForPaths { predicate(Paths.get(it)) } @@ -77,7 +163,7 @@ object CachingJarFileSystemProvider : JarFileSystemProvider() { } fun clearCache(path: Path) { - clearCache(path.normalize().pathString) + clearCache(keyOf(path)) } fun clearCache(path: String) { diff --git a/java/javac-services/src/main/java/dev/mutwakil/androidide/javac/services/fs/JarPackageProviderImpl.kt b/java/javac-services/src/main/java/dev/mutwakil/androidide/javac/services/fs/JarPackageProviderImpl.kt index 940f8900e4..c7d854fb0c 100644 --- a/java/javac-services/src/main/java/dev/mutwakil/androidide/javac/services/fs/JarPackageProviderImpl.kt +++ b/java/javac-services/src/main/java/dev/mutwakil/androidide/javac/services/fs/JarPackageProviderImpl.kt @@ -27,8 +27,8 @@ import java.nio.file.Path * @author Akash Yadav */ object JarPackageProviderImpl : JarPackageProvider { - override fun getPackages(archivePath: Path): MutableMap { - val fs = CachingJarFileSystemProvider.newFileSystem(archivePath) as CachedJarFileSystem - return fs.packages - } -} + override fun getPackages(archivePath: Path): Map { + val fs = CachingJarFileSystemProvider.newFileSystem(archivePath) as CachedJarFileSystem + return fs.packageIndex() + } +} \ No newline at end of file diff --git a/java/javac-services/src/main/java/dev/mutwakil/androidide/javac/services/fs/ListingPackageMap.kt b/java/javac-services/src/main/java/dev/mutwakil/androidide/javac/services/fs/ListingPackageMap.kt new file mode 100644 index 0000000000..f7a0cbd533 --- /dev/null +++ b/java/javac-services/src/main/java/dev/mutwakil/androidide/javac/services/fs/ListingPackageMap.kt @@ -0,0 +1,106 @@ +/* + * 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 dev.mutwakil.androidide.javac.services.fs + +import dev.mutwakil.androidide.zipfs2.listing.JarListing +import jdkx.lang.model.SourceVersion +import openjdk.tools.javac.file.RelativePath.RelativeDirectory +import java.nio.file.Path + +private typealias PackageEntry = Map.Entry + +/** + * A read-only view of the package directories of a JAR, resolved on demand from its [JarListing]. + * + * Keys and values match what javac's archive walk produces: the root plus every directory whose + * segments are all Java identifiers. Nothing is materialized per package. + */ +internal class ListingPackageMap( + private val fs: CachedJarFileSystem, + private val listing: JarListing, +) : AbstractMap() { + override val entries: Set = + object : AbstractSet() { + override val size: Int + get() = PackageIterator().asSequence().count() + + override fun iterator(): Iterator = PackageIterator().asSequence().map { entryOf(it) }.iterator() + + override fun contains(element: PackageEntry): Boolean = get(element.key) == element.value + } + + // The listing root is always a package, so the map is never empty; skips the walk behind size. + override fun isEmpty(): Boolean = false + + override fun containsKey(key: RelativeDirectory): Boolean = indexOf(key) >= 0 + + override fun get(key: RelativeDirectory): Path? { + val index = indexOf(key) + return if (index < 0) null else fs.getPath(listing.name(index)) + } + + private fun entryOf(index: Int): PackageEntry { + val name = listing.name(index) + return java.util.AbstractMap.SimpleImmutableEntry( + RelativeDirectory(name.substring(1)), + fs.getPath(name), + ) + } + + // Returns the listing index of the package directory for the key, or -1 if it is not one. + private fun indexOf(key: RelativeDirectory): Int { + val relative = key.path.removeSuffix("/") + if (relative.isNotEmpty() && !relative.split('/').all(SourceVersion::isIdentifier)) { + return -1 + } + val index = listing.find("/$relative") + return if (index >= 0 && listing.isDirectory(index)) index else -1 + } + + // Depth-first walk that does not descend into files or non-identifier directories. + private inner class PackageIterator : Iterator { + private val pending = ArrayDeque().apply { addLast(0) } + private var upcoming = advance() + + override fun hasNext(): Boolean = upcoming >= 0 + + override fun next(): Int { + val current = upcoming + if (current < 0) throw NoSuchElementException() + upcoming = advance() + return current + } + + private fun advance(): Int { + while (pending.isNotEmpty()) { + val index = pending.removeLast() + val sibling = listing.nextSibling(index) + if (sibling >= 0) pending.addLast(sibling) + if (!isPackage(index)) continue + val child = listing.firstChild(index) + if (child >= 0) pending.addLast(child) + return index + } + return -1 + } + + private fun isPackage(index: Int): Boolean = + listing.isDirectory(index) && + (index == 0 || SourceVersion.isIdentifier(listing.shortName(index))) + } +} \ No newline at end of file diff --git a/java/lsp/src/main/java/dev/mutwakil/androidide/lsp/java/JavaCompilerProvider.java b/java/lsp/src/main/java/dev/mutwakil/androidide/lsp/java/JavaCompilerProvider.java index eee769c271..df65ebf66d 100644 --- a/java/lsp/src/main/java/dev/mutwakil/androidide/lsp/java/JavaCompilerProvider.java +++ b/java/lsp/src/main/java/dev/mutwakil/androidide/lsp/java/JavaCompilerProvider.java @@ -18,10 +18,18 @@ package dev.mutwakil.androidide.lsp.java; import androidx.annotation.NonNull; +import androidx.annotation.Nullable; import dev.mutwakil.androidide.lsp.java.compiler.JavaCompilerService; +import dev.mutwakil.androidide.projects.IProjectManager; import dev.mutwakil.androidide.projects.api.ModuleProject; +import dev.mutwakil.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. @@ -29,47 +37,118 @@ * @author Akash Yadav */ public class JavaCompilerProvider { + private static final Logger logger = LoggerFactory.getLogger(JavaCompilerProvider.class); + private static JavaCompilerProvider sInstance; - private static JavaCompilerProvider sInstance; - private final Map mCompilers = new ConcurrentHashMap<>(); - - private JavaCompilerProvider() {} - - @NonNull - public static JavaCompilerService get(ModuleProject module) { - return JavaCompilerProvider.getInstance().forModule(module); - } - - public static JavaCompilerProvider getInstance() { - if (sInstance == null) { - sInstance = new JavaCompilerProvider(); - } - - return sInstance; - } - - @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 mdoule 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(); - } + /** + * 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); + final ArtifactScope scope = module == null ? null : module.artifactScopeOf(file); + return scope == null ? null : getInstance().forModule(module, scope); + } + + /** 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}, or the no-module compiler when {@code file} is outside every source directory of the selected variant; callers that would analyze such a file must check {@link ModuleProject#artifactScopeOf(Path)} first. + */ + @NonNull + public static JavaCompilerService get(@NonNull ModuleProject module, @NonNull Path file) { + final ArtifactScope scope = module.artifactScopeOf(file); + if (scope == null) { + return JavaCompilerService.NO_MODULE_COMPILER; + } + return JavaCompilerProvider.getInstance().forModule(module, scope); + } + + public static JavaCompilerProvider getInstance() { + if (sInstance == null) { + sInstance = new JavaCompilerProvider(); + } + + return sInstance; + } + + // One compiler per module and test scope: each compiles against its own source path and classpath. + private final Map mCompilers = new ConcurrentHashMap<>(); + + private JavaCompilerProvider() {} + + // TODO This currently destroys all the compiler instances + // We must have a method to destroy only the required instance in + // JavaLanguageServer.handleFailure(LSPFailure) + public synchronized void destroy() { + for (final JavaCompilerService compiler : mCompilers.values()) { + compiler.destroy(); + } + mCompilers.clear(); + } + + /** + * Iterate over all available {@link JavaCompilerService} instances to perform given {@code action} function and return the result of the function. + * + * @param action + * The function to consume the {@link JavaCompilerService} instances and produce a result. The function can return {@code null} to indicate that no result was produced for the provided element. If the function returns a non-null value, the iteration is stopped and the non-null result is returned. If the function returns {@code null} for all elements, then {@code null} is returned. + * @return The result of the action. + * @param + * The type of the result produced by the given function. + */ + @Nullable + public synchronized T find(Function action) { + logger.debug("find from {} compiler services", mCompilers.size()); + for (JavaCompilerService service : mCompilers.values()) { + final var result = action.apply(service); + if (result != null) { + return result; + } + } + return null; + } + + /** The compiler for {@code module}'s {@code scope} sources. */ + @NonNull + public synchronized JavaCompilerService forModule(ModuleProject module, @NonNull ArtifactScope scope) { + // A module instance is set to the compiler only in case the project is initialized or + // this method was called with other module instance. + final Key key = new Key(module, scope); + final JavaCompilerService cached = mCompilers.get(key); + if (cached != null && cached.getModule() != null) { + return cached; + } + + final JavaCompilerService newInstance = new JavaCompilerService(module, scope); + mCompilers.put(key, newInstance); + + return newInstance; + } + + /** Invalidates the cached compiles of {@code module}'s other scopes that read {@code changed}'s sources. */ + public void invalidateScopesSeeing(@NonNull ModuleProject module, @NonNull ArtifactScope changed) { + mCompilers.forEach((key, compiler) -> { + if (key.module() == module && !key.scope().equals(changed) && key.scope().sees(changed)) { + compiler.invalidateCompile(); + } + }); + } + + private record Key(ModuleProject module, @NonNull ArtifactScope scope) {} } diff --git a/java/lsp/src/main/java/dev/mutwakil/androidide/lsp/java/JavaLanguageServer.kt b/java/lsp/src/main/java/dev/mutwakil/androidide/lsp/java/JavaLanguageServer.kt index 829017748d..cc0b40caf4 100644 --- a/java/lsp/src/main/java/dev/mutwakil/androidide/lsp/java/JavaLanguageServer.kt +++ b/java/lsp/src/main/java/dev/mutwakil/androidide/lsp/java/JavaLanguageServer.kt @@ -25,6 +25,7 @@ import dev.mutwakil.androidide.eventbus.events.editor.DocumentSelectedEvent import dev.mutwakil.androidide.javac.services.fs.CacheFSInfoSingleton import dev.mutwakil.androidide.javac.services.fs.CachingJarFileSystemProvider.clearCache import dev.mutwakil.androidide.javac.services.fs.CachingJarFileSystemProvider.clearCachesForPaths +import dev.mutwakil.androidide.javac.services.fs.CachingJarFileSystemProvider.closeRetired import dev.mutwakil.androidide.lsp.api.ILanguageClient import dev.mutwakil.androidide.lsp.api.ILanguageServer import dev.mutwakil.androidide.lsp.api.IServerSettings @@ -66,6 +67,7 @@ import dev.mutwakil.androidide.projects.api.ModuleProject import dev.mutwakil.androidide.projects.api.Workspace import dev.mutwakil.androidide.utils.DocumentUtils import dev.mutwakil.androidide.utils.VMUtils +import dev.mutwakil.androidide.zipfs2.listing.JarListingCache import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Job @@ -114,6 +116,8 @@ class JavaLanguageServer : ILanguageServer { override val serverId: String = SERVER_ID + //override val debugAdapter: IDebugAdapter = JavaDebugAdapter() + companion object { const val SERVER_ID = "ide.lsp.java" private val log = LoggerFactory.getLogger(JavaLanguageServer::class.java) @@ -159,6 +163,7 @@ class JavaLanguageServer : ILanguageServer { } override fun shutdown() { + //(this.debugAdapter as? AutoCloseable?)?.close() JavaCompilerProvider.getInstance().destroy() SourceFileManager.clearCache() CacheFSInfoSingleton.clearCache() @@ -166,6 +171,8 @@ class JavaLanguageServer : ILanguageServer { EventBus.getDefault().unregister(this) timer.cancel() serverScope.cancel() + // Last, so a throwing listener cannot skip the rest; the listings would otherwise outlive the project. + JarListingCache.SHARED.clear() } override fun connectClient(client: ILanguageClient?) { @@ -211,6 +218,9 @@ class JavaLanguageServer : ILanguageServer { // Maybe this could be improved by using data from the AndroidModule project model clearCachesForPaths { path: String -> path.endsWith("/R.jar") } + // The file managers that held the superseded JAR file systems were closed above + closeRetired() + // Clear cached module-specific compilers JavaCompilerProvider.getInstance().destroy() @@ -226,7 +236,7 @@ class JavaLanguageServer : ILanguageServer { override fun complete(params: CompletionParams?): CompletionResult { val compiler = getCompiler(params!!.file) - if (!settings.completionsEnabled() || !completionProvider.canComplete(params.file)) { + if (!settings.completionsEnabled() || !completionProvider.canComplete(params.file) || isOutsideSelectedVariant(params.file)) { return CompletionResult.EMPTY } @@ -249,7 +259,7 @@ class JavaLanguageServer : ILanguageServer { override suspend fun findReferences(params: ReferenceParams): ReferenceResult { val compiler = getCompiler(params.file) - return if (!settings.referencesEnabled()) { + return if (!settings.referencesEnabled() || isOutsideSelectedVariant(params.file)) { ReferenceResult(emptyList()) } else { ReferenceProvider(compiler, params.cancelChecker).findReferences(params) @@ -258,7 +268,7 @@ class JavaLanguageServer : ILanguageServer { override suspend fun findDefinition(params: DefinitionParams): DefinitionResult { val compiler = getCompiler(params.file) - return if (!settings.definitionsEnabled()) { + return if (!settings.definitionsEnabled() || isOutsideSelectedVariant(params.file)) { DefinitionResult(emptyList()) } else { DefinitionProvider(compiler, settings, params.cancelChecker).findDefinition(params) @@ -276,7 +286,7 @@ class JavaLanguageServer : ILanguageServer { override suspend fun signatureHelp(params: SignatureHelpParams): SignatureHelp { val compiler = getCompiler(params.file) - return if (!settings.signatureHelpEnabled()) { + return if (!settings.signatureHelpEnabled() || isOutsideSelectedVariant(params.file)) { SignatureHelp(emptyList(), -1, -1) } else { SignatureProvider(compiler, params.cancelChecker).signatureHelp(params) @@ -309,6 +319,10 @@ class JavaLanguageServer : ILanguageServer { } } + /** Whether [file] is in a module but not compiled by its selected variant, so it gets no analysis. */ + private fun isOutsideSelectedVariant(file: Path): Boolean = + ProjectManagerImpl.getInstance().workspace?.isOutsideSelectedVariant(file) == true + @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) fun getCompiler(file: Path?): JavaCompilerService { if (!DocumentUtils.isJavaFile(file)) { @@ -317,7 +331,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() { @@ -343,9 +357,11 @@ class JavaLanguageServer : ILanguageServer { val module = getInstance() .findModuleForFile(event.changedFile) - if (module != null) { - val compiler = JavaCompilerProvider.get(module) - compiler.onDocumentChange(event) + val changedScope = module?.artifactScopeOf(event.changedFile) + if (module != null && changedScope != null) { + JavaCompilerProvider.getInstance().forModule(module, changedScope).onDocumentChange(event) + // Scopes that compile against the changed one (tests against main or fixtures) are stale now. + JavaCompilerProvider.getInstance().invalidateScopesSeeing(module, changedScope) } startOrRestartAnalyzeTimer() } diff --git a/java/lsp/src/main/java/dev/mutwakil/androidide/lsp/java/actions/BaseJavaCodeAction.kt b/java/lsp/src/main/java/dev/mutwakil/androidide/lsp/java/actions/BaseJavaCodeAction.kt index 7c7863f600..bc345a0679 100644 --- a/java/lsp/src/main/java/dev/mutwakil/androidide/lsp/java/actions/BaseJavaCodeAction.kt +++ b/java/lsp/src/main/java/dev/mutwakil/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/java/lsp/src/main/java/dev/mutwakil/androidide/lsp/java/actions/FieldBasedAction.kt b/java/lsp/src/main/java/dev/mutwakil/androidide/lsp/java/actions/FieldBasedAction.kt index 3811fab87b..55e0873002 100644 --- a/java/lsp/src/main/java/dev/mutwakil/androidide/lsp/java/actions/FieldBasedAction.kt +++ b/java/lsp/src/main/java/dev/mutwakil/androidide/lsp/java/actions/FieldBasedAction.kt @@ -76,7 +76,7 @@ abstract class FieldBasedAction : BaseJavaCodeAction() { val module = IProjectManager.getInstance().workspace?.findModuleForFile(file.toFile(), 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/java/lsp/src/main/java/dev/mutwakil/androidide/lsp/java/actions/diagnostics/AddImportAction.kt b/java/lsp/src/main/java/dev/mutwakil/androidide/lsp/java/actions/diagnostics/AddImportAction.kt index 5627ebea6c..dd6ef76c6c 100644 --- a/java/lsp/src/main/java/dev/mutwakil/androidide/lsp/java/actions/diagnostics/AddImportAction.kt +++ b/java/lsp/src/main/java/dev/mutwakil/androidide/lsp/java/actions/diagnostics/AddImportAction.kt @@ -108,7 +108,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) @@ -155,7 +155,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/java/lsp/src/main/java/dev/mutwakil/androidide/lsp/java/actions/diagnostics/AddThrowsAction.kt b/java/lsp/src/main/java/dev/mutwakil/androidide/lsp/java/actions/diagnostics/AddThrowsAction.kt index 83034330e5..a47760bd62 100644 --- a/java/lsp/src/main/java/dev/mutwakil/androidide/lsp/java/actions/diagnostics/AddThrowsAction.kt +++ b/java/lsp/src/main/java/dev/mutwakil/androidide/lsp/java/actions/diagnostics/AddThrowsAction.kt @@ -62,11 +62,7 @@ class AddThrowsAction : BaseJavaCodeAction() { override suspend fun execAction(data: ActionData): Any { val diagnostic = data[DiagnosticItem::class.java]!! - val compiler = - JavaCompilerProvider.get( - IProjectManager.getInstance().workspace?.findModuleForFile(data.requireFile(), false) - ?: return Any() - ) + val compiler = JavaCompilerProvider.forFile(data.requireFile()) ?: return Any() val file = data.requirePath() return compiler.compile(file).get { task -> val needsThrow = CodeActionUtils.findMethod(task, diagnostic.range) diff --git a/java/lsp/src/main/java/dev/mutwakil/androidide/lsp/java/actions/diagnostics/CreateMissingMethodAction.kt b/java/lsp/src/main/java/dev/mutwakil/androidide/lsp/java/actions/diagnostics/CreateMissingMethodAction.kt index 79a61a23c7..bc669c7d54 100644 --- a/java/lsp/src/main/java/dev/mutwakil/androidide/lsp/java/actions/diagnostics/CreateMissingMethodAction.kt +++ b/java/lsp/src/main/java/dev/mutwakil/androidide/lsp/java/actions/diagnostics/CreateMissingMethodAction.kt @@ -64,11 +64,7 @@ class CreateMissingMethodAction : BaseJavaCodeAction() { override suspend fun execAction(data: ActionData): Any { val diagnostic = data[dev.mutwakil.androidide.lsp.models.DiagnosticItem::class.java]!! - val compiler = - JavaCompilerProvider.get( - IProjectManager.getInstance().workspace?.findModuleForFile(data.requireFile(), false) - ?: return Any() - ) + val compiler = 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/java/lsp/src/main/java/dev/mutwakil/androidide/lsp/java/actions/diagnostics/FieldToBlockAction.kt b/java/lsp/src/main/java/dev/mutwakil/androidide/lsp/java/actions/diagnostics/FieldToBlockAction.kt index 54c534cc0f..ce5e730352 100644 --- a/java/lsp/src/main/java/dev/mutwakil/androidide/lsp/java/actions/diagnostics/FieldToBlockAction.kt +++ b/java/lsp/src/main/java/dev/mutwakil/androidide/lsp/java/actions/diagnostics/FieldToBlockAction.kt @@ -65,11 +65,7 @@ class FieldToBlockAction : BaseJavaCodeAction() { } override suspend fun execAction(data: ActionData): Any { - val compiler = - JavaCompilerProvider.get( - IProjectManager.getInstance().workspace?.findModuleForFile(data.requireFile(), false) - ?: return Any() - ) + val compiler = JavaCompilerProvider.forFile(data.requireFile()) ?: return Any() val diagnostic = data[DiagnosticItem::class.java]!! val file = data.requirePath() diff --git a/java/lsp/src/main/java/dev/mutwakil/androidide/lsp/java/actions/diagnostics/RemoveClassAction.kt b/java/lsp/src/main/java/dev/mutwakil/androidide/lsp/java/actions/diagnostics/RemoveClassAction.kt index b50201b9e6..93d110fb10 100644 --- a/java/lsp/src/main/java/dev/mutwakil/androidide/lsp/java/actions/diagnostics/RemoveClassAction.kt +++ b/java/lsp/src/main/java/dev/mutwakil/androidide/lsp/java/actions/diagnostics/RemoveClassAction.kt @@ -63,11 +63,7 @@ class RemoveClassAction : BaseJavaCodeAction() { override suspend fun execAction(data: ActionData): Any { val diagnostic = data[dev.mutwakil.androidide.lsp.models.DiagnosticItem::class.java]!! - val compiler = - JavaCompilerProvider.get( - IProjectManager.getInstance().workspace?.findModuleForFile(data.requireFile(), false) - ?: return Any() - ) + val compiler = JavaCompilerProvider.forFile(data.requireFile()) ?: return Any() val file = data.requirePath() return compiler.compile(file).get { diff --git a/java/lsp/src/main/java/dev/mutwakil/androidide/lsp/java/actions/diagnostics/RemoveMethodAction.kt b/java/lsp/src/main/java/dev/mutwakil/androidide/lsp/java/actions/diagnostics/RemoveMethodAction.kt index 2026974140..2d79c14145 100644 --- a/java/lsp/src/main/java/dev/mutwakil/androidide/lsp/java/actions/diagnostics/RemoveMethodAction.kt +++ b/java/lsp/src/main/java/dev/mutwakil/androidide/lsp/java/actions/diagnostics/RemoveMethodAction.kt @@ -63,11 +63,7 @@ class RemoveMethodAction : BaseJavaCodeAction() { override suspend fun execAction(data: ActionData): Any { val diagnostic = data[dev.mutwakil.androidide.lsp.models.DiagnosticItem::class.java]!! - val compiler = - JavaCompilerProvider.get( - IProjectManager.getInstance().workspace?.findModuleForFile(data.requireFile(), false) - ?: return Any() - ) + val compiler = JavaCompilerProvider.forFile(data.requireFile()) ?: return Any() val file = data.requirePath() return compiler.compile(file).get { diff --git a/java/lsp/src/main/java/dev/mutwakil/androidide/lsp/java/actions/diagnostics/RemoveUnusedThrowsAction.kt b/java/lsp/src/main/java/dev/mutwakil/androidide/lsp/java/actions/diagnostics/RemoveUnusedThrowsAction.kt index 313eb573a9..5e9147333e 100644 --- a/java/lsp/src/main/java/dev/mutwakil/androidide/lsp/java/actions/diagnostics/RemoveUnusedThrowsAction.kt +++ b/java/lsp/src/main/java/dev/mutwakil/androidide/lsp/java/actions/diagnostics/RemoveUnusedThrowsAction.kt @@ -64,11 +64,7 @@ class RemoveUnusedThrowsAction : BaseJavaCodeAction() { override suspend fun execAction(data: ActionData): Any { val d = data[dev.mutwakil.androidide.lsp.models.DiagnosticItem::class.java]!! - val compiler = - JavaCompilerProvider.get( - IProjectManager.getInstance().workspace?.findModuleForFile(data.requireFile(), false) - ?: return Any() - ) + val compiler = 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/java/lsp/src/main/java/dev/mutwakil/androidide/lsp/java/actions/diagnostics/SuppressUncheckedWarningAction.kt b/java/lsp/src/main/java/dev/mutwakil/androidide/lsp/java/actions/diagnostics/SuppressUncheckedWarningAction.kt index e09f641751..11f1a0275e 100644 --- a/java/lsp/src/main/java/dev/mutwakil/androidide/lsp/java/actions/diagnostics/SuppressUncheckedWarningAction.kt +++ b/java/lsp/src/main/java/dev/mutwakil/androidide/lsp/java/actions/diagnostics/SuppressUncheckedWarningAction.kt @@ -63,11 +63,7 @@ class SuppressUncheckedWarningAction : BaseJavaCodeAction() { override suspend fun execAction(data: ActionData): Any { val diagnostic = data[dev.mutwakil.androidide.lsp.models.DiagnosticItem::class.java]!! - val compiler = - JavaCompilerProvider.get( - IProjectManager.getInstance().workspace?.findModuleForFile(data.requireFile(), false) - ?: return Any() - ) + val compiler = JavaCompilerProvider.forFile(data.requireFile()) ?: return Any() val file = data.requirePath() return compiler.compile(file).get { task -> val warnedMethod = CodeActionUtils.findMethod(task, diagnostic.range) diff --git a/java/lsp/src/main/java/dev/mutwakil/androidide/lsp/java/actions/diagnostics/VariableToStatementAction.kt b/java/lsp/src/main/java/dev/mutwakil/androidide/lsp/java/actions/diagnostics/VariableToStatementAction.kt index e9c0167f0e..af493501b5 100644 --- a/java/lsp/src/main/java/dev/mutwakil/androidide/lsp/java/actions/diagnostics/VariableToStatementAction.kt +++ b/java/lsp/src/main/java/dev/mutwakil/androidide/lsp/java/actions/diagnostics/VariableToStatementAction.kt @@ -68,11 +68,7 @@ class VariableToStatementAction : BaseJavaCodeAction() { override suspend fun execAction(data: ActionData): Any { val diagnostic = data[dev.mutwakil.androidide.lsp.models.DiagnosticItem::class.java]!! - val compiler = - JavaCompilerProvider.get( - IProjectManager.getInstance().workspace?.findModuleForFile(data.requireFile(), false) - ?: return Any() - ) + val compiler = JavaCompilerProvider.forFile(data.requireFile()) ?: return Any() val path = data.requirePath() return compiler.compile(path).get { diff --git a/java/lsp/src/main/java/dev/mutwakil/androidide/lsp/java/actions/generators/GenerateConstructorAction.kt b/java/lsp/src/main/java/dev/mutwakil/androidide/lsp/java/actions/generators/GenerateConstructorAction.kt index fb00dec491..f6045467fd 100644 --- a/java/lsp/src/main/java/dev/mutwakil/androidide/lsp/java/actions/generators/GenerateConstructorAction.kt +++ b/java/lsp/src/main/java/dev/mutwakil/androidide/lsp/java/actions/generators/GenerateConstructorAction.kt @@ -80,11 +80,7 @@ class GenerateConstructorAction : FieldBasedAction() { } private fun generateConstructor(data: ActionData, selected: MutableSet) { - val compiler = - JavaCompilerProvider.get( - IProjectManager.getInstance().workspace?.findModuleForFile(data.requireFile(), false) - ?: return - ) + val compiler = JavaCompilerProvider.forFile(data.requireFile()) ?: return val range = data[dev.mutwakil.androidide.models.Range::class.java]!! val file = data.requirePath() diff --git a/java/lsp/src/main/java/dev/mutwakil/androidide/lsp/java/actions/generators/GenerateMissingConstructorAction.kt b/java/lsp/src/main/java/dev/mutwakil/androidide/lsp/java/actions/generators/GenerateMissingConstructorAction.kt index f7226149d1..99a3174f1d 100644 --- a/java/lsp/src/main/java/dev/mutwakil/androidide/lsp/java/actions/generators/GenerateMissingConstructorAction.kt +++ b/java/lsp/src/main/java/dev/mutwakil/androidide/lsp/java/actions/generators/GenerateMissingConstructorAction.kt @@ -63,11 +63,7 @@ class GenerateMissingConstructorAction : BaseJavaCodeAction() { override suspend fun execAction(data: ActionData): Any { val diagnostic = data[dev.mutwakil.androidide.lsp.models.DiagnosticItem::class.java]!! - val compiler = - JavaCompilerProvider.get( - IProjectManager.getInstance().workspace?.findModuleForFile(data.requireFile(), false) - ?: return Any() - ) + val compiler = JavaCompilerProvider.forFile(data.requireFile()) ?: return Any() val file = data.requirePath() return compiler.compile(file).get { task -> val needsConstructor = diff --git a/java/lsp/src/main/java/dev/mutwakil/androidide/lsp/java/actions/generators/GenerateSettersAndGettersAction.kt b/java/lsp/src/main/java/dev/mutwakil/androidide/lsp/java/actions/generators/GenerateSettersAndGettersAction.kt index 6b1dc1090f..1ae405b2a6 100644 --- a/java/lsp/src/main/java/dev/mutwakil/androidide/lsp/java/actions/generators/GenerateSettersAndGettersAction.kt +++ b/java/lsp/src/main/java/dev/mutwakil/androidide/lsp/java/actions/generators/GenerateSettersAndGettersAction.kt @@ -87,11 +87,7 @@ class GenerateSettersAndGettersAction : FieldBasedAction() { } private fun generateForFields(data: ActionData, names: MutableSet) { - val compiler = - JavaCompilerProvider.get( - IProjectManager.getInstance().workspace?.findModuleForFile(data.requireFile(), false) - ?: return - ) + val compiler = JavaCompilerProvider.forFile(data.requireFile()) ?: return val range = data[dev.mutwakil.androidide.models.Range::class.java]!! val file = data.requirePath() diff --git a/java/lsp/src/main/java/dev/mutwakil/androidide/lsp/java/actions/generators/GenerateToStringMethodAction.kt b/java/lsp/src/main/java/dev/mutwakil/androidide/lsp/java/actions/generators/GenerateToStringMethodAction.kt index 995782e27c..ad769f33c7 100644 --- a/java/lsp/src/main/java/dev/mutwakil/androidide/lsp/java/actions/generators/GenerateToStringMethodAction.kt +++ b/java/lsp/src/main/java/dev/mutwakil/androidide/lsp/java/actions/generators/GenerateToStringMethodAction.kt @@ -82,11 +82,7 @@ class GenerateToStringMethodAction : FieldBasedAction() { } private fun generateToString(data: ActionData, selected: MutableSet) { - val compiler = - JavaCompilerProvider.get( - IProjectManager.getInstance().workspace?.findModuleForFile(data.requireFile(), false) - ?: return - ) + val compiler = JavaCompilerProvider.forFile(data.requireFile()) ?: return val range = data[dev.mutwakil.androidide.models.Range::class.java]!! val file = data.requirePath() diff --git a/java/lsp/src/main/java/dev/mutwakil/androidide/lsp/java/actions/generators/OverrideSuperclassMethodsAction.kt b/java/lsp/src/main/java/dev/mutwakil/androidide/lsp/java/actions/generators/OverrideSuperclassMethodsAction.kt index 0b0af6475c..408fcd108a 100644 --- a/java/lsp/src/main/java/dev/mutwakil/androidide/lsp/java/actions/generators/OverrideSuperclassMethodsAction.kt +++ b/java/lsp/src/main/java/dev/mutwakil/androidide/lsp/java/actions/generators/OverrideSuperclassMethodsAction.kt @@ -93,11 +93,7 @@ class OverrideSuperclassMethodsAction : BaseJavaCodeAction() { override suspend fun execAction(data: ActionData): Any { val range = data[dev.mutwakil.androidide.models.Range::class.java]!! - val compiler = - JavaCompilerProvider.get( - IProjectManager.getInstance().workspace?.findModuleForFile(data.requireFile(), false) - ?: return Any() - ) + val compiler = JavaCompilerProvider.forFile(data.requireFile()) ?: return Any() val file = data.requirePath() return compiler.compile(file).get { task -> diff --git a/java/lsp/src/main/java/dev/mutwakil/androidide/lsp/java/compiler/ClasspathTypeLookup.kt b/java/lsp/src/main/java/dev/mutwakil/androidide/lsp/java/compiler/ClasspathTypeLookup.kt index 67b788d893..643df008d1 100644 --- a/java/lsp/src/main/java/dev/mutwakil/androidide/lsp/java/compiler/ClasspathTypeLookup.kt +++ b/java/lsp/src/main/java/dev/mutwakil/androidide/lsp/java/compiler/ClasspathTypeLookup.kt @@ -2,6 +2,7 @@ package dev.mutwakil.androidide.lsp.java.compiler import dev.mutwakil.androidide.projects.ProjectManagerImpl import dev.mutwakil.androidide.projects.api.ModuleProject +import dev.mutwakil.androidide.projects.models.ArtifactScope import org.appdevforall.codeonthego.indexing.jvm.JvmSymbol import org.appdevforall.codeonthego.indexing.jvm.JvmVisibility import org.appdevforall.codeonthego.indexing.jvm.ModuleClasspathLookup @@ -137,16 +138,18 @@ class ClasspathTypeLookup internal constructor( companion object { /** * Creates the lookup for [module] over the indexes registered with the project manager, and the - * boot classes [bootClasses] returns. A `null` [module] has no source or classpath classes. + * boot classes [bootClasses] returns. Source classes are [scope]'s. A + * `null` [module] has no source or classpath classes. */ @JvmStatic fun forModule( module: ModuleProject?, + scope: ArtifactScope, bootClasses: () -> Collection, ) = ClasspathTypeLookup( sourceClasses = { module - ?.compileJavaSourceClasses + ?.javaSourceClasses(scope) ?.allSources() ?.map { it.qualifiedName } .orEmpty() diff --git a/java/lsp/src/main/java/dev/mutwakil/androidide/lsp/java/compiler/CompileBatch.java b/java/lsp/src/main/java/dev/mutwakil/androidide/lsp/java/compiler/CompileBatch.java index 78fc3caa86..5cc6f878a7 100644 --- a/java/lsp/src/main/java/dev/mutwakil/androidide/lsp/java/compiler/CompileBatch.java +++ b/java/lsp/src/main/java/dev/mutwakil/androidide/lsp/java/compiler/CompileBatch.java @@ -154,11 +154,11 @@ private List options() { System.setProperty(PROP_ANDROIDIDE_JAVA_HOME, JAVA_HOME.getAbsolutePath()); if (this.parent.module != null && this.parent.module.hasAndroidProject()) { setLatestSourceVersion(SourceVersion.RELEASE_8); - setLatestSupportedSourceVersion(SourceVersion.RELEASE_17); + setLatestSupportedSourceVersion(SourceVersion.RELEASE_11); disableModules(); } else { - setLatestSourceVersion(SourceVersion.RELEASE_17); - setLatestSupportedSourceVersion(SourceVersion.RELEASE_17); + setLatestSourceVersion(SourceVersion.RELEASE_11); + setLatestSupportedSourceVersion(SourceVersion.RELEASE_11); enableModules(); } @@ -235,7 +235,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/java/lsp/src/main/java/dev/mutwakil/androidide/lsp/java/compiler/JavaCompilerService.java b/java/lsp/src/main/java/dev/mutwakil/androidide/lsp/java/compiler/JavaCompilerService.java index ac9fa0a19c..3a0f56eeaf 100644 --- a/java/lsp/src/main/java/dev/mutwakil/androidide/lsp/java/compiler/JavaCompilerService.java +++ b/java/lsp/src/main/java/dev/mutwakil/androidide/lsp/java/compiler/JavaCompilerService.java @@ -37,6 +37,7 @@ import dev.mutwakil.androidide.projects.FileManager; import dev.mutwakil.androidide.projects.api.AndroidModule; import dev.mutwakil.androidide.projects.api.ModuleProject; +import dev.mutwakil.androidide.projects.models.ArtifactScope; import dev.mutwakil.androidide.projects.util.BootClasspathProvider; import dev.mutwakil.androidide.projects.util.StringSearch; import dev.mutwakil.androidide.utils.Cache; @@ -83,12 +84,15 @@ public class JavaCompilerService implements CompilerProvider { protected final SynchronizedTask synchronizedTask = new SynchronizedTask(); protected final SourceFileManager fileManager; protected final ModuleProject module; + @NonNull + protected final ArtifactScope scope; private final ClasspathTypeLookup types; public ReusableCompiler compiler = new JCReusableCompiler(); protected Set bootClasspathClasses = BootClasspathProvider.getTopLevelClasses( Collections.singleton(Environment.ANDROID_JAR.getAbsolutePath())); private CompileBatch cachedCompile; private int changeDelta = 0; + private volatile boolean stale = false; private Position lastReparsePosition = Position.NONE; private Position newCursorPosition = Position.NONE; @@ -96,14 +100,20 @@ public class JavaCompilerService implements CompilerProvider { // The module project must not be null // It is marked as nullable just for some special cases like tests public JavaCompilerService(@Nullable ModuleProject module) { + this(module, ArtifactScope.Main.INSTANCE); + } + + /** A compiler for {@code module}'s {@code scope} sources. */ + public JavaCompilerService(@Nullable ModuleProject module, @NonNull ArtifactScope scope) { this.module = module; + this.scope = scope; if (module == null) { this.fileManager = SourceFileManager.NO_MODULE; } else { - this.fileManager = SourceFileManager.forModule(module); + this.fileManager = SourceFileManager.forModule(module, scope); this.bootClasspathClasses = Collections.unmodifiableSet(getBootclasspathClasses()); } - this.types = ClasspathTypeLookup.forModule(module, () -> this.bootClasspathClasses); + this.types = ClasspathTypeLookup.forModule(module, scope, () -> this.bootClasspathClasses); } @VisibleForTesting @@ -112,7 +122,17 @@ public JavaCompilerService(@Nullable ModuleProject module) { SourceFileManager fileManager, Set bootClasspathClasses, ClasspathTypeLookup types) { + this(module, ArtifactScope.Main.INSTANCE, fileManager, bootClasspathClasses, types); + } + + private JavaCompilerService( + @Nullable ModuleProject module, + @NonNull ArtifactScope scope, + SourceFileManager fileManager, + Set bootClasspathClasses, + ClasspathTypeLookup types) { this.module = module; + this.scope = scope; this.fileManager = fileManager; this.bootClasspathClasses = bootClasspathClasses; this.types = types; @@ -143,7 +163,7 @@ public SynchronizedTask compile(final CompilationRequest request) { public JavaCompilerService copy() { final JavaCompilerService compiler = new JavaCompilerService( - this.module, this.fileManager, this.bootClasspathClasses, this.types); + this.module, this.scope, this.fileManager, this.bootClasspathClasses, this.types); compiler.cachedCompile = null; compiler.newCursorPosition = Position.NONE; compiler.lastReparsePosition = Position.NONE; @@ -186,7 +206,7 @@ public List findImportableQualifiedNames(String simpleName, String impor @Override public Path[] findMemberReferences(String className, String memberName) { List candidates = new ArrayList<>(); - List sourceNodes = module != null ? module.compileJavaSourceClasses.allSources() : Collections.emptyList(); + List sourceNodes = module != null ? getSourceClasses().allSources() : Collections.emptyList(); for (SourceClassTrie.SourceNode node : sourceNodes) { final Path path = node.getFile(); if (containsWord(path, memberName)) { @@ -207,7 +227,7 @@ public Path findTypeDeclaration(String className) { // optimization. String packageName = Extractors.packageName(className); String simpleName = Extractors.simpleName(className); - List classes = module != null ? module.listClassesFromSourceDirs(packageName) : Collections.emptyList(); + List classes = module != null ? module.listClassesFromSourceDirs(packageName, scope) : Collections.emptyList(); for (SourceClassTrie.SourceNode node : classes) { final Path path = node.getFile(); if (containsWord(path, simpleName) && containsType(path, className)) { @@ -232,7 +252,7 @@ public Path[] findTypeReferences(String className) { String packageName = Extractors.packageName(className); String simpleName = Extractors.simpleName(className); List candidates = new ArrayList<>(); - List sourceNodes = module != null ? module.compileJavaSourceClasses.allSources() : Collections.emptyList(); + List sourceNodes = module != null ? getSourceClasses().allSources() : Collections.emptyList(); for (SourceClassTrie.SourceNode node : sourceNodes) { final Path path = node.getFile(); if (containsWord(path, packageName) @@ -249,10 +269,28 @@ public ModuleProject getModule() { return module; } + /** The scope this compiler compiles. */ + @NonNull + public ArtifactScope getScope() { + return scope; + } + + /** The Java source classes this compiler sees: main's, or main's plus its test scope's. Requires a module. */ + public SourceClassTrie getSourceClasses() { + return module.javaSourceClasses(scope); + } + public SynchronizedTask getSynchronizedTask() { return synchronizedTask; } + /** + * Makes the next request recompile. The cache only checks the requested files' timestamps, so it cannot see an edit to a source it merely reads, such as a main source a test reads. Only sets a flag: callers run per keystroke and must not wait on a compile in progress. + */ + public void invalidateCompile() { + stale = true; + } + public void onDocumentChange(@NonNull DocumentChangeEvent event) { this.changeDelta += event.getChangeDelta(); this.newCursorPosition = event.getChangeRange().getEnd(); @@ -275,6 +313,12 @@ public ParseTask parse(Path file) { return new ParseTask(parser.task, parser.root); } + /** Whether the next request recompiles regardless of the cache. */ + @VisibleForTesting + boolean isStale() { + return stale; + } + @Nullable private Pair binarySearchCurrentMethod( @NonNull final List> positions, final long cursor) { @@ -301,7 +345,11 @@ private Pair binarySearchCurrentMethod( private SynchronizedTask compileBatch(CompilationRequest request) { synchronizedTask.post( () -> { - if (needsCompilation(request.sources)) { + if (stale) { + // Cleared first, so an invalidation during this compile marks it stale again. + stale = false; + recompile(request); + } else if (needsCompilation(request.sources)) { reparseOrRecompile(request); } else { LOG.info("...using cached compile"); @@ -435,7 +483,7 @@ private boolean needsRecompilation(final CompilationRequest request) { } private String packageNameOrEmpty(Path file) { - return module != null ? module.packageNameOrEmpty(file) : ""; + return module != null ? module.packageNameOrEmpty(file, scope) : ""; } private CompileBatch performCompilation(CompilationRequest request) { diff --git a/java/lsp/src/main/java/dev/mutwakil/androidide/lsp/java/compiler/SourceFileManager.java b/java/lsp/src/main/java/dev/mutwakil/androidide/lsp/java/compiler/SourceFileManager.java index 0b393f585b..27b27d5333 100644 --- a/java/lsp/src/main/java/dev/mutwakil/androidide/lsp/java/compiler/SourceFileManager.java +++ b/java/lsp/src/main/java/dev/mutwakil/androidide/lsp/java/compiler/SourceFileManager.java @@ -21,18 +21,22 @@ import static java.util.Collections.emptySet; import androidx.annotation.NonNull; -import com.blankj.utilcode.util.CloseUtils; import dev.mutwakil.androidide.javac.config.JavacConfigProvider; import dev.mutwakil.androidide.javac.services.fs.AndroidFsProviderImpl; +import dev.mutwakil.androidide.javac.services.fs.JarPackageProviderImpl; import dev.mutwakil.androidide.projects.api.AndroidModule; import dev.mutwakil.androidide.projects.api.ModuleProject; import dev.mutwakil.androidide.projects.models.AndroidProjectExtsKt; +import dev.mutwakil.androidide.projects.models.ArtifactScope; import dev.mutwakil.androidide.projects.util.StringSearch; import dev.mutwakil.androidide.utils.ClassTrie; import dev.mutwakil.androidide.utils.Environment; import dev.mutwakil.androidide.utils.SourceClassTrie; +import dev.mutwakil.androidide.zipfs2.JarPackageProvider; import java.io.File; import java.io.IOException; +import java.io.OutputStreamWriter; +import java.io.PrintWriter; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; @@ -44,216 +48,239 @@ import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.stream.Stream; +import jdkx.tools.DiagnosticListener; import jdkx.tools.FileObject; import jdkx.tools.ForwardingJavaFileManager; import jdkx.tools.JavaFileObject; import jdkx.tools.StandardLocation; -import openjdk.tools.javac.api.JavacTool; +import openjdk.tools.javac.file.CacheFSInfo; import openjdk.tools.javac.file.JavacFileManager; import openjdk.tools.javac.util.Context; +import openjdk.tools.javac.util.Log; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class SourceFileManager extends ForwardingJavaFileManager { - public static final SourceFileManager NO_MODULE; - private static final Logger LOG; - private static final Map cachedFileManagers = - new ConcurrentHashMap<>(); - - static { - // Initialize LOG first to prevent NPE - LOG = LoggerFactory.getLogger(SourceFileManager.class); - NO_MODULE = new SourceFileManager(null); - } - - private final ModuleProject module; - - private SourceFileManager(final ModuleProject module) { - super(createDelegateFileManager()); - this.module = module; - - AndroidFsProviderImpl.INSTANCE.init(); - - if (module == null) { - return; - } - - // Must be set before setting classpaths - System.setProperty(JavacConfigProvider.PROP_ANDROIDIDE_JAVA_HOME, - Environment.JAVA_HOME.getAbsolutePath()); - - setLocationLogError(StandardLocation.SOURCE_PATH, module.getCompileSourceDirectories()); - setLocationLogError(StandardLocation.CLASS_PATH, configureClasspaths(module)); - listLocations(EnumSet.of(StandardLocation.CLASS_PATH, StandardLocation.PLATFORM_CLASS_PATH)); - } - - @NonNull - private Set configureClasspaths(final ModuleProject module) { - if (module == null) { - return emptySet(); - } - - if (module instanceof AndroidModule androidModule) { - setLocationLogError(StandardLocation.PLATFORM_CLASS_PATH, AndroidProjectExtsKt.getBootClassPaths(androidModule)); - } - - return module.getCompileClasspaths(); - } - - private static JavacFileManager createDelegateFileManager() { - return JavacTool.create() - .getStandardFileManager(msg -> LOG.debug(String.valueOf(msg)), Locale.getDefault(), - StandardCharsets.UTF_8); - } - - public void setLocationLogError(Location location, Iterable searchPath) { - try { - fileManager.setLocation(location, searchPath); - } catch (IOException e) { - LOG.error("Unable to set location", e); - } - } - - private void listLocations(final EnumSet locations) { - for (StandardLocation location : locations) { - try { - fileManager.cacheLocation(location); - } catch (Exception e) { - // Ignored - LOG.debug("Failed to list location: {}", location, e); - } - } - } - - @Override - public Iterable list( - Location location, String packageName, Set kinds, boolean recurse) - throws IOException { - if (location == StandardLocation.SOURCE_PATH) { - if (this.module == null) { - return emptyList(); - } - - final ClassTrie.Node node = module.compileJavaSourceClasses.findNode(packageName); - if (node == null || node.isClass()) { - return emptyList(); - } - - final Stream nodes; - if (recurse) { - nodes = node.allClassNodes().stream(); - } else { - nodes = node.getChildren().values().stream(); - } - - final Stream stream = - nodes - .filter(it -> it instanceof SourceClassTrie.SourceNode) - .map(it -> asJavaFileObject((SourceClassTrie.SourceNode) it)) - .filter(Objects::nonNull); - - return stream::iterator; - } - - return super.list(location, packageName, kinds, recurse); - } - - @Override - public String inferBinaryName(Location location, JavaFileObject file) { - if (location == StandardLocation.SOURCE_PATH) { - SourceFileObject source = (SourceFileObject) file; - String packageName = packageNameOrEmpty(source.path); - String className = removeExtension(source.path.getFileName().toString()); - if (!packageName.isEmpty()) { - className = packageName + "." + className; - } - return className; - } - - return super.inferBinaryName(location, file); - } - - @Override - public boolean hasLocation(Location location) { - return location == StandardLocation.SOURCE_PATH || super.hasLocation(location); - } - - @Override - public JavaFileObject getJavaFileForInput( - Location location, String className, JavaFileObject.Kind kind) throws IOException { - if (location == StandardLocation.SOURCE_PATH) { - String packageName = StringSearch.mostName(className); - String simpleClassName = StringSearch.lastName(className); - List classes = - module != null ? module.listClassesFromSourceDirs(packageName) : emptyList(); - for (SourceClassTrie.SourceNode node : classes) { - final Path path = node.getFile(); - if (path.getFileName().toString().equals(simpleClassName + kind.extension)) { - if (!Files.exists(path))return null; - - return new SourceFileObject(path); - } - } - // Fall through to disk in case we have .jar or .zip files on the source path - } - return super.getJavaFileForInput(location, className, kind); - } - - @Override - public FileObject getFileForInput(Location location, String packageName, String relativeName) - throws IOException { - if (location == StandardLocation.SOURCE_PATH) { - return null; - } - return super.getFileForInput(location, packageName, relativeName); - } - - @Override - 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; - } else { - return super.contains(location, file); - } - } - - private String packageNameOrEmpty(Path file) { - return this.module != null ? module.packageNameOrEmpty(file) : ""; - } - - private String removeExtension(String fileName) { - int lastDot = fileName.lastIndexOf("."); - return (lastDot == -1 ? fileName : fileName.substring(0, lastDot)); - } - - private JavaFileObject asJavaFileObject(SourceClassTrie.SourceNode node) { - final Path path = node.getFile(); - if (!Files.exists(path))return null ; - // TODO erase method bodies of files that are not open - return new SourceFileObject(node.getFile()); - } - - public static SourceFileManager forModule(@NonNull ModuleProject project) { - Objects.requireNonNull(project); - return cachedFileManagers.computeIfAbsent(project, SourceFileManager::createForModule); - } - - private static SourceFileManager createForModule(@NonNull ModuleProject project) { - LOG.info("Creating source file manager instance for module: {}", project); - return new SourceFileManager(project); - } - - public static void clearCache() { - for (final SourceFileManager fileManager : cachedFileManagers.values()) { - CloseUtils.closeIO(fileManager); - } - - cachedFileManagers.clear(); - } - - public void setContext(final Context context) { - fileManager.setContext(context); - } + public static final SourceFileManager NO_MODULE; + private static final Logger LOG; + // 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, null); + } + + public static void clearCache() { + for (final SourceFileManager fileManager : cachedFileManagers.values()) { + try { + fileManager.close(); + } catch (IOException e) { + LOG.warn("Failed to close SourceFileManager", e); + } + } + + cachedFileManagers.clear(); + } + + public static SourceFileManager forModule(@NonNull ModuleProject project) { + return forModule(project, ArtifactScope.Main.INSTANCE); + } + + /** The file manager for {@code project}'s {@code scope} sources. */ + public static SourceFileManager forModule(@NonNull ModuleProject project, @NonNull ArtifactScope scope) { + Objects.requireNonNull(project); + return cachedFileManagers.computeIfAbsent(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. */ + static JavacFileManager createDelegateFileManager() { + final Context context = new Context(); + context.put(Locale.class, Locale.getDefault()); + context.put(DiagnosticListener.class, (DiagnosticListener) msg -> LOG.debug(String.valueOf(msg))); + context.put(Log.errKey, new PrintWriter(new OutputStreamWriter(System.err, StandardCharsets.UTF_8), true)); + CacheFSInfo.preRegister(context); + context.put(JarPackageProvider.class, JarPackageProviderImpl.INSTANCE); + return new JavacFileManager(context, true, StandardCharsets.UTF_8); + } + + 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 final ArtifactScope scope; + + private SourceFileManager(final ModuleProject module, final ArtifactScope scope) { + super(createDelegateFileManager()); + this.module = module; + this.scope = scope; + + AndroidFsProviderImpl.INSTANCE.init(); + + if (module == null) { + return; + } + + // Must be set before setting classpaths + System.setProperty(JavacConfigProvider.PROP_ANDROIDIDE_JAVA_HOME, + Environment.JAVA_HOME.getAbsolutePath()); + + final Set sourcePath = module.getCompileSourceDirectories(scope); + setLocationLogError(StandardLocation.SOURCE_PATH, sourcePath); + setLocationLogError(StandardLocation.CLASS_PATH, configureClasspaths(module)); + listLocations(EnumSet.of(StandardLocation.CLASS_PATH, StandardLocation.PLATFORM_CLASS_PATH)); + } + + @Override + public boolean contains(Location location, FileObject file) throws IOException { + if (location == StandardLocation.SOURCE_PATH) { + SourceFileObject source = (SourceFileObject) file; + return module.javaSourceClasses(scope).findSource(source.path) != null; + } else { + return super.contains(location, file); + } + } + + @Override + public FileObject getFileForInput(Location location, String packageName, String relativeName) + throws IOException { + if (location == StandardLocation.SOURCE_PATH) { + return null; + } + return super.getFileForInput(location, packageName, relativeName); + } + + @Override + public JavaFileObject getJavaFileForInput( + Location location, String className, JavaFileObject.Kind kind) throws IOException { + if (location == StandardLocation.SOURCE_PATH) { + String packageName = StringSearch.mostName(className); + String simpleClassName = StringSearch.lastName(className); + 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)) { + if (!Files.exists(path)) + return null; + + return new SourceFileObject(path); + } + } + // Fall through to disk in case we have .jar or .zip files on the source path + } + return super.getJavaFileForInput(location, className, kind); + } + + @Override + public boolean hasLocation(Location location) { + return location == StandardLocation.SOURCE_PATH || super.hasLocation(location); + } + + @Override + public String inferBinaryName(Location location, JavaFileObject file) { + if (location == StandardLocation.SOURCE_PATH) { + SourceFileObject source = (SourceFileObject) file; + String packageName = packageNameOrEmpty(source.path); + String className = removeExtension(source.path.getFileName().toString()); + if (!packageName.isEmpty()) { + className = packageName + "." + className; + } + return className; + } + + return super.inferBinaryName(location, file); + } + + @Override + public Iterable list( + Location location, String packageName, Set kinds, boolean recurse) + throws IOException { + if (location == StandardLocation.SOURCE_PATH) { + if (this.module == null) { + return emptyList(); + } + + final ClassTrie.Node node = module.javaSourceClasses(scope).findNode(packageName); + if (node == null || node.isClass()) { + return emptyList(); + } + + final Stream nodes; + if (recurse) { + nodes = node.allClassNodes().stream(); + } else { + nodes = node.getChildren().values().stream(); + } + + final Stream stream = nodes + .filter(it -> it instanceof SourceClassTrie.SourceNode) + .map(it -> asJavaFileObject((SourceClassTrie.SourceNode) it)) + .filter(Objects::nonNull); + + return stream::iterator; + } + + return super.list(location, packageName, kinds, recurse); + } + + public void setContext(final Context context) { + fileManager.setContext(context); + } + + public void setLocationLogError(Location location, Iterable searchPath) { + try { + fileManager.setLocation(location, searchPath); + } catch (IOException e) { + LOG.error("Unable to set location", e); + } + } + + private JavaFileObject asJavaFileObject(SourceClassTrie.SourceNode node) { + final Path path = node.getFile(); + if (!Files.exists(path)) + return null; + + // TODO erase method bodies of files that are not open + return new SourceFileObject(node.getFile()); + } + + @NonNull + private Set configureClasspaths(final ModuleProject module) { + if (module == null) { + return emptySet(); + } + + if (module instanceof AndroidModule androidModule) { + setLocationLogError(StandardLocation.PLATFORM_CLASS_PATH, AndroidProjectExtsKt.getBootClassPaths(androidModule)); + } + + return module.getCompileClasspaths(scope, false); + } + + private void listLocations(final EnumSet locations) { + for (StandardLocation location : locations) { + try { + fileManager.cacheLocation(location); + } catch (Exception e) { + // Ignored + LOG.debug("Failed to list location: {}", location, e); + } + } + } + + private String packageNameOrEmpty(Path file) { + return this.module != null ? module.packageNameOrEmpty(file, scope) : ""; + } + + private String removeExtension(String fileName) { + int lastDot = fileName.lastIndexOf("."); + return (lastDot == -1 ? fileName : fileName.substring(0, lastDot)); + } + + private record Key(ModuleProject module, ArtifactScope scope) {} } diff --git a/java/lsp/src/main/java/dev/mutwakil/androidide/lsp/java/edits/AdvancedJavaEditHandler.kt b/java/lsp/src/main/java/dev/mutwakil/androidide/lsp/java/edits/AdvancedJavaEditHandler.kt index b7164ee8b2..468cabf516 100644 --- a/java/lsp/src/main/java/dev/mutwakil/androidide/lsp/java/edits/AdvancedJavaEditHandler.kt +++ b/java/lsp/src/main/java/dev/mutwakil/androidide/lsp/java/edits/AdvancedJavaEditHandler.kt @@ -40,9 +40,7 @@ abstract class AdvancedJavaEditHandler(protected val file: Path) : BaseJavaEditH column: Int, index: Int ) { - val compiler = JavaCompilerProvider.get( - IProjectManager.getInstance().workspace?.findModuleForFile(file.toFile(), false) ?: return - ) + val compiler = JavaCompilerProvider.forFile(file) ?: return performEdits(compiler, editor, item) executeCommand(editor, item.command) diff --git a/java/lsp/src/main/java/dev/mutwakil/androidide/lsp/java/providers/JavaDiagnosticProvider.kt b/java/lsp/src/main/java/dev/mutwakil/androidide/lsp/java/providers/JavaDiagnosticProvider.kt index 77395c8e3f..fef234fb5d 100644 --- a/java/lsp/src/main/java/dev/mutwakil/androidide/lsp/java/providers/JavaDiagnosticProvider.kt +++ b/java/lsp/src/main/java/dev/mutwakil/androidide/lsp/java/providers/JavaDiagnosticProvider.kt @@ -36,121 +36,124 @@ 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().workspace?.findModuleForFile(file.toFile(), false) - ?: return DiagnosticResult.NO_UPDATE - val compiler = JavaCompilerService(module) - - abortIfCancelled() - - log.debug("Analyzing: {}", file) - - val modifiedAt = FileManager.getLastModified(file) - val analyzedAt = analyzeTimestamps[file] - - if (analyzedAt?.isAfter(modifiedAt) == true) { - log.debug("Using cached analyze results...") - return cachedDiagnostics - } - - analyzingThread?.let { analyzingThread -> - if (analyzing.get()) { - log.debug("Cancelling currently analyzing thread...") - ProgressManager.instance.cancel(analyzingThread) - this.analyzingThread = null - } - } - - analyzing.set(true) - - 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 cancel() { - this.analyzingThread?.cancel() - } - - fun clearTimestamp(file: Path) { - analyzeTimestamps.remove(file) - } - - private fun doAnalyze(file: Path, task: CompileTask): DiagnosticResult { - val result = - if (!isTaskValid(task)) { - // Do not use Collections.emptyList () - // The returned list is accessed and the list returned by Collections.emptyList() - // throws exception when trying to access. - log.info("Using cached diagnostics") - cachedDiagnostics - } else - DiagnosticResult( - file, - findDiagnostics(task, file).sortedBy { - it.range - } - ) - return result.also { - log.info("Analyze file completed. Found {} diagnostic items", result.diagnostics.size) - } - } - - private fun isTaskValid(task: CompileTask?): Boolean { - abortIfCancelled() - return task?.task != null && task.roots != null && task.roots.size > 0 - } - - inner class AnalyzingThread(val compiler: JavaCompilerService, val file: Path) : - Thread("JavaAnalyzerThread") { - - var result: DiagnosticResult = DiagnosticResult.NO_UPDATE - - fun cancel() { - ProgressManager.instance.cancel(this) - } - - override fun run() { - result = - try { - compiler.compile(file).get { task -> doAnalyze(file, task) } - } catch (err: Throwable) { - if (CancelChecker.isCancelled(err)) { - log.error("Analyze request cancelled") - } else { - log.warn("Unable to analyze file", err) - } - DiagnosticResult.NO_UPDATE - } finally { - compiler.destroy() - analyzing.set(false) - } - .also { - cachedDiagnostics = it - analyzeTimestamps[file] = Instant.now() - } - } - } + 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 + // Outside the selected variant: clear what an earlier variant reported, analyze nothing. + val scope = module.artifactScopeOf(file) ?: return DiagnosticResult(file, ArrayList()) + val compiler = JavaCompilerService(module, scope) + + abortIfCancelled() + + log.debug("Analyzing: {}", file) + + val modifiedAt = FileManager.getLastModified(file) + val analyzedAt = analyzeTimestamps[file] + + if (analyzedAt?.isAfter(modifiedAt) == true) { + log.debug("Using cached analyze results...") + return cachedDiagnostics + } + + analyzingThread?.let { analyzingThread -> + if (analyzing.get()) { + log.debug("Cancelling currently analyzing thread...") + ProgressManager.instance.cancel(analyzingThread) + this.analyzingThread = null + } + } + + analyzing.set(true) + + val analyzingThread = + AnalyzingThread(compiler, file).also { + analyzingThread = it + it.start() + it.join() + } + + return analyzingThread.result.also { + this.analyzingThread = null + } + } + + fun isAnalyzing(): Boolean = this.analyzing.get() + + fun cancel() { + this.analyzingThread?.cancel() + } + + fun clearTimestamp(file: Path) { + analyzeTimestamps.remove(file) + } + + private fun doAnalyze( + file: Path, + task: CompileTask, + ): DiagnosticResult { + val result = + if (!isTaskValid(task)) { + // Do not use Collections.emptyList () + // The returned list is accessed and the list returned by Collections.emptyList() + // throws exception when trying to access. + log.info("Using cached diagnostics") + cachedDiagnostics + } else { + DiagnosticResult( + file, + findDiagnostics(task, file).sortedBy { + it.range + }, + ) + } + return result.also { + log.info("Analyze file completed. Found {} diagnostic items", result.diagnostics.size) + } + } + + private fun isTaskValid(task: CompileTask?): Boolean { + abortIfCancelled() + return task?.task != null && task.roots != null && task.roots.size > 0 + } + + inner class AnalyzingThread( + val compiler: JavaCompilerService, + val file: Path, + ) : Thread("JavaAnalyzerThread") { + var result: DiagnosticResult = DiagnosticResult.NO_UPDATE + + fun cancel() { + ProgressManager.instance.cancel(this) + } + + override fun run() { + result = + try { + compiler.compile(file).get { task -> doAnalyze(file, task) } + } catch (err: Throwable) { + if (CancelChecker.isCancelled(err)) { + log.error("Analyze request cancelled") + } else { + log.warn("Unable to analyze file", err) + } + DiagnosticResult.NO_UPDATE + } finally { + compiler.destroy() + analyzing.set(false) + }.also { + cachedDiagnostics = it + analyzeTimestamps[file] = Instant.now() + } + } + } } diff --git a/java/lsp/src/main/java/dev/mutwakil/androidide/lsp/java/providers/completion/ImportCompletionProvider.kt b/java/lsp/src/main/java/dev/mutwakil/androidide/lsp/java/providers/completion/ImportCompletionProvider.kt index 63d240c81e..e9e2a2c439 100644 --- a/java/lsp/src/main/java/dev/mutwakil/androidide/lsp/java/providers/completion/ImportCompletionProvider.kt +++ b/java/lsp/src/main/java/dev/mutwakil/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/indexing/build.gradle.kts b/lsp/indexing/build.gradle.kts index 571d16aee7..391f50516e 100644 --- a/lsp/indexing/build.gradle.kts +++ b/lsp/indexing/build.gradle.kts @@ -16,6 +16,7 @@ dependencies { api(libs.kotlinx.coroutines.core) api(projects.logging.logger) + implementation(projects.utilities.shared) testImplementation(projects.testing.unitTest) testImplementation(libs.tests.kotlinx.coroutines) diff --git a/lsp/indexing/src/main/kotlin/org/appdevforall/codeonthego/indexing/IndexSessionLifetime.kt b/lsp/indexing/src/main/kotlin/org/appdevforall/codeonthego/indexing/IndexSessionLifetime.kt new file mode 100644 index 0000000000..54bab966bd --- /dev/null +++ b/lsp/indexing/src/main/kotlin/org/appdevforall/codeonthego/indexing/IndexSessionLifetime.kt @@ -0,0 +1,21 @@ +package org.appdevforall.codeonthego.indexing + +/** + * Marks whether the project session that owns a set of indexes has ended. + * + * Indexes of an ended session are expected to be used after close while the session's remaining + * work winds down, so they log that at DEBUG; a live session's use after close is a bug and logs ERROR. + */ +class IndexSessionLifetime { + @Volatile + private var ended = false + + /** Whether [end] has been called. */ + val isEnded: Boolean + get() = ended + + /** Ends the session; idempotent and never blocks. */ + fun end() { + ended = true + } +} diff --git a/lsp/indexing/src/main/kotlin/org/appdevforall/codeonthego/indexing/SQLiteIndex.kt b/lsp/indexing/src/main/kotlin/org/appdevforall/codeonthego/indexing/SQLiteIndex.kt index 0f2eca4146..4004ea57ae 100644 --- a/lsp/indexing/src/main/kotlin/org/appdevforall/codeonthego/indexing/SQLiteIndex.kt +++ b/lsp/indexing/src/main/kotlin/org/appdevforall/codeonthego/indexing/SQLiteIndex.kt @@ -101,6 +101,8 @@ import kotlin.collections.iterator * @param batchSize Number of rows per INSERT transaction. * @param sourceIdChunkSize Max number of `_source_id` placeholders per source-scoped statement. * See [SOURCE_ID_CHUNK_SIZE]. + * @param lifetime The project session owning this index; once it has ended, use after close is + * expected and logged at DEBUG instead of ERROR. */ class SQLiteIndex( override val descriptor: IndexDescriptor, @@ -110,6 +112,7 @@ class SQLiteIndex( override val name: String = "sqlite:${descriptor.name}", private val batchSize: Int = 500, @param:VisibleForTesting internal val sourceIdChunkSize: Int = SOURCE_ID_CHUNK_SIZE, + private val lifetime: IndexSessionLifetime? = null, ) : Index, PackageTree { companion object { @@ -191,6 +194,10 @@ class SQLiteIndex( private val mutex = Mutex() @Volatile private var closed = false + override val isOpen: Boolean + get() = !closed + + private var useAfterCloseReported = false private val db: SupportSQLiteDatabase init { @@ -233,7 +240,7 @@ class SQLiteIndex( override fun query(query: IndexQuery): Sequence = runBlocking { - ifOpen(emptySequence()) { + ifOpen("query", emptySequence()) { val limit = effectiveLimit(query) val results = mutableListOf() for (chunk in sourceIdChunks(query)) { @@ -256,7 +263,7 @@ class SQLiteIndex( override suspend fun get(key: String): T? = withContext(Dispatchers.IO) { - ifOpen(null) { + ifOpen("get", null) { val cursor = db.query( "SELECT _payload FROM $tableName WHERE _key = ? ORDER BY _source_id LIMIT 1", @@ -274,7 +281,7 @@ class SQLiteIndex( override suspend fun containsSource(sourceId: String): Boolean = withContext(Dispatchers.IO) { - ifOpen(false) { + ifOpen("containsSource", false) { val cursor = db.query( "SELECT 1 FROM $tableName WHERE _source_id = ? LIMIT 1", @@ -289,7 +296,7 @@ class SQLiteIndex( query: IndexQuery, ): Sequence = runBlocking { - ifOpen(emptySequence()) { + ifOpen("distinctValues", emptySequence()) { val col = fieldColumns[fieldName] ?: throw IllegalArgumentException("Unknown field: $fieldName") @@ -339,13 +346,13 @@ class SQLiteIndex( fingerprint: String, entries: Flow, ) = withContext(Dispatchers.IO) { - val generation = ifOpen(null) { beginPassLocked(sourceId) } ?: return@withContext + val generation = ifOpen("insertSource", null) { beginPassLocked(sourceId) } ?: return@withContext insertBatched(entries, SourcePass(sourceId, fingerprint, generation)) } override suspend fun sourceFingerprint(sourceId: String): String? = withContext(Dispatchers.IO) { - ifOpen(null) { + ifOpen("sourceFingerprint", null) { db .query( "SELECT _fingerprint FROM $sourcesTableName WHERE _source_id = ?", @@ -356,7 +363,7 @@ class SQLiteIndex( override suspend fun sourceFingerprints(): Map = withContext(Dispatchers.IO) { - ifOpen(emptyMap()) { + ifOpen("sourceFingerprints", emptyMap()) { db.query("SELECT _source_id, _fingerprint FROM $sourcesTableName").use { cursor -> buildMap { while (cursor.moveToNext()) { @@ -372,7 +379,7 @@ class SQLiteIndex( sourceIds: Collection?, ): Set = runBlocking { - ifOpen(emptySet()) { + ifOpen("subpackages", emptySet()) { val names = HashSet() for (chunk in sourceIdChunks(sourceIds)) { val (sql, args) = buildSubpackagesQuery(parent, chunk) @@ -391,7 +398,7 @@ class SQLiteIndex( sourceIds: Collection?, ): Boolean = runBlocking { - ifOpen(false) { + ifOpen("containsPackage", false) { sourceIdChunks(sourceIds).any { chunk -> val (sql, args) = buildContainsPackageQuery(name, chunk) db.query(sql, args.toTypedArray()).use { it.moveToFirst() } @@ -419,19 +426,19 @@ class SQLiteIndex( batch.add(entry) if (batch.size >= batchSize) { ensureActive() - ifOpen { insertBatchLocked(batch, generation, completing = null) } + ifOpen("insert") { insertBatchLocked(batch, generation, completing = null) } batch.clear() } } if (batch.isNotEmpty() || pass != null) { ensureActive() - ifOpen { insertBatchLocked(batch, generation, completing = pass) } + ifOpen("insert") { insertBatchLocked(batch, generation, completing = pass) } } } override suspend fun insert(entry: T) = withContext(Dispatchers.IO) { - ifOpen { insertBatchLocked(listOf(entry), generation = 0L, completing = null) } + ifOpen("insert") { insertBatchLocked(listOf(entry), generation = 0L, completing = null) } } override suspend fun removeBySource(sourceId: String) = removeBySources(listOf(sourceId)) @@ -448,7 +455,7 @@ class SQLiteIndex( override suspend fun removeBySources(sourceIds: Collection) = withContext(Dispatchers.IO) { if (sourceIds.isEmpty()) return@withContext - ifOpen { + ifOpen("removeBySources") { db.beginTransaction() try { for (chunk in sourceIds.chunked(DELETE_CHUNK_SIZE)) { @@ -475,7 +482,7 @@ class SQLiteIndex( override suspend fun clear() = withContext(Dispatchers.IO) { - ifOpen { + ifOpen("clear") { db.beginTransaction() try { db.execSQL("DELETE FROM $tableName") @@ -503,7 +510,7 @@ class SQLiteIndex( */ override suspend fun optimize() = withContext(Dispatchers.IO) { - ifOpen { + ifOpen("optimize") { val version = db.query("SELECT sqlite_version()").use { if (it.moveToFirst()) it.getString(0) else "" } if (!supportsAnalysisLimit(version)) { log.debug("Not analyzing {}: SQLite {} has no analysis limit", tableName, version) @@ -536,15 +543,48 @@ class SQLiteIndex( } private suspend inline fun ifOpen( + operation: String, default: R, crossinline block: () -> R, - ): R = mutex.withLock { if (closed) default else block() } + ): R = + mutex.withLock { + if (closed) { + reportUseAfterClose(operation) + default + } else { + block() + } + } + + private suspend inline fun ifOpen( + operation: String, + crossinline block: () -> Unit, + ) = ifOpen(operation, Unit, block) - private suspend inline fun ifOpen(crossinline block: () -> Unit) = mutex.withLock { if (!closed) block() } + /* + * A closed index answers with empty results, which callers cannot tell from a genuinely empty + * index, so the first such call is logged with its stack to name whoever still holds it. Once the + * owning session has ended its remaining work is expected to hit closed indexes, so that is DEBUG. + * Called under [mutex]. + */ + private fun reportUseAfterClose(operation: String) { + if (useAfterCloseReported) return + useAfterCloseReported = true + if (lifetime?.isEnded == true) { + log.debug("Index '{}' used after its session ended, in {}; returning an empty result", name, operation) + return + } + log.error( + "Index '{}' used after close in {}; returning an empty result", + name, + operation, + IllegalStateException("Use of closed index '$name'"), + ) + } suspend fun size(): Int = withContext(Dispatchers.IO) { - ifOpen(0) { + ifOpen("size", 0) { val cursor = db.query("SELECT COUNT(*) FROM $tableName") cursor.use { if (it.moveToFirst()) it.getInt(0) else 0 } } @@ -937,7 +977,7 @@ class SQLiteIndex( private fun explain(query: SqlQuery): String = runBlocking { - ifOpen("") { + ifOpen("explain", "") { db.query("EXPLAIN QUERY PLAN ${query.sql}", query.args.toTypedArray()).use { cursor -> val detail = cursor.getColumnIndexOrThrow("detail") buildList { while (cursor.moveToNext()) add(cursor.getString(detail)) }.joinToString("\n") diff --git a/lsp/indexing/src/main/kotlin/org/appdevforall/codeonthego/indexing/api/Index.kt b/lsp/indexing/src/main/kotlin/org/appdevforall/codeonthego/indexing/api/Index.kt index d3bbc85a63..a5b48d51de 100644 --- a/lsp/indexing/src/main/kotlin/org/appdevforall/codeonthego/indexing/api/Index.kt +++ b/lsp/indexing/src/main/kotlin/org/appdevforall/codeonthego/indexing/api/Index.kt @@ -147,5 +147,9 @@ interface Index : */ suspend fun optimize() {} + /** Whether the index still serves reads and writes; false once it is closed. */ + val isOpen: Boolean + get() = true + override fun close() {} } diff --git a/lsp/indexing/src/main/kotlin/org/appdevforall/codeonthego/indexing/service/IndexRegistry.kt b/lsp/indexing/src/main/kotlin/org/appdevforall/codeonthego/indexing/service/IndexRegistry.kt index e2639c5cae..1d22dac8d6 100644 --- a/lsp/indexing/src/main/kotlin/org/appdevforall/codeonthego/indexing/service/IndexRegistry.kt +++ b/lsp/indexing/src/main/kotlin/org/appdevforall/codeonthego/indexing/service/IndexRegistry.kt @@ -1,5 +1,6 @@ package org.appdevforall.codeonthego.indexing.service +import org.appdevforall.codeonthego.indexing.IndexSessionLifetime import java.io.Closeable import java.util.concurrent.ConcurrentHashMap @@ -16,49 +17,123 @@ data class IndexKey( /** * Central registry where [IndexingService]s publish their indexes * and consumers (LSPs, etc.) retrieve them. + * + * Once closed, it refuses new indexes and [require] throws [IndexRegistryClosedException], so work + * for an ended project session stops instead of opening indexes nothing would close. */ -class IndexRegistry : Closeable { - +class IndexRegistry( + /** The project session these indexes belong to; ended when that session closes. */ + val lifetime: IndexSessionLifetime = IndexSessionLifetime(), +) : Closeable { private val indexes = ConcurrentHashMap() private val listeners = ConcurrentHashMap Unit>>() + @Volatile + private var closed = false + + /** + * Whether [close] has been called or this registry's session has ended. + * + * The lifetime ends as soon as the manager closes, while [close] runs later in the background, so + * an ended lifetime already counts as closed. + */ + val isClosed: Boolean + get() = closed || lifetime.isEnded + /** * Register an index. Replaces any previously registered index * with the same key. * * If there are listeners waiting for this key, they are notified * immediately. + * + * @throws IndexRegistryClosedException if the registry is closed; [index] is closed first. */ - fun register(key: IndexKey, index: T) { + fun register( + key: IndexKey, + index: T, + ) { + if (isClosed) { + (index as? Closeable)?.close() + throw closedException(key) + } + val old = indexes.put(key.name, index) + if (isClosed) { + // close() may have drained the map before this entry landed; whoever removes it closes it. + if (indexes.remove(key.name, index)) (index as? Closeable)?.close() + throw closedException(key) + } // Close the old index if it's Closeable if (old is Closeable && old !== index) { old.close() } - // Notify listeners + notifyListeners(key, index) + } + + private fun notifyListeners( + key: IndexKey, + index: T, + ) { listeners[key.name]?.forEach { listener -> @Suppress("UNCHECKED_CAST") (listener as (T) -> Unit).invoke(index) } } + /** + * Returns the index registered for [key], registering the one [create] returns if there is none. + * + * Unlike [register], an existing index is kept open and in place, so callers holding it are not + * left with a closed index. [create] runs only when no index is registered, and listeners are + * notified only when it ran. [create] runs inside the registry's map update, so it must not call + * back into this registry. + * + * @throws IndexRegistryClosedException if the registry is closed; [create] is then not called. + */ + fun registerIfAbsent( + key: IndexKey, + create: () -> T, + ): T { + if (isClosed) throw closedException(key) + + var created: T? = null + val index = indexes.computeIfAbsent(key.name) { create().also { created = it } } + if (isClosed) { + // close() may have drained the map before this entry landed; whoever removes it closes it. + if (indexes.remove(key.name, index)) (index as? Closeable)?.close() + throw closedException(key) + } + + created?.let { notifyListeners(key, it) } + + @Suppress("UNCHECKED_CAST") + return index as T + } + /** * Retrieve an index by key. Returns null if not yet registered. */ @Suppress("UNCHECKED_CAST") - fun get(key: IndexKey): T? = - indexes[key.name] as? T + fun get(key: IndexKey): T? = indexes[key.name] as? T /** * Retrieve an index, throwing if not available. + * + * @throws IndexRegistryClosedException if the registry is closed. + * @throws IllegalStateException if the registry is open but nothing is registered for [key]. */ fun require(key: IndexKey): T = - get(key) ?: throw IllegalStateException( - "Index '${key.name}' is not registered. " + - "Has the corresponding IndexingService been initialized?" - ) + get(key) ?: if (isClosed) { + throw closedException(key) + } else { + throw IllegalStateException( + "Index '${key.name}' is not registered. " + + "Has the corresponding IndexingService been initialized?", + ) + } /** * Execute a block if the index is available. @@ -78,9 +153,13 @@ class IndexRegistry : Closeable { * If the index is already registered, the listener is * called immediately. */ - fun onAvailable(key: IndexKey, listener: (T) -> Unit) { + fun onAvailable( + key: IndexKey, + listener: (T) -> Unit, + ) { @Suppress("UNCHECKED_CAST") - listeners.getOrPut(key.name) { mutableListOf() } + listeners + .getOrPut(key.name) { mutableListOf() } .add(listener as (Any) -> Unit) // If already registered, notify immediately @@ -98,8 +177,7 @@ class IndexRegistry : Closeable { /** * Returns true if an index is registered for this key. */ - fun isRegistered(key: IndexKey): Boolean = - indexes.containsKey(key.name) + fun isRegistered(key: IndexKey): Boolean = indexes.containsKey(key.name) /** * Returns all registered keys. @@ -107,13 +185,16 @@ class IndexRegistry : Closeable { fun registeredKeys(): Set = indexes.keys.toSet() /** - * Close and remove all registered indexes. + * Close and remove all registered indexes, and refuse new ones from now on. */ override fun close() { - indexes.values.forEach { index -> - if (index is Closeable) index.close() + closed = true + // Removed one by one so an index a racing registerIfAbsent adds is closed exactly once. + for (name in indexes.keys.toList()) { + (indexes.remove(name) as? Closeable)?.close() } - indexes.clear() listeners.clear() } -} \ No newline at end of file + + private fun closedException(key: IndexKey<*>) = IndexRegistryClosedException("Index registry is closed; cannot provide '${key.name}'") +} diff --git a/lsp/indexing/src/main/kotlin/org/appdevforall/codeonthego/indexing/service/IndexRegistryClosedException.kt b/lsp/indexing/src/main/kotlin/org/appdevforall/codeonthego/indexing/service/IndexRegistryClosedException.kt new file mode 100644 index 0000000000..2d5de12099 --- /dev/null +++ b/lsp/indexing/src/main/kotlin/org/appdevforall/codeonthego/indexing/service/IndexRegistryClosedException.kt @@ -0,0 +1,11 @@ +package org.appdevforall.codeonthego.indexing.service + +/** + * Thrown when an index is requested from, or registered with, an [IndexRegistry] that has been closed. + * + * Its project session has ended, so callers treat it as an expected end of their work rather than + * a failure. + */ +class IndexRegistryClosedException( + message: String, +) : IllegalStateException(message) diff --git a/lsp/indexing/src/main/kotlin/org/appdevforall/codeonthego/indexing/service/IndexingServiceManager.kt b/lsp/indexing/src/main/kotlin/org/appdevforall/codeonthego/indexing/service/IndexingServiceManager.kt index c6dacbd9b9..ee88edaa82 100644 --- a/lsp/indexing/src/main/kotlin/org/appdevforall/codeonthego/indexing/service/IndexingServiceManager.kt +++ b/lsp/indexing/src/main/kotlin/org/appdevforall/codeonthego/indexing/service/IndexingServiceManager.kt @@ -177,6 +177,7 @@ class IndexingServiceManager( */ override fun close() { log.info("Shutting down indexing services") + registry.lifetime.end() // Called from ProjectHandlerActivity.onPause on the main thread, so the // closes (SERVICE_CLOSE_TIMEOUT only bounds cooperative ones; SQLiteIndex and @@ -242,12 +243,21 @@ class IndexingServiceManager( } } - /** Returns false when setup was skipped because the previous close has not finished. */ + /** + * Returns false when setup did not happen, so the next [onProjectSynced] retries it: the previous + * close has not finished, no service is registered yet, or this manager closed meanwhile. + */ private suspend fun initializeServices(): Boolean { if (!awaitPendingClose()) return false - log.info("Initializing {} indexing services", services.size) val allServices = allServices() + if (allServices.isEmpty()) { + // A sync can reach a new manager before its services register; latching here would skip them. + log.info("No indexing services registered yet; initializing on the next sync") + return false + } + log.info("Initializing {} indexing services", allServices.size) + for (service in allServices) { try { service.initialize(registry) @@ -256,6 +266,10 @@ class IndexingServiceManager( service.id, service.providedKeys.joinToString { it.name }, ) + } catch (e: IndexRegistryClosedException) { + // Returning true would set initialized after close() reset it. + log.info("Indexing session closed while initializing '{}'; stopping", service.id) + return false } catch (e: Exception) { log.error("Failed to initialize service: {}", service.id, e) } diff --git a/lsp/indexing/src/main/kotlin/org/appdevforall/codeonthego/indexing/util/BackgroundIndexer.kt b/lsp/indexing/src/main/kotlin/org/appdevforall/codeonthego/indexing/util/BackgroundIndexer.kt index 41e349c1c3..cc1900195c 100644 --- a/lsp/indexing/src/main/kotlin/org/appdevforall/codeonthego/indexing/util/BackgroundIndexer.kt +++ b/lsp/indexing/src/main/kotlin/org/appdevforall/codeonthego/indexing/util/BackgroundIndexer.kt @@ -1,5 +1,6 @@ package org.appdevforall.codeonthego.indexing.util +import dev.mutwakil.androidide.memprof.Memprof import kotlinx.coroutines.CancellationException import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.CoroutineStart @@ -164,12 +165,18 @@ class BackgroundIndexer( progressListener?.onProgress(sourceId, IndexingEvent.Progress(count)) } } - withContext(Dispatchers.IO) { - if (fingerprint != null) { - index.insertSource(sourceId, fingerprint, entries) - } else { - insertInBatches(entries) + // The section's procAllocBytes counts the whole process, and sources index concurrently, + // so each source's figure also holds its neighbours' allocations: an upper bound, not + // this source's share. Duration and entry count are this source's own. + Memprof.section("Index library source", sourceId) { span -> + withContext(Dispatchers.IO) { + if (fingerprint != null) { + index.insertSource(sourceId, fingerprint, entries) + } else { + insertInBatches(entries) + } } + span.put("entries", count.toLong()) } progressListener?.onProgress(sourceId, IndexingEvent.Completed(count)) diff --git a/lsp/jvm-symbol-index/src/main/kotlin/org/appdevforall/codeonthego/indexing/jvm/JarIndexingService.kt b/lsp/jvm-symbol-index/src/main/kotlin/org/appdevforall/codeonthego/indexing/jvm/JarIndexingService.kt index f23d7f295f..e530e09662 100644 --- a/lsp/jvm-symbol-index/src/main/kotlin/org/appdevforall/codeonthego/indexing/jvm/JarIndexingService.kt +++ b/lsp/jvm-symbol-index/src/main/kotlin/org/appdevforall/codeonthego/indexing/jvm/JarIndexingService.kt @@ -15,6 +15,7 @@ import kotlinx.coroutines.flow.catch import kotlinx.coroutines.launch import kotlinx.coroutines.sync.Mutex import kotlinx.coroutines.sync.withLock +import org.appdevforall.codeonthego.indexing.IndexSessionLifetime import org.appdevforall.codeonthego.indexing.service.IndexKey import org.appdevforall.codeonthego.indexing.service.IndexRegistry import org.appdevforall.codeonthego.indexing.service.IndexingProgressTracker @@ -58,7 +59,7 @@ abstract class JarIndexingService( private val workspaceSupplier: () -> Workspace? = { ProjectManagerImpl.getInstance().workspace }, private val unreadableJarReporter: (List) -> Unit = ::reportUnreadableClasspathJars, private val unreadableJarFilter: (Collection) -> List = { it.toList() }, - private val indexFactory: (Context, String, String) -> JvmSymbolIndex = JvmSymbolIndex::createSqliteIndex, + private val indexFactory: (Context, String, String, IndexSessionLifetime?) -> JvmSymbolIndex = JvmSymbolIndex::createSqliteIndex, ) : IndexingService { companion object { private val log = LoggerFactory.getLogger(JarIndexingService::class.java) @@ -90,7 +91,7 @@ abstract class JarIndexingService( ) override suspend fun initialize(registry: IndexRegistry) { - val jvmIndex = indexFactory(context, dbName, indexName) + val jvmIndex = indexFactory(context, dbName, indexName, registry.lifetime) this.jarIndex = jvmIndex registry.register(indexKey, jvmIndex) diff --git a/lsp/jvm-symbol-index/src/main/kotlin/org/appdevforall/codeonthego/indexing/jvm/JvmSymbolIndex.kt b/lsp/jvm-symbol-index/src/main/kotlin/org/appdevforall/codeonthego/indexing/jvm/JvmSymbolIndex.kt index 8673d108bc..0b0061dfc7 100644 --- a/lsp/jvm-symbol-index/src/main/kotlin/org/appdevforall/codeonthego/indexing/jvm/JvmSymbolIndex.kt +++ b/lsp/jvm-symbol-index/src/main/kotlin/org/appdevforall/codeonthego/indexing/jvm/JvmSymbolIndex.kt @@ -6,6 +6,7 @@ import kotlinx.coroutines.Job import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.joinAll import org.appdevforall.codeonthego.indexing.FilteredIndex +import org.appdevforall.codeonthego.indexing.IndexSessionLifetime import org.appdevforall.codeonthego.indexing.SQLiteIndex import org.appdevforall.codeonthego.indexing.api.Index import org.appdevforall.codeonthego.indexing.api.IndexQueryBuilder @@ -69,11 +70,13 @@ open class JvmSymbolIndex( * @param context The context to use for accessing the SQLite database. * @param dbName The name of the database. Defaults to [DB_NAME_DEFAULT]. * @param indexName The name of the index. Defaults to [INDEX_NAME_LIBRARY]. + * @param lifetime The project session owning the index, or null if it has none. */ fun createSqliteIndex( context: Context, dbName: String, indexName: String, + lifetime: IndexSessionLifetime? = null, ): JvmSymbolIndex { val cache = SQLiteIndex( @@ -82,6 +85,7 @@ open class JvmSymbolIndex( dbName = dbName, formatVersion = FORMAT_VERSION, name = indexName, + lifetime = lifetime, ) val indexer = BackgroundIndexer(cache) @@ -323,6 +327,10 @@ open class JvmSymbolIndex( backing.optimize() } + /** Whether the backing index still serves reads and writes. */ + val isOpen: Boolean + get() = backing.isOpen + override fun close() { indexer.close() super.close() diff --git a/lsp/jvm-symbol-index/src/main/kotlin/org/appdevforall/codeonthego/indexing/jvm/KtFileMetadataIndex.kt b/lsp/jvm-symbol-index/src/main/kotlin/org/appdevforall/codeonthego/indexing/jvm/KtFileMetadataIndex.kt index 44e5eed353..4ce5fea8b5 100644 --- a/lsp/jvm-symbol-index/src/main/kotlin/org/appdevforall/codeonthego/indexing/jvm/KtFileMetadataIndex.kt +++ b/lsp/jvm-symbol-index/src/main/kotlin/org/appdevforall/codeonthego/indexing/jvm/KtFileMetadataIndex.kt @@ -1,12 +1,41 @@ package org.appdevforall.codeonthego.indexing.jvm import android.content.Context +import org.appdevforall.codeonthego.indexing.IndexSessionLifetime import org.appdevforall.codeonthego.indexing.SQLiteIndex import org.appdevforall.codeonthego.indexing.api.Index import org.appdevforall.codeonthego.indexing.api.indexQuery import org.appdevforall.codeonthego.indexing.jvm.KtFileMetadataDescriptor.KEY_IS_INDEXED import org.appdevforall.codeonthego.indexing.jvm.KtFileMetadataDescriptor.KEY_PACKAGE import java.io.Closeable +import java.util.concurrent.CopyOnWriteArrayList + +/** + * A completed write to a [KtFileMetadataIndex]. + */ +sealed interface KtFileMetadataWrite { + /** The record for [filePath] was inserted or replaced; its package is [packageFqName]. */ + data class Upserted( + val filePath: String, + val packageFqName: String, + ) : KtFileMetadataWrite + + /** The records for [filePaths] were removed. */ + data class Removed( + val filePaths: Collection, + ) : KtFileMetadataWrite + + /** Every record was removed. */ + data object Cleared : KtFileMetadataWrite +} + +/** + * Receives each [KtFileMetadataWrite] after it has been applied to the index. + */ +fun interface KtFileMetadataWriteListener { + /** Called synchronously on the writing thread once [write] is visible to readers. */ + fun onWrite(write: KtFileMetadataWrite) +} /** * An index of [KtFileMetadata] entries, one per Kotlin source file. @@ -19,11 +48,13 @@ class KtFileMetadataIndex( * Creates a [KtFileMetadataIndex] backed by a SQLite database. * * The [context] is required by the AndroidX SQLite helpers even for in-memory - * databases; it is not used for any file I/O. + * databases; it is not used for any file I/O. [lifetime] is the project session owning the + * index, or null if it has none. */ fun sqliteBacked( context: Context, dbName: String? = null, + lifetime: IndexSessionLifetime? = null, ): KtFileMetadataIndex = KtFileMetadataIndex( SQLiteIndex( @@ -32,24 +63,47 @@ class KtFileMetadataIndex( dbName = dbName, formatVersion = JvmSymbolIndex.FORMAT_VERSION, name = "kt-file-metadata", + lifetime = lifetime, ), ) } + private val listeners = CopyOnWriteArrayList() + + /** + * Registers [listener] to be told about every later write. + * + * Closing the returned handle unregisters it. + */ + fun addWriteListener(listener: KtFileMetadataWriteListener): AutoCloseable { + listeners.add(listener) + return AutoCloseable { listeners.remove(listener) } + } + + private fun notifyListeners(write: KtFileMetadataWrite) { + listeners.forEach { it.onWrite(write) } + } + /** * Insert or replace the metadata record for a single file. * * Because [KtFileMetadata.key] and [KtFileMetadata.sourceId] are both the * file path, a file has at most one row and an insert replaces it. */ - suspend fun upsert(metadata: KtFileMetadata) = backing.insert(metadata) + suspend fun upsert(metadata: KtFileMetadata) { + backing.insert(metadata) + notifyListeners(KtFileMetadataWrite.Upserted(metadata.filePath, metadata.packageFqName)) + } /** * Remove the metadata record for [filePath]. * * No-op if the file is not in the index. */ - suspend fun remove(filePath: String) = backing.removeBySource(filePath) + suspend fun remove(filePath: String) { + backing.removeBySource(filePath) + notifyListeners(KtFileMetadataWrite.Removed(listOf(filePath))) + } /** * Remove the metadata records for every path in [filePaths] as a single @@ -59,7 +113,10 @@ class KtFileMetadataIndex( * transaction instead of N - see [Index.removeBySources]. Paths not present in * the index are ignored. */ - suspend fun removeAll(filePaths: Collection) = backing.removeBySources(filePaths) + suspend fun removeAll(filePaths: Collection) { + backing.removeBySources(filePaths) + notifyListeners(KtFileMetadataWrite.Removed(filePaths)) + } /** * Return the [KtFileMetadata] for [filePath], or `null` if the file is @@ -150,7 +207,14 @@ class KtFileMetadataIndex( ).map { it.filePath } /** Remove all records from the index. */ - suspend fun clear() = backing.clear() + suspend fun clear() { + backing.clear() + notifyListeners(KtFileMetadataWrite.Cleared) + } + + /** Whether the backing index still serves reads and writes. */ + val isOpen: Boolean + get() = backing.isOpen override fun close() = backing.close() } diff --git a/lsp/kotlin/build.gradle.kts b/lsp/kotlin/build.gradle.kts index 91223231dd..7f6e02d797 100644 --- a/lsp/kotlin/build.gradle.kts +++ b/lsp/kotlin/build.gradle.kts @@ -76,6 +76,7 @@ dependencies { exclude(group = "org.ec4j.core", module = "ec4j-core") } implementation(libs.composite.googleJavaFormat) + implementation(libs.composite.javac) implementation(libs.google.guava) compileOnly(projects.core.common) diff --git a/lsp/kotlin/src/main/java/dev/mutwakil/androidide/lsp/kotlin/CompilerSession.kt b/lsp/kotlin/src/main/java/dev/mutwakil/androidide/lsp/kotlin/CompilerSession.kt new file mode 100644 index 0000000000..d797eab529 --- /dev/null +++ b/lsp/kotlin/src/main/java/dev/mutwakil/androidide/lsp/kotlin/CompilerSession.kt @@ -0,0 +1,169 @@ +package dev.mutwakil.androidide.lsp.kotlin + +import dev.mutwakil.androidide.lsp.kotlin.compiler.KotlinModuleLayout +import dev.mutwakil.androidide.projects.api.Workspace +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.CoroutineDispatcher +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.channels.Channel +import kotlinx.coroutines.launch +import org.appdevforall.codeonthego.indexing.service.IndexRegistryClosedException +import org.appdevforall.codeonthego.indexing.service.IndexingServiceManager +import org.slf4j.LoggerFactory + +/** The steps [CompilerSession] runs for each project update, on its own thread. */ +internal interface CompilerLifecycle { + /** Returns the indexing manager of the current project session. */ + fun currentManager(): IndexingServiceManager + + /** Runs on every project update, before its layout is compared. */ + fun prepare( + workspace: Workspace, + manager: IndexingServiceManager, + ) + + /** Returns the module layout of [workspace]. */ + fun layoutOf(workspace: Workspace): KotlinModuleLayout + + /** Waits for the previous compiler to finish closing; returns false if it is still closing. */ + fun awaitClosed(): Boolean + + /** Builds a compiler for [layout] against [manager]'s indexes. */ + fun build( + workspace: Workspace, + layout: KotlinModuleLayout, + manager: IndexingServiceManager, + ): C + + /** Closes [compiler] without blocking the caller. */ + fun close(compiler: C) + + /** Runs after every project update that left [compiler] serving [workspace]. */ + fun onReady( + workspace: Workspace, + compiler: C, + ) +} + +/** + * Keeps one compiler serving the current project, rebuilding it only when the module layout changes. + * + * Project updates (a sync, or `generateSources` after a resource edit) are queued and handled one at + * a time on a single thread; updates that arrive while one is handled collapse into the latest. A + * rebuild closes the old compiler before building the new one, so [current] is null meanwhile. + */ +internal class CompilerSession( + scope: CoroutineScope, + private val lifecycle: CompilerLifecycle, + dispatcher: CoroutineDispatcher = Dispatchers.IO.limitedParallelism(1), +) { + private companion object { + private val logger = LoggerFactory.getLogger(CompilerSession::class.java) + } + + private val updates = Channel(Channel.CONFLATED) + + /** Guards only the swap of [current] against [isShutDown]; never held while building or closing. */ + private val lock = Any() + private var isShutDown = false + + /** Read and written only by the worker. */ + private var currentLayout: KotlinModuleLayout? = null + + /** The compiler serving the project, or null before the first build and during a rebuild. */ + @Volatile + var current: C? = null + private set + + private val worker = + scope.launch(dispatcher) { + for (workspace in updates) { + try { + update(workspace) + } catch (e: CancellationException) { + throw e + } catch (e: Throwable) { + if (e.isProjectClosed()) { + logger.info("Project closed during a Kotlin update; dropping it") + } else { + logger.error("Kotlin project update failed", e) + } + } + } + } + + /** Queues a project update; never blocks. */ + fun submit(workspace: Workspace) { + updates.trySend(workspace) + } + + /** Stops handling updates and closes the current compiler, and any compiler a running build returns. */ + fun shutdown() { + val closing = + synchronized(lock) { + isShutDown = true + current.also { current = null } + } + updates.close() + worker.cancel() + closing?.let(lifecycle::close) + } + + private fun update(workspace: Workspace) { + /* + * prepare opens the source indexes, which a previous project's compiler may still hold open. + * The update cannot be cancelled while it blocks, so shutdown is re-checked after each wait: + * past it, prepare would revive the closed project's indexing state. + * + * The manager is taken once, under the same lock as that check: the editor stops this session + * before it destroys the project, so an update past the check only ever sees the closing + * session's manager, never the next one's. + */ + if (!awaitClosed()) return + val manager = synchronized(lock) { if (isShutDown) null else lifecycle.currentManager() } ?: return + lifecycle.prepare(workspace, manager) + val layout = lifecycle.layoutOf(workspace) + if (isStopped()) return + + val existing = current + if (existing != null && layout == currentLayout) { + logger.info("Kotlin module layout unchanged; keeping the analysis session") + if (!isStopped()) lifecycle.onReady(workspace, existing) + return + } + + detachCurrent() + if (!awaitClosed() || isStopped()) return + + val built = lifecycle.build(workspace, layout, manager) + val published = + synchronized(lock) { + if (!isShutDown) current = built + !isShutDown + } + if (!published) { + lifecycle.close(built) + return + } + + currentLayout = layout + lifecycle.onReady(workspace, built) + } + + private fun isStopped() = synchronized(lock) { isShutDown } + + private fun Throwable.isProjectClosed() = generateSequence(this) { it.cause }.any { it is IndexRegistryClosedException } + + private fun awaitClosed(): Boolean { + if (lifecycle.awaitClosed()) return true + logger.error("Skipping Kotlin setup: the previous compiler is still closing") + return false + } + + private fun detachCurrent() { + currentLayout = null + val old = synchronized(lock) { current.also { current = null } } ?: return + lifecycle.close(old) + } +} diff --git a/lsp/kotlin/src/main/java/dev/mutwakil/androidide/lsp/kotlin/KotlinLanguageServer.kt b/lsp/kotlin/src/main/java/dev/mutwakil/androidide/lsp/kotlin/KotlinLanguageServer.kt index 34bc19825a..ba6a755b10 100644 --- a/lsp/kotlin/src/main/java/dev/mutwakil/androidide/lsp/kotlin/KotlinLanguageServer.kt +++ b/lsp/kotlin/src/main/java/dev/mutwakil/androidide/lsp/kotlin/KotlinLanguageServer.kt @@ -33,10 +33,11 @@ import dev.mutwakil.androidide.lsp.api.ILanguageServer import dev.mutwakil.androidide.lsp.api.IServerSettings import dev.mutwakil.androidide.lsp.kotlin.compiler.CompilationEnvironment import dev.mutwakil.androidide.lsp.kotlin.compiler.Compiler +import dev.mutwakil.androidide.lsp.kotlin.compiler.KotlinModuleLayout import dev.mutwakil.androidide.lsp.kotlin.compiler.KotlinProjectModel +import dev.mutwakil.androidide.lsp.kotlin.compiler.kotlinModuleLayout import dev.mutwakil.androidide.lsp.kotlin.completion.KotlinSnippetRepository import dev.mutwakil.androidide.lsp.kotlin.completion.codeComplete -import dev.mutwakil.androidide.lsp.kotlin.diagnostic.collectDiagnosticsFor import dev.mutwakil.androidide.lsp.kotlin.format.KotlinCodeFormatter import dev.mutwakil.androidide.lsp.kotlin.navigation.findDefinitionAt import dev.mutwakil.androidide.lsp.kotlin.navigation.findUsagesAt @@ -62,7 +63,9 @@ import dev.mutwakil.androidide.tasks.createJobCancelChecker import dev.mutwakil.androidide.utils.DocumentUtils import dev.mutwakil.androidide.utils.Environment import dev.mutwakil.androidide.utils.ifNotEmpty +import dev.mutwakil.androidide.zipfs2.listing.JarListingCache //import io.sentry.Sentry +import kotlinx.coroutines.CoroutineExceptionHandler import kotlinx.coroutines.CoroutineName import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.SupervisorJob @@ -88,19 +91,36 @@ import java.util.concurrent.Executors import java.util.concurrent.Future import java.util.concurrent.TimeUnit import java.util.concurrent.TimeoutException +import kotlin.io.path.extension class KotlinLanguageServer : ILanguageServer { + /** Volatile: read by the session worker when it publishes a compiler, written by [connectClient]. */ + @Volatile private var _client: ILanguageClient? = null private var _settings: IServerSettings? = null - private var initialized = false + /* + * A rebuild can close the compiler a file-event launch is still working on, so a failure there is + * logged, not left to crash the app. + */ private val scope = - CoroutineScope(SupervisorJob() + CoroutineName(KotlinLanguageServer::class.simpleName!!)) - private var projectModel: KotlinProjectModel? = null - private var compiler: Compiler? = null + CoroutineScope( + SupervisorJob() + CoroutineName(KotlinLanguageServer::class.simpleName!!) + + CoroutineExceptionHandler { _, t -> logger.warn("Uncaught exception in Kotlin language server coroutine", t) }, + ) + private val session = CompilerSession(scope, ProjectCompilerLifecycle()) + private val compiler: Compiler? + get() = session.current override val serverId: String = SERVER_ID + /** + * True for `.kt` only. A `.kts` script is served by this language server but compiles to no + * class the debuggee loads, so a breakpoint in one could be drawn and persisted and would then + * never bind. + */ + //override fun supportsDebugging(file: Path): Boolean = file.extension == KOTLIN_SOURCE_EXTENSION + override val client: ILanguageClient? get() = _client @@ -109,12 +129,14 @@ class KotlinLanguageServer : ILanguageServer { companion object { const val SERVER_ID = "ide.lsp.kotlin" + const val KOTLIN_SOURCE_EXTENSION = "kt" private val logger = LoggerFactory.getLogger(KotlinLanguageServer::class.java) - - // Compiler.close() drains its workers with runBlocking and is reached from - // ProjectHandlerActivity.onDestroy on the main thread, so it runs here instead. One - // thread serializes closes; setupWithProject waits so a new compiler never starts - // while the previous one is still disposing. + + /** + * Runs every Compiler.close(), which blocks draining workers and is reached from the editor's + * project teardown in ProjectHandlerActivity.onPause, on the main thread. One thread serializes closes; the next + * build waits so a new compiler never starts while the previous one is still disposing. + */ private val closeExecutor = Executors.newSingleThreadExecutor { Thread(it, "KotlinLspClose").apply { isDaemon = true } } @@ -142,12 +164,23 @@ class KotlinLanguageServer : ILanguageServer { } return true } - + + private fun closeInBackground(compiler: Compiler) { + pendingClose = + closeExecutor.submit { + try { + compiler.close() + } catch (e: Throwable) { + // Throwable: an Error (e.g. "Project is already disposed") left in the Future + // would otherwise be rethrown by every later setup. + logger.error("Failed to close the Kotlin compiler", e) + } + } + } } init { applySettings(KotlinServerSettings.getInstance()) - KotlinSnippetRepository.init() if (!EventBus.getDefault().isRegistered(this)) { EventBus.getDefault().register(this) @@ -156,21 +189,10 @@ class KotlinLanguageServer : ILanguageServer { override fun shutdown() { EventBus.getDefault().unregister(this) + session.shutdown() scope.cancel("LSP is being shut down") - compiler?.let { closing -> - pendingClose = - closeExecutor.submit { - try { - closing.close() - } catch (e: Throwable) { - // Throwable: an Error (e.g. "Project is already disposed") left in the Future - // would otherwise be rethrown by every later setupWithProject. - logger.error("Failed to close the Kotlin compiler", e) - } - } - } - compiler = null - initialized = false + // Drops the VFS handlers too, closing their JAR handles; the registry shuts every server down on project close. + JarListingCache.SHARED.clear() } override fun connectClient(client: ILanguageClient?) { @@ -185,97 +207,97 @@ class KotlinLanguageServer : ILanguageServer { this._settings = settings } + /** Queues a project update; the analysis session is kept or rebuilt off the caller's thread. */ override fun setupWithProject(workspace: Workspace) { - logger.info("setupWithProject called, initialized={}", initialized) - - // Runs on an EventBus background thread. Wait out the previous project's teardown: - // its compiler and the SQLite indexes it registered must be closed before we reopen them. - // If they are still closing, skip setup rather than share them; initialized stays false, - // so the next ProjectInitializedEvent (sync) retries. - if (!awaitPendingClose() || !runBlocking { IndexingServiceManager.awaitPendingClose() }) { - logger.error("Skipping Kotlin setup: the previous project is still closing") - return - } - + logger.info("setupWithProject called") LSPEditorActions.ensureActionsMenuRegistered(KotlinCodeActionsMenu) + session.submit(workspace) + } + + private inner class ProjectCompilerLifecycle : CompilerLifecycle { + override fun currentManager() = ProjectManagerImpl.getInstance().indexingServiceManager - val context = BaseApplication.baseInstance - val indexingServiceManager = - ProjectManagerImpl - .getInstance() - .indexingServiceManager + override fun prepare( + workspace: Workspace, + manager: IndexingServiceManager, + ) { + val context = BaseApplication.baseInstance + val indexingRegistry = manager.registry - val indexingRegistry = indexingServiceManager.registry - indexingRegistry.register( - key = KT_SOURCE_FILE_INDEX_KEY, - index = + // Once per project: replacing them would close the instances a live session reads. + indexingRegistry.registerIfAbsent(KT_SOURCE_FILE_INDEX_KEY) { JvmSymbolIndex.createSqliteIndex( context = context, dbName = KT_SOURCE_FILE_INDEX_KEY.name, indexName = KT_SOURCE_FILE_INDEX_KEY.name, - ), - ) - - indexingRegistry.register( - key = KT_SOURCE_FILE_META_INDEX_KEY, - index = + lifetime = indexingRegistry.lifetime, + ) + } + indexingRegistry.registerIfAbsent(KT_SOURCE_FILE_META_INDEX_KEY) { KtFileMetadataIndex.sqliteBacked( context = context, dbName = KT_SOURCE_FILE_META_INDEX_KEY.name, - ), - ) - - val jvmLibraryIndexingService = - indexingServiceManager.getService(JvmLibraryIndexingService.ID) as? JvmLibraryIndexingService? - - jvmLibraryIndexingService?.refresh() - - val jdkHome = Environment.JAVA_HOME.toPath() - val jdkRelease = IJdkDistributionProvider.DEFAULT_JAVA_RELEASE - val intellijPluginRoot = Paths.get(context.applicationInfo.sourceDir) - - val jvmTarget = - JvmTarget.fromString(IJdkDistributionProvider.DEFAULT_JAVA_VERSION) - ?: JvmTarget.JVM_21 - - val jvmPlatform = JvmPlatforms.jvmPlatformByTargetVersion(jvmTarget) + lifetime = indexingRegistry.lifetime, + ) + } - if (!initialized) { - logger.info("Creating initial analysis session") + val jvmLibraryIndexingService = + manager.getService(JvmLibraryIndexingService.ID) as? JvmLibraryIndexingService? + jvmLibraryIndexingService?.refresh() + } - val model = KotlinProjectModel() - model.update(workspace, jvmPlatform) - this.projectModel = model + override fun layoutOf(workspace: Workspace) = workspace.kotlinModuleLayout() + + /* + * The previous compiler, and on a project switch the previous project's SQLite indexes, must be + * closed before a new compiler opens them. + */ + override fun awaitClosed() = awaitPendingClose() && runBlocking { IndexingServiceManager.awaitPendingClose() } + + override fun build( + workspace: Workspace, + layout: KotlinModuleLayout, + manager: IndexingServiceManager, + ): Compiler { + logger.info("Creating analysis session") + + val jvmTarget = + JvmTarget.fromString(IJdkDistributionProvider.DEFAULT_JAVA_VERSION) + ?: JvmTarget.JVM_21 + + val model = KotlinProjectModel(manager.registry) + model.update(workspace, JvmPlatforms.jvmPlatformByTargetVersion(jvmTarget)) + + return Compiler( + layout = layout, + projectModel = model, + intellijPluginRoot = Paths.get(BaseApplication.baseInstance.applicationInfo.sourceDir), + jdkHome = Environment.JAVA_HOME.toPath(), + jdkRelease = IJdkDistributionProvider.DEFAULT_JAVA_RELEASE, + languageVersion = LanguageVersion.LATEST_STABLE, + ) + } - val compiler = - Compiler( - workspace = workspace, - projectModel = model, - intellijPluginRoot = intellijPluginRoot, - jdkHome = jdkHome, - jdkRelease = jdkRelease, - languageVersion = LanguageVersion.LATEST_STABLE, - ) + override fun close(compiler: Compiler) = closeInBackground(compiler) + override fun onReady( + workspace: Workspace, + compiler: Compiler, + ) { compiler.updateLanguageClient(client) - this.compiler = compiler - } else { - logger.info("Updating project model") - projectModel?.update(workspace, jvmPlatform) - } - // Open already open files - // we won't get an event for these - FileManager.activeDocuments.ifNotEmpty { - forEach { document -> - compiler - ?.compilationEnvironmentFor(document.file) - ?.openFileIfNeeded(document.file) + // Already open files get no open event. + FileManager.activeDocuments.ifNotEmpty { + forEach { document -> + compiler + .compilationEnvironmentFor(document.file) + ?.openFileIfNeeded(document.file) + } } - } - initialized = true - logger.info("Kotlin project initialized") + KotlinSnippetRepository.init() + logger.info("Kotlin project initialized") + } } override fun complete(params: CompletionParams?): CompletionResult { @@ -360,9 +382,14 @@ class KotlinLanguageServer : ILanguageServer { return DiagnosticResult.NO_UPDATE } + // Outside the selected variant: clear what an earlier variant reported, analyze nothing. + if (ProjectManagerImpl.getInstance().workspace?.isOutsideSelectedVariant(file) == true) { + return DiagnosticResult(file, ArrayList()) + } + return compiler - ?.compilationEnvironmentFor(file) - ?.let { context(it) { collectDiagnosticsFor(file, createJobCancelChecker()) } } + ?.compilationEnvironmentForKotlinPath(file) + ?.diagnosticsFor(file, createJobCancelChecker()) ?: DiagnosticResult.NO_UPDATE } @@ -417,7 +444,7 @@ class KotlinLanguageServer : ILanguageServer { @Subscribe @Suppress("unused") fun onBuildCompleted(event: BuildCompletedEvent) { -// Sentry.addBreadcrumb("onBuildCompleted: result=${event.result}") + //Sentry.addBreadcrumb("onBuildCompleted: result=${event.result}") compiler?.refreshSources() } @@ -455,12 +482,13 @@ class KotlinLanguageServer : ILanguageServer { @Suppress("unused") fun onFileDeleted(event: FileDeletionEvent) { val path = event.file.toPath() - if (!DocumentUtils.isKotlinFile(path)) { + // The file is already gone, so only its extension can say it was Kotlin. + if (!DocumentUtils.hasKotlinExtension(path)) { return } scope.launch { - runCatching { compiler?.compilationEnvironmentFor(path) } + runCatching { compiler?.compilationEnvironmentForKotlinPath(path) } .getOrNull() ?.onFileRemoved(path) } @@ -473,14 +501,17 @@ class KotlinLanguageServer : ILanguageServer { val toPath = event.newFile.toPath() scope.launch { - val oldIsKotlinFile = DocumentUtils.isKotlinFile(fromPath) + // One read: a rebuild can swap the compiler between two reads of the property. + val compiler = compiler ?: return@launch + // The old path no longer exists, so only its extension can say it was Kotlin. + val oldIsKotlinFile = DocumentUtils.hasKotlinExtension(fromPath) val newIsKotlinFile = DocumentUtils.isKotlinFile(toPath) if (!oldIsKotlinFile && newIsKotlinFile) { // only the new file is a Kotlin file // so just submit it for indexing compiler - ?.compilationEnvironmentFor(toPath) + .compilationEnvironmentFor(toPath) ?.onFileCreated(toPath) return@launch } @@ -489,17 +520,16 @@ class KotlinLanguageServer : ILanguageServer { // only the old file was a Kotlin file // so just remove it from the index compiler - ?.compilationEnvironmentFor(fromPath) + .compilationEnvironmentForKotlinPath(fromPath) ?.onFileRemoved(fromPath) return@launch } - val fromKind = runCatching { compiler?.compilationKindFor(fromPath) }.getOrNull() - val toKind = runCatching { compiler?.compilationKindFor(toPath) }.getOrNull() - val fromEnv = fromKind?.let { compiler?.compilationEnvironmentFor(it) } - val toEnv = toKind?.let { compiler?.compilationEnvironmentFor(it) } + // Path-based, so a .kts side yields no environment instead of the kind-based overload's throw. + val fromEnv = runCatching { compiler.compilationEnvironmentForKotlinPath(fromPath) }.getOrNull() + val toEnv = runCatching { compiler.compilationEnvironmentForKotlinPath(toPath) }.getOrNull() - if (fromKind != null && fromEnv == toEnv && toEnv != null) { + if (fromEnv != null && fromEnv == toEnv) { // file was renamed within the same compilation environment toEnv.onFileMoved(fromPath, toPath) return@launch diff --git a/lsp/kotlin/src/main/java/dev/mutwakil/androidide/lsp/kotlin/compiler/AbstractCompilationEnvironment.kt b/lsp/kotlin/src/main/java/dev/mutwakil/androidide/lsp/kotlin/compiler/AbstractCompilationEnvironment.kt index 1a03f8b31d..b6a444e0bf 100644 --- a/lsp/kotlin/src/main/java/dev/mutwakil/androidide/lsp/kotlin/compiler/AbstractCompilationEnvironment.kt +++ b/lsp/kotlin/src/main/java/dev/mutwakil/androidide/lsp/kotlin/compiler/AbstractCompilationEnvironment.kt @@ -1,23 +1,39 @@ package dev.mutwakil.androidide.lsp.kotlin.compiler import dev.mutwakil.androidide.lsp.kotlin.compiler.index.KtSymbolIndex +import dev.mutwakil.androidide.lsp.kotlin.compiler.modules.AbstractKtModule +import dev.mutwakil.androidide.lsp.kotlin.compiler.modules.AnalysisPriority +import dev.mutwakil.androidide.lsp.kotlin.compiler.modules.AnalysisScheduler import dev.mutwakil.androidide.lsp.kotlin.compiler.modules.KtModule import dev.mutwakil.androidide.lsp.kotlin.compiler.modules.asFlatSequence import dev.mutwakil.androidide.lsp.kotlin.compiler.modules.isSourceModule import dev.mutwakil.androidide.lsp.kotlin.compiler.services.JavaModuleAccessibilityChecker import dev.mutwakil.androidide.lsp.kotlin.compiler.services.JavaModuleAnnotationsProvider import dev.mutwakil.androidide.lsp.kotlin.compiler.services.KtLspService +import dev.mutwakil.androidide.lsp.kotlin.compiler.services.ProjectStructureProvider +import dev.mutwakil.androidide.lsp.kotlin.compiler.services.ResolutionScopeProvider import dev.mutwakil.androidide.lsp.kotlin.compiler.services.WriteAccessGuard import dev.mutwakil.androidide.lsp.kotlin.compiler.services.latestLanguageVersionSettings import dev.mutwakil.androidide.lsp.kotlin.compiler.util.SLF4JLogger +import dev.mutwakil.androidide.lsp.kotlin.utils.SymbolVisibilityChecker +import dev.mutwakil.androidide.lsp.kotlin.utils.toVirtualFileOrNull +import dev.mutwakil.androidide.progress.ICancelChecker import kotlinx.coroutines.runBlocking import kotlinx.coroutines.withTimeoutOrNull +import org.appdevforall.codeonthego.indexing.jvm.JvmSymbolIndex import org.jetbrains.kotlin.K1Deprecation +import org.jetbrains.kotlin.analysis.api.KaImplementationDetail +import org.jetbrains.kotlin.analysis.api.platform.analysisMessageBus import org.jetbrains.kotlin.analysis.api.platform.declarations.KotlinAnnotationsResolverFactory import org.jetbrains.kotlin.analysis.api.platform.declarations.KotlinDeclarationProviderFactory import org.jetbrains.kotlin.analysis.api.platform.declarations.KotlinDirectInheritorsProvider import org.jetbrains.kotlin.analysis.api.platform.java.KotlinJavaModuleAccessibilityChecker import org.jetbrains.kotlin.analysis.api.platform.java.KotlinJavaModuleAnnotationsProvider +import org.jetbrains.kotlin.analysis.api.platform.modification.KaElementModificationType +import org.jetbrains.kotlin.analysis.api.platform.modification.KaSourceModificationService +import org.jetbrains.kotlin.analysis.api.platform.modification.KotlinModuleStateModificationEvent +import org.jetbrains.kotlin.analysis.api.platform.modification.KotlinModuleStateModificationKind +import org.jetbrains.kotlin.analysis.api.platform.modification.publishModificationEvent import org.jetbrains.kotlin.analysis.api.platform.packages.KotlinPackagePartProviderFactory import org.jetbrains.kotlin.analysis.api.platform.packages.KotlinPackageProviderFactory import org.jetbrains.kotlin.analysis.api.platform.projectStructure.KotlinModuleDependentsProvider @@ -28,6 +44,7 @@ import org.jetbrains.kotlin.analysis.api.standalone.base.projectStructure.Standa import org.jetbrains.kotlin.analysis.api.standalone.base.projectStructure.registerProjectExtensionPoints import org.jetbrains.kotlin.analysis.api.standalone.base.projectStructure.registerProjectModelServices import org.jetbrains.kotlin.analysis.api.standalone.base.projectStructure.registerProjectServices +import org.jetbrains.kotlin.analysis.low.level.api.fir.sessions.LLFirSessionInvalidationTopics import org.jetbrains.kotlin.cli.common.intellijPluginRoot import org.jetbrains.kotlin.cli.common.messages.CompilerMessageSeverity import org.jetbrains.kotlin.cli.common.messages.CompilerMessageSourceLocation @@ -77,7 +94,9 @@ import org.jetbrains.kotlin.config.useFir import org.jetbrains.kotlin.load.kotlin.MetadataFinderFactory import org.jetbrains.kotlin.load.kotlin.VirtualFileFinderFactory import org.jetbrains.kotlin.metadata.jvm.deserialization.JvmProtoBufUtil +import org.jetbrains.kotlin.psi.KtFile import org.jetbrains.kotlin.psi.KtPsiFactory +import org.slf4j.LoggerFactory import java.nio.file.Path import kotlin.io.path.pathString import kotlin.time.Duration.Companion.seconds @@ -102,6 +121,12 @@ internal abstract class AbstractCompilationEnvironment( /** Max time close() will block the (main) thread draining background workers before disposal. */ val CLOSE_DRAIN_TIMEOUT = 2.seconds + /** Max time close() waits for analyses and project reads to finish before disposing anyway. */ + private val DISPOSE_WAIT = 10.seconds + private const val DISPOSE_RETRY_MILLIS = 10L + + private val logger = LoggerFactory.getLogger(AbstractCompilationEnvironment::class.java) + init { System.setProperty("java.awt.headless", "true") setupIdeaStandaloneExecution() @@ -128,6 +153,13 @@ internal abstract class AbstractCompilationEnvironment( val psiManager: PsiManager get() = PsiManager.getInstance(project) + val symbolVisibilityChecker: SymbolVisibilityChecker by lazy { + SymbolVisibilityChecker(ProjectStructureProvider.getInstance(project)) + } + + /** The indexes completion searches for symbols to offer with an import, in that order: source first. */ + abstract val unimportedSymbolIndexes: List + protected abstract fun createServiceRegistrars(): List /** @@ -184,19 +216,20 @@ internal abstract class AbstractCompilationEnvironment( ) -> KtSymbolIndex, ) { val configuration = createCompilerConfiguration() + // The factory is read when the application environment is created, inside createProjectEnvironment. + KotlinApplicationEnvironmentPin.useListingJarFileSystem() projectEnv = StandaloneProjectFactory.createProjectEnvironment( projectDisposable = disposable, applicationEnvironmentMode = applicationEnvironmentMode, compilerConfiguration = configuration, ) + project.registerRWLock() if (applicationEnvironmentMode == KotlinCoreApplicationEnvironmentMode.Production) { KotlinApplicationEnvironmentPin.ensure(configuration) } - project.registerRWLock() - val serviceRegistrars = createServiceRegistrars() ApplicationServiceRegistration.registerWithCustomRegistration( application, @@ -330,6 +363,72 @@ internal abstract class AbstractCompilationEnvironment( postInit(libraryRoots) } + suspend fun onFileCreated(path: Path) { + if (project.isDisposed) return + notifyElementModifiedForPath(path) { KaElementModificationType.ElementAdded } + ktSymbolIndex.submitForIndexing(path) + } + + suspend fun onFileRemoved(path: Path) { + if (project.isDisposed) return + notifyElementModifiedForPath(path) { ktFile -> + KaElementModificationType.ElementRemoved(ktFile) + } + ProjectStructureProvider.getInstance(project).unregisterInMemoryFile(path.pathString) + ktSymbolIndex.removeFromIndex(path) + } + + @OptIn(KaImplementationDetail::class) + protected inline fun notifyElementModifiedForPath( + path: Path, + crossinline typeProvider: (KtFile) -> KaElementModificationType, + ) { + // Resolve PSI/module structure under the read lock; driving psiManager.findFile / + // structureProvider concurrently with an `analyze` read section otherwise races. + val (ktFile, module) = + project.readUnlessDisposed { + val structureProvider = ProjectStructureProvider.getInstance(project) + val ktFile = + path.toVirtualFileOrNull()?.let { + psiManager.findFile(it) as? KtFile + } + + val module = + ( + ktFile?.let { structureProvider.getModule(it, null) } + ?: structureProvider.findModuleForSourceId(path.pathString) + ) as? AbstractKtModule + + ktFile to module + } ?: return + + project.writeUnlessDisposed { + // Must run under the write lock so the session mutation can't race a concurrent + // `analyze` (which only holds the read lock); see KtSymbolIndex.refreshToCurrent. + if (ktFile != null) { + KaSourceModificationService + .getInstance(project) + .handleElementModification(ktFile, typeProvider(ktFile)) + } + + // A path in no module is in no session's scope; invalidating globally would only force + // the platform and library sessions to rebuild. + if (module != null) { + module.invalidateSearchScope() + project.publishModificationEvent( + KotlinModuleStateModificationEvent( + module, + KotlinModuleStateModificationKind.UPDATE, + ), + ) + project.analysisMessageBus + .syncPublisher(LLFirSessionInvalidationTopics.SESSION_INVALIDATION) + .afterInvalidation(setOf(module)) + ResolutionScopeProvider.getInstance(project).invalidate(module) + } + } + } + private fun createCompilerConfiguration(): CompilerConfiguration = CompilerConfiguration().apply { this.moduleName = JvmProtoBufUtil.DEFAULT_MODULE_NAME @@ -352,13 +451,43 @@ internal abstract class AbstractCompilationEnvironment( // Stop and join the background index workers *before* the project is disposed. // Otherwise IndexWorker's coroutine keeps calling PsiManager.findFile(project) on a // disposed project and crashes with "AssertionError: Project is already disposed" - // (Sentry APPDEVFORALL-17R / ADFA-4384). close() runs on the main thread during editor - // teardown, so the join is bounded by a timeout to avoid an ANR if a read is slow; the - // project.isDisposed guards cover the rare case where the timeout fires before draining. + // (Sentry APPDEVFORALL-17R / ADFA-4384). KotlinLanguageServer.shutdown() runs this off the + // main thread; the join is still bounded so a slow read cannot stall the next project's + // setup, and the project.isDisposed guards cover the timeout firing before draining. if (::ktSymbolIndex.isInitialized) { runBlocking { withTimeoutOrNull(CLOSE_DRAIN_TIMEOUT) { ktSymbolIndex.close() } } } - Disposer.dispose(disposable) + if (!::projectEnv.isInitialized) { + Disposer.dispose(disposable) + return + } + + disposeWhenIdle() + } + + /* + * A rebuild disposes a compiler while the editor is live, so wait for analyses and project reads in + * flight. Both locks are needed and must never be waited on while holding the other: an analysis + * takes project.read under the analysis lock, and indexing takes the analysis lock under + * project.read. Hence the analysis lock is taken, the write lock only tried, and both dropped on a + * miss. Past [DISPOSE_WAIT] it disposes anyway, as it did before this wait existed. + */ + private fun disposeWhenIdle() { + val deadline = System.nanoTime() + DISPOSE_WAIT.inWholeNanoseconds + while (true) { + val disposed = + AnalysisScheduler.withLock(AnalysisPriority.INTERACTIVE, ICancelChecker.NOOP, onPreempt = {}) { + project.tryWrite { Disposer.dispose(disposable) } + } + if (disposed) return + + if (System.nanoTime() > deadline) { + logger.warn("Disposing '{}' while project reads are still running after {}", name, DISPOSE_WAIT) + Disposer.dispose(disposable) + return + } + Thread.sleep(DISPOSE_RETRY_MILLIS) + } } } diff --git a/lsp/kotlin/src/main/java/dev/mutwakil/androidide/lsp/kotlin/compiler/CompilationEnvironment.kt b/lsp/kotlin/src/main/java/dev/mutwakil/androidide/lsp/kotlin/compiler/CompilationEnvironment.kt index 58e4ae856f..f4163f9a5f 100644 --- a/lsp/kotlin/src/main/java/dev/mutwakil/androidide/lsp/kotlin/compiler/CompilationEnvironment.kt +++ b/lsp/kotlin/src/main/java/dev/mutwakil/androidide/lsp/kotlin/compiler/CompilationEnvironment.kt @@ -9,13 +9,12 @@ import dev.mutwakil.androidide.lsp.kotlin.compiler.modules.asFlatSequence import dev.mutwakil.androidide.lsp.kotlin.compiler.modules.backingFilePath import dev.mutwakil.androidide.lsp.kotlin.compiler.registrar.AnalysisApiServiceProviders import dev.mutwakil.androidide.lsp.kotlin.compiler.registrar.LspAnalysisApiServiceRegistrar -import dev.mutwakil.androidide.lsp.kotlin.compiler.services.ProjectStructureProvider import dev.mutwakil.androidide.lsp.kotlin.compiler.services.ResolutionScopeProvider +import dev.mutwakil.androidide.lsp.kotlin.diagnostic.DiagnosticsOutcome import dev.mutwakil.androidide.lsp.kotlin.diagnostic.collectDiagnosticsFor -import dev.mutwakil.androidide.lsp.kotlin.utils.SymbolVisibilityChecker -import dev.mutwakil.androidide.lsp.kotlin.utils.toVirtualFileOrNull +import dev.mutwakil.androidide.lsp.models.DiagnosticResult +import dev.mutwakil.androidide.progress.ICancelChecker import dev.mutwakil.androidide.projects.FileManager -import dev.mutwakil.androidide.projects.api.Workspace import dev.mutwakil.androidide.utils.KeyedDebouncingAction //import io.sentry.Sentry import kotlinx.coroutines.CancellationException @@ -29,16 +28,13 @@ import kotlinx.coroutines.cancelAndJoin import kotlinx.coroutines.runBlocking import kotlinx.coroutines.withContext import kotlinx.coroutines.withTimeoutOrNull +import org.appdevforall.codeonthego.indexing.jvm.JVM_LIBRARY_SYMBOL_INDEX import org.appdevforall.codeonthego.indexing.jvm.JvmSymbolIndex +import org.appdevforall.codeonthego.indexing.jvm.KT_SOURCE_FILE_INDEX_KEY +import org.appdevforall.codeonthego.indexing.jvm.KT_SOURCE_FILE_META_INDEX_KEY import org.appdevforall.codeonthego.indexing.jvm.KtFileMetadataIndex import org.jetbrains.kotlin.analysis.api.KaImplementationDetail -import org.jetbrains.kotlin.analysis.api.platform.analysisMessageBus import org.jetbrains.kotlin.analysis.api.platform.modification.KaElementModificationType -import org.jetbrains.kotlin.analysis.api.platform.modification.KaSourceModificationService -import org.jetbrains.kotlin.analysis.api.platform.modification.KotlinModuleStateModificationEvent -import org.jetbrains.kotlin.analysis.api.platform.modification.KotlinModuleStateModificationKind -import org.jetbrains.kotlin.analysis.api.platform.modification.publishModificationEvent -import org.jetbrains.kotlin.analysis.low.level.api.fir.sessions.LLFirSessionInvalidationTopics import org.jetbrains.kotlin.cli.common.messages.CompilerMessageSeverity import org.jetbrains.kotlin.cli.common.messages.CompilerMessageSourceLocation import org.jetbrains.kotlin.cli.common.messages.MessageCollector @@ -48,10 +44,8 @@ import org.jetbrains.kotlin.cli.jvm.index.JavaRoot import org.jetbrains.kotlin.com.intellij.mock.MockProject import org.jetbrains.kotlin.com.intellij.openapi.vfs.VirtualFileManager import org.jetbrains.kotlin.config.LanguageVersion -import org.jetbrains.kotlin.psi.KtFile import org.slf4j.LoggerFactory import java.nio.file.Path -import kotlin.io.path.pathString import kotlin.time.Duration.Companion.milliseconds /** @@ -65,7 +59,7 @@ import kotlin.time.Duration.Companion.milliseconds internal class CompilationEnvironment( name: String, kind: CompilationKind, - private val workspace: Workspace, + private val layout: KotlinModuleLayout, val ktProject: KotlinProjectModel, intellijPluginRoot: Path, jdkHome: Path, @@ -112,26 +106,27 @@ internal class CompilationEnvironment( get() = ktProject.libraryIndex val requireLibraryIndex: JvmSymbolIndex - get() = checkNotNull(libraryIndex) + get() = ktProject.requireIndex(JVM_LIBRARY_SYMBOL_INDEX) val sourceIndex: JvmSymbolIndex? get() = ktProject.sourceIndex val requireSourceIndex: JvmSymbolIndex - get() = checkNotNull(sourceIndex) + get() = ktProject.requireIndex(KT_SOURCE_FILE_INDEX_KEY) val fileIndex: KtFileMetadataIndex? get() = ktProject.fileIndex val requireFileIndex: KtFileMetadataIndex - get() = checkNotNull(fileIndex) + get() = ktProject.requireIndex(KT_SOURCE_FILE_META_INDEX_KEY) val generatedIndex: JvmSymbolIndex? get() = ktProject.generatedIndex - val symbolVisibilityChecker: SymbolVisibilityChecker by lazy { - SymbolVisibilityChecker(ProjectStructureProvider.getInstance(project)) - } + // Source first, library last: one shared cap across the indexes means whichever is queried last + // loses when the cap binds, and a project symbol is likelier to be the one being reached for. + override val unimportedSymbolIndexes: List + get() = listOfNotNull(sourceIndex, generatedIndex, libraryIndex) var languageClient: ILanguageClient? get() = _languageClient @@ -140,7 +135,21 @@ internal class CompilationEnvironment( } init { - initialize(::buildModules, ::buildKtSymbolIndex) + try { + initialize(::buildModules, ::buildKtSymbolIndex) + } catch (failure: Throwable) { + releaseAfterFailedInit(failure) + throw failure + } + } + + /* + * A throwing constructor never hands this instance to anyone who would close it, so the project + * environment initialize() already created would leak. super.close() rather than close(): the + * fields this class declares after its init block are still unset. + */ + private fun releaseAfterFailedInit(failure: Throwable) { + runCatching { super.close() }.exceptionOrNull()?.let(failure::addSuppressed) } @OptIn(KaImplementationDetail::class) @@ -161,7 +170,7 @@ internal class CompilationEnvironment( private fun buildModules( project: MockProject, applicationEnv: KotlinCoreApplicationEnvironment, - ): List = workspace.collectKtModules(project, applicationEnv) + ): List = layout.toKtModules(project, applicationEnv) override fun createServiceRegistrars() = listOf(LspAnalysisApiServiceRegistrar(AnalysisApiServiceProviders.Production)) @@ -191,7 +200,7 @@ internal class CompilationEnvironment( debounceDuration = DEFAULT_FILE_MOD_EVENT_DEBOUNCE_DURATION, ) { path, cancelChecker -> try { - val result = collectDiagnosticsFor(path, cancelChecker) + val result = diagnosticsFor(path, cancelChecker) withContext(Dispatchers.Main.immediate) { languageClient?.publishDiagnostics(result) } @@ -213,10 +222,36 @@ internal class CompilationEnvironment( } } + /** The diagnostics of [path]; a run the document superseded is scheduled again and reports nothing. */ + fun diagnosticsFor( + path: Path, + cancelChecker: ICancelChecker, + ): DiagnosticResult = + when (val outcome = collectDiagnosticsFor(path, cancelChecker)) { + is DiagnosticsOutcome.Collected -> { + outcome.result + } + + DiagnosticsOutcome.Superseded -> { + /* + * On the debounced path this is a self-send: this runs as fileAnalyzer's own action, so the + * send reads to the worker as a newer key and cancels the run it came from. Deliberate - the + * reschedule still lands, and the only casualty is the NO_UPDATE publish, which had nothing + * to say anyway. Reached from KotlinLanguageServer.analyze() instead, it is a plain reschedule. + */ + fileAnalyzer.schedule(path) + DiagnosticResult.NO_UPDATE + } + + DiagnosticsOutcome.Unavailable -> { + DiagnosticResult.NO_UPDATE + } + } + fun refreshSources() { -// Sentry.addBreadcrumb("refreshSources (env=$name, modules=${modules.size})") - project.write { -// Sentry.addBreadcrumb("refreshSources(env=$name): in-progress") + //Sentry.addBreadcrumb("refreshSources (env=$name, modules=${modules.size})") + project.writeUnlessDisposed { + //Sentry.addBreadcrumb("refreshSources(env=$name): in-progress") ResolutionScopeProvider.getInstance(project).invalidateAll() modules .asFlatSequence() @@ -244,89 +279,23 @@ internal class CompilationEnvironment( ktSymbolIndex.invalidateCurrent(path) } - @OptIn(KaImplementationDetail::class) - private inline fun notifyElementModifiedForPath( - path: Path, - crossinline typeProvider: (KtFile) -> KaElementModificationType, - ) { - // Resolve PSI/module structure under the read lock; driving psiManager.findFile / - // structureProvider concurrently with an `analyze` read section otherwise races. - val (ktFile, module) = - project.read { - val structureProvider = ProjectStructureProvider.getInstance(project) - val ktFile = - path.toVirtualFileOrNull()?.let { - psiManager.findFile(it) as? KtFile - } - - val module = - ( - ktFile?.let { structureProvider.getModule(it, null) } - ?: structureProvider.findModuleForSourceId(path.pathString) - ) as? AbstractKtModule - - ktFile to module - } - - project.write { - // Must run under the write lock so the session mutation can't race a concurrent - // `analyze` (which only holds the read lock); see KtSymbolIndex.refreshToCurrent. - if (ktFile != null) { - KaSourceModificationService - .getInstance(project) - .handleElementModification(ktFile, typeProvider(ktFile)) - } - - if (module != null) { - module.invalidateSearchScope() - project.publishModificationEvent( - KotlinModuleStateModificationEvent( - module, - KotlinModuleStateModificationKind.UPDATE, - ), - ) - project.analysisMessageBus - .syncPublisher(LLFirSessionInvalidationTopics.SESSION_INVALIDATION) - .afterInvalidation(setOf(module)) - ResolutionScopeProvider.getInstance(project).invalidate(module) - } else { - project.analysisMessageBus - .syncPublisher(LLFirSessionInvalidationTopics.SESSION_INVALIDATION) - .afterGlobalInvalidation() - ResolutionScopeProvider.getInstance(project).invalidateAll() - } - } - } - suspend fun onFileChangedOnDisk(path: Path) { - if (FileManager.isActive(path)) return + if (project.isDisposed || FileManager.isActive(path)) return ktSymbolIndex.evictDiskCopy(path) notifyElementModifiedForPath(path) { KaElementModificationType.Unknown } ktSymbolIndex.submitForIndexing(path) } - suspend fun onFileCreated(path: Path) { - notifyElementModifiedForPath(path) { KaElementModificationType.ElementAdded } - ktSymbolIndex.submitForIndexing(path) - } - - suspend fun onFileRemoved(path: Path) { - notifyElementModifiedForPath(path) { ktFile -> - KaElementModificationType.ElementRemoved(ktFile) - } - ProjectStructureProvider.getInstance(project).unregisterInMemoryFile(path.pathString) - ktSymbolIndex.removeFromIndex(path) - } - suspend fun onFileMoved( fromPath: Path, toPath: Path, ) { - val isFileOpen = FileManager.isActive(fromPath) onFileRemoved(fromPath) onFileCreated(toPath) - if (isFileOpen) { - ktSymbolIndex.invalidateCurrent(fromPath) + // The IDE moves an open document to its new path before posting the rename, so fromPath is + // never active here; drop its in-memory copy unconditionally and ask about toPath instead. + ktSymbolIndex.invalidateCurrent(fromPath) + if (FileManager.isActive(toPath)) { onFileOpen(toPath) } } diff --git a/lsp/kotlin/src/main/java/dev/mutwakil/androidide/lsp/kotlin/compiler/Compiler.kt b/lsp/kotlin/src/main/java/dev/mutwakil/androidide/lsp/kotlin/compiler/Compiler.kt index 296cdcc98f..8814330862 100644 --- a/lsp/kotlin/src/main/java/dev/mutwakil/androidide/lsp/kotlin/compiler/Compiler.kt +++ b/lsp/kotlin/src/main/java/dev/mutwakil/androidide/lsp/kotlin/compiler/Compiler.kt @@ -1,7 +1,7 @@ package dev.mutwakil.androidide.lsp.kotlin.compiler import dev.mutwakil.androidide.lsp.api.ILanguageClient -import dev.mutwakil.androidide.projects.api.Workspace +import dev.mutwakil.androidide.projects.IProjectManager import dev.mutwakil.androidide.utils.DocumentUtils import org.jetbrains.kotlin.com.intellij.openapi.vfs.StandardFileSystems import org.jetbrains.kotlin.com.intellij.openapi.vfs.VirtualFileManager @@ -13,7 +13,7 @@ import java.nio.file.Path import kotlin.io.path.pathString internal class Compiler( - workspace: Workspace, + layout: KotlinModuleLayout, projectModel: KotlinProjectModel, intellijPluginRoot: Path, jdkHome: Path, @@ -35,7 +35,7 @@ internal class Compiler( CompilationEnvironment( name = "default", kind = CompilationKind.Default, - workspace = workspace, + layout = layout, ktProject = projectModel, intellijPluginRoot = intellijPluginRoot, jdkHome = jdkHome, @@ -67,11 +67,20 @@ internal class Compiler( /** * The environment for [file], or null when there is none. A `.kts` has no environment yet; * this returns null for it rather than letting the kind-based overload's - * [UnsupportedOperationException] escape into an LSP request on an open build script. + * [UnsupportedOperationException] escape into an LSP request on an open build script. A file + * its module's selected variant does not compile has none either, so it gets no analysis. */ fun compilationEnvironmentFor(file: Path): CompilationEnvironment? { if (!DocumentUtils.isKotlinFile(file)) return null + if (IProjectManager.getInstance().workspace?.isOutsideSelectedVariant(file) == true) return null + return compilationEnvironmentForKotlinPath(file) + } + /** + * As [compilationEnvironmentFor], but without checking that [file] exists: for a Kotlin path that + * was deleted or renamed away, whose environment still holds its index entries. + */ + fun compilationEnvironmentForKotlinPath(file: Path): CompilationEnvironment? { val kind = compilationKindFor(file) if (kind == CompilationKind.Script) return null diff --git a/lsp/kotlin/src/main/java/dev/mutwakil/androidide/lsp/kotlin/compiler/KotlinApplicationEnvironmentPin.kt b/lsp/kotlin/src/main/java/dev/mutwakil/androidide/lsp/kotlin/compiler/KotlinApplicationEnvironmentPin.kt index 9fd51e863c..48aac6ccdd 100644 --- a/lsp/kotlin/src/main/java/dev/mutwakil/androidide/lsp/kotlin/compiler/KotlinApplicationEnvironmentPin.kt +++ b/lsp/kotlin/src/main/java/dev/mutwakil/androidide/lsp/kotlin/compiler/KotlinApplicationEnvironmentPin.kt @@ -1,21 +1,40 @@ package dev.mutwakil.androidide.lsp.kotlin.compiler +import dev.mutwakil.androidide.lsp.kotlin.compiler.vfs.ListingJarFileSystem +import dev.mutwakil.androidide.zipfs2.listing.JarListingCache import org.jetbrains.kotlin.K1Deprecation -import org.jetbrains.kotlin.cli.jvm.compiler.KotlinCoreEnvironment.Companion.getOrCreateApplicationEnvironmentForProduction as acquireApplicationEnvironment +import org.jetbrains.kotlin.cli.jvm.compiler.KotlinCoreApplicationEnvironment import org.jetbrains.kotlin.com.intellij.openapi.util.Disposer import org.jetbrains.kotlin.config.CompilerConfiguration +import org.jetbrains.kotlin.cli.jvm.compiler.KotlinCoreEnvironment.Companion.getOrCreateApplicationEnvironmentForProduction as acquireApplicationEnvironment @OptIn(K1Deprecation::class) internal object KotlinApplicationEnvironmentPin { - private var pinned = false private val pin = Disposer.newDisposable("kotlin-lsp-application-environment-pin") + /** + * The one JAR file system of the process: code compares files with the environment's + * `jarFileSystem` by identity, and each instance listens to the shared listing cache. + */ + private val jarFileSystem by lazy { ListingJarFileSystem(JarListingCache.SHARED) } + + /** + * Makes every Kotlin application environment created after this call, in production or unit + * test mode, use the shared listing-backed JAR file system. + */ + fun useListingJarFileSystem() { + KotlinCoreApplicationEnvironment.jarFileSystemFactory = { jarFileSystem } + } + @Synchronized fun ensure(configuration: CompilerConfiguration) { if (pinned) return - acquireApplicationEnvironment(pin, configuration) + val environment = acquireApplicationEnvironment(pin, configuration) + check(environment.jarFileSystem is ListingJarFileSystem) { + "The Kotlin application environment was created before its JAR file system was set" + } pinned = true } } diff --git a/lsp/kotlin/src/main/java/dev/mutwakil/androidide/lsp/kotlin/compiler/KotlinModuleLayout.kt b/lsp/kotlin/src/main/java/dev/mutwakil/androidide/lsp/kotlin/compiler/KotlinModuleLayout.kt new file mode 100644 index 0000000000..2756affe5d --- /dev/null +++ b/lsp/kotlin/src/main/java/dev/mutwakil/androidide/lsp/kotlin/compiler/KotlinModuleLayout.kt @@ -0,0 +1,161 @@ +package dev.mutwakil.androidide.lsp.kotlin.compiler + +import dev.mutwakil.androidide.projects.api.AndroidModule +import dev.mutwakil.androidide.projects.api.ModuleProject +import dev.mutwakil.androidide.projects.api.Workspace +import dev.mutwakil.androidide.projects.models.ArtifactScope +import dev.mutwakil.androidide.projects.models.bootClassPaths +import java.io.File +import java.nio.file.Path + +/** + * The project structure Kotlin analysis is built from: everything the analysis modules are made of. + * + * Two equal layouts describe the same analysis modules, so an analysis session built from one serves + * the other. Jars are identified by path; a jar rewritten in place is not a layout change. Compile + * classpaths are sets because the project model does not keep their order. + * + * @property bootClassPaths Boot classpath jars of every Android module, existing ones only, in order. + * @property libraries Every module's compile and test compile classpaths, existing jars only. + * @property modules One entry per source module, in workspace order, each Gradle module's main + * sources followed by its test sources. + */ +internal data class KotlinModuleLayout( + val bootClassPaths: List, + val libraries: Set, + val modules: List, +) + +/** + * One source module of a [KotlinModuleLayout]. + * + * @property path Identifies the module: the Gradle project path for main sources, with a + * scope suffix for other scopes' sources (see [testModulePath]). + * @property sourceRoots The module's source directories. + * @property classpath The compile classpath without generated sources. + * @property moduleDependencies Paths of the modules this one compiles against. + * @property apiVersion The Kotlin API version, or null when the module has no Java or Android project. + * @property jvmTarget The Kotlin JVM target, or null when the module has no Java or Android project. + * @property friends Paths of the modules whose `internal` declarations this one may use: a test + * module's main module. + */ +internal data class SourceModuleLayout( + val path: String, + val name: String, + val sourceRoots: Set, + val classpath: Set, + val moduleDependencies: List, + val apiVersion: String?, + val jvmTarget: String?, + val friends: List = emptyList(), +) + +/** The [SourceModuleLayout.path] of the [scope] module of the Gradle module at [path]. */ +internal fun testModulePath( + path: String, + scope: ArtifactScope, +): String = "$path[${scope.moduleSuffix}]" + +/** + * Returns the [KotlinModuleLayout] of this workspace. Reads the file system, so not on the main thread. + * + * Module dependencies and compile classpaths are resolved through the global + * `IProjectManager.getInstance().workspace`, not this one, and come out empty while it is null. + */ +internal fun Workspace.kotlinModuleLayout(): KotlinModuleLayout { + val moduleProjects = + subProjects + .filterIsInstance() + .filter { it.path != rootProject.path } + + val bootClassPaths = + moduleProjects + .filterIsInstance() + .flatMap { it.bootClassPaths } + .filter { it.exists() } + .map { it.toPath() } + .distinct() + + val libraries = + moduleProjects + .flatMap { module -> + module.getCompileClasspaths() + module.nonMainScopes().flatMap { module.getCompileClasspaths(it) } + }.filter { it.exists() } + .mapTo(LinkedHashSet()) { it.toPath() } + + return KotlinModuleLayout( + bootClassPaths = bootClassPaths, + libraries = libraries, + modules = + moduleProjects.flatMap { module -> + val main = module.sourceModuleLayout() + listOf(main) + module.nonMainScopes().mapNotNull { module.testModuleLayout(main, it) } + }, + ) +} + +private fun ModuleProject.nonMainScopes() = getArtifactScopes().filter { it != ArtifactScope.Main } + +private fun ModuleProject.sourceModuleLayout(): SourceModuleLayout { + val kotlinSettings = + when { + hasJavaProject() -> javaProject.kotlinCompilerSettings + hasAndroidProject() -> androidProject.kotlinCompilerSettings + else -> null + } + + return SourceModuleLayout( + path = path, + name = name, + sourceRoots = existingRoots(getSourceDirectories()), + classpath = getCompileClasspaths(excludeSourceGeneratedClassPath = true).mapTo(LinkedHashSet()) { it.toPath() }, + moduleDependencies = getCompileModuleProjects().map { it.path }, + apiVersion = kotlinSettings?.apiVersion, + jvmTarget = kotlinSettings?.jvmTarget, + ) +} + +/** + * The [scope] module layered over [main], or null when none of its source dirs exists. It is + * main's friend, so it may use `internal` declarations, and compiles against main, everything main + * does, the scopes it sees and its own scope-only modules. No two test modules depend on each other. + */ +private fun ModuleProject.testModuleLayout( + main: SourceModuleLayout, + scope: ArtifactScope, +): SourceModuleLayout? { + val sourceRoots = existingRoots(getSourceDirectories(scope)) + if (sourceRoots.isEmpty()) { + return null + } + + val ownSeenScopes = + nonMainScopes() + .filter { it != scope && scope.sees(it) && hasScopeModule(it) } + .map { testModulePath(path, it) } + val otherModulesFixtures = + getTestFixturesModuleProjects(scope) + .filter { it.hasScopeModule(ArtifactScope.TestFixtures) } + .map { testModulePath(it.path, ArtifactScope.TestFixtures) } + // Scope-only project dependencies must be source modules: the scope's classpath leaves out their jars. + val scopeOnlyModules = getCompileModuleProjects(scope).map { it.path } + + return main.copy( + path = testModulePath(path, scope), + name = "$name (${scope.displayName()})", + sourceRoots = sourceRoots, + classpath = getCompileClasspaths(scope, excludeSourceGeneratedClassPath = true).mapTo(LinkedHashSet()) { it.toPath() }, + moduleDependencies = (listOf(path) + ownSeenScopes + otherModulesFixtures + main.moduleDependencies + scopeOnlyModules).distinct(), + friends = listOf(path), + ) +} + +/** Whether [scope] gets a source module: [testModuleLayout] makes one only for existing dirs. */ +private fun ModuleProject.hasScopeModule(scope: ArtifactScope): Boolean = existingRoots(getSourceDirectories(scope)).isNotEmpty() + +/** `unitTest` -> `unit test`. */ +private fun ArtifactScope.displayName(): String = moduleSuffix.replace(Regex("[A-Z]")) { " " + it.value.lowercase() } + +// The analysis session drops a root that does not exist when it is built, so a dir created later +// (src/debug/java, most variant layers) must change the layout for the next sync to rebuild it. +private fun existingRoots(dirs: Set): Set = dirs.filter { it.isDirectory }.mapTo(LinkedHashSet()) { it.toPath() } diff --git a/lsp/kotlin/src/main/java/dev/mutwakil/androidide/lsp/kotlin/compiler/KotlinProjectModel.kt b/lsp/kotlin/src/main/java/dev/mutwakil/androidide/lsp/kotlin/compiler/KotlinProjectModel.kt index 39151ec65f..c30af53dac 100644 --- a/lsp/kotlin/src/main/java/dev/mutwakil/androidide/lsp/kotlin/compiler/KotlinProjectModel.kt +++ b/lsp/kotlin/src/main/java/dev/mutwakil/androidide/lsp/kotlin/compiler/KotlinProjectModel.kt @@ -1,6 +1,5 @@ package dev.mutwakil.androidide.lsp.kotlin.compiler -import dev.mutwakil.androidide.projects.ProjectManagerImpl import dev.mutwakil.androidide.projects.api.Workspace import org.appdevforall.codeonthego.indexing.jvm.JVM_GENERATED_SYMBOL_INDEX import org.appdevforall.codeonthego.indexing.jvm.JVM_LIBRARY_SYMBOL_INDEX @@ -8,6 +7,9 @@ import org.appdevforall.codeonthego.indexing.jvm.JvmSymbolIndex import org.appdevforall.codeonthego.indexing.jvm.KT_SOURCE_FILE_INDEX_KEY import org.appdevforall.codeonthego.indexing.jvm.KT_SOURCE_FILE_META_INDEX_KEY import org.appdevforall.codeonthego.indexing.jvm.KtFileMetadataIndex +import org.appdevforall.codeonthego.indexing.service.IndexKey +import org.appdevforall.codeonthego.indexing.service.IndexRegistry +import org.appdevforall.codeonthego.indexing.service.IndexRegistryClosedException import org.jetbrains.kotlin.platform.TargetPlatform import org.jetbrains.kotlin.platform.jvm.JvmPlatforms import org.slf4j.LoggerFactory @@ -23,7 +25,13 @@ import org.slf4j.LoggerFactory * (build complete), it notifies registered listeners so they can * refresh their sessions. */ -internal class KotlinProjectModel { +internal class KotlinProjectModel( + /* + * The registry of the project session this model was built for. Its indexes are looked up on each + * read because the generated index may register after the build. + */ + private val registry: IndexRegistry, +) { private val logger = LoggerFactory.getLogger(KotlinProjectModel::class.java) private var workspace: Workspace? = null @@ -32,36 +40,24 @@ internal class KotlinProjectModel { private val listeners = mutableListOf() val libraryIndex: JvmSymbolIndex? - get() = - ProjectManagerImpl - .getInstance() - .indexingServiceManager - .registry - .get(JVM_LIBRARY_SYMBOL_INDEX) + get() = registry.get(JVM_LIBRARY_SYMBOL_INDEX) val sourceIndex: JvmSymbolIndex? - get() = - ProjectManagerImpl - .getInstance() - .indexingServiceManager - .registry - .get(KT_SOURCE_FILE_INDEX_KEY) + get() = registry.get(KT_SOURCE_FILE_INDEX_KEY) val fileIndex: KtFileMetadataIndex? - get() = - ProjectManagerImpl - .getInstance() - .indexingServiceManager - .registry - .get(KT_SOURCE_FILE_META_INDEX_KEY) + get() = registry.get(KT_SOURCE_FILE_META_INDEX_KEY) val generatedIndex: JvmSymbolIndex? - get() = - ProjectManagerImpl - .getInstance() - .indexingServiceManager - .registry - .get(JVM_GENERATED_SYMBOL_INDEX) + get() = registry.get(JVM_GENERATED_SYMBOL_INDEX) + + /** + * Returns the index registered for [key]. + * + * @throws IndexRegistryClosedException if this model's project session has closed. + * @throws IllegalStateException if the session is open but nothing is registered for [key]. + */ + fun requireIndex(key: IndexKey): T = registry.require(key) /** * The kind of change that occurred. diff --git a/lsp/kotlin/src/main/java/dev/mutwakil/androidide/lsp/kotlin/compiler/ReadWriteLock.kt b/lsp/kotlin/src/main/java/dev/mutwakil/androidide/lsp/kotlin/compiler/ReadWriteLock.kt index 2a75d9800a..03f142e972 100644 --- a/lsp/kotlin/src/main/java/dev/mutwakil/androidide/lsp/kotlin/compiler/ReadWriteLock.kt +++ b/lsp/kotlin/src/main/java/dev/mutwakil/androidide/lsp/kotlin/compiler/ReadWriteLock.kt @@ -21,4 +21,30 @@ fun Project.read(fn: () -> T): T { fun Project.write(fn: () -> T): T { val lock = getUserData(key)!! return lock.write(fn) -} \ No newline at end of file +} + +/** + * Runs [fn] under the read lock and returns its result, or returns null without running it if the project is disposed. + * + * Disposal takes the write lock, so the project cannot be disposed while [fn] runs. + */ +fun Project.readUnlessDisposed(fn: () -> T): T? = read { if (isDisposed) null else fn() } + +/** Runs [fn] under the write lock and returns its result, or returns null without running it if the project is disposed. */ +fun Project.writeUnlessDisposed(fn: () -> T): T? = write { if (isDisposed) null else fn() } + +/** + * Runs [fn] under the write lock if it is free now, without waiting or queueing; returns whether it ran. + * + * A queued writer would block every new reader, including the UI thread, until it got the lock. + */ +fun Project.tryWrite(fn: () -> Unit): Boolean { + val writeLock = getUserData(key)!!.writeLock() + if (!writeLock.tryLock()) return false + try { + fn() + } finally { + writeLock.unlock() + } + return true +} diff --git a/lsp/kotlin/src/main/java/dev/mutwakil/androidide/lsp/kotlin/compiler/WorkspaceExts.kt b/lsp/kotlin/src/main/java/dev/mutwakil/androidide/lsp/kotlin/compiler/WorkspaceExts.kt index fa82409684..7e5a774b22 100644 --- a/lsp/kotlin/src/main/java/dev/mutwakil/androidide/lsp/kotlin/compiler/WorkspaceExts.kt +++ b/lsp/kotlin/src/main/java/dev/mutwakil/androidide/lsp/kotlin/compiler/WorkspaceExts.kt @@ -5,10 +5,6 @@ import dev.mutwakil.androidide.lsp.kotlin.compiler.modules.KtModule import dev.mutwakil.androidide.lsp.kotlin.compiler.modules.KtSourceModule import dev.mutwakil.androidide.lsp.kotlin.compiler.modules.buildKtLibraryModule import dev.mutwakil.androidide.lsp.kotlin.compiler.modules.buildKtSourceModule -import dev.mutwakil.androidide.projects.api.AndroidModule -import dev.mutwakil.androidide.projects.api.ModuleProject -import dev.mutwakil.androidide.projects.api.Workspace -import dev.mutwakil.androidide.projects.models.bootClassPaths import org.jetbrains.kotlin.com.intellij.core.CoreApplicationEnvironment import org.jetbrains.kotlin.com.intellij.openapi.project.Project import org.slf4j.LoggerFactory @@ -17,19 +13,12 @@ import kotlin.io.path.pathString private val logger = LoggerFactory.getLogger("WorkspaceExts") -internal fun Workspace.collectKtModules( +/** Builds the analysis modules this layout describes, one per source module, test modules included. */ +internal fun KotlinModuleLayout.toKtModules( project: Project, appEnv: CoreApplicationEnvironment, ): List = buildList { - fun addModule(module: KtModule) = add(module) - - val moduleProjects = - subProjects - .asSequence() - .filterIsInstance() - .filter { it.path != rootProject.path } - val jarToModMap = mutableMapOf() // One module per jar: every module shares android.jar, and each KtLibraryModule @@ -42,59 +31,52 @@ internal fun Workspace.collectKtModules( } } - // A List, not a Sequence: a Sequence would re-run addLibrary for every source module below. - val bootClassPaths = - moduleProjects - .filterIsInstance() - .flatMap { it.bootClassPaths.asSequence() } - .filter { it.exists() } - .map { it.toPath() } - .distinct() - .map(::addLibrary) - .toList() + val bootLibraries = bootClassPaths.map(::addLibrary) + val libraryDependencies = libraries.associateWith(::addLibrary) - val libraryDependencies = - moduleProjects - .flatMap { it.getCompileClasspaths() } - .filter { it.exists() } - .map { it.toPath() } - .associateWith(::addLibrary) + val layoutsByPath = modules.associateBy { it.path } + val sourceModules = mutableMapOf() + val modulesInProgress = mutableSetOf() - val subprojectsAsModules = mutableMapOf() - val sourceRootToModuleMap = mutableMapOf() - - fun getOrCreateModule(moduleProject: ModuleProject): KtSourceModule { - subprojectsAsModules[moduleProject]?.let { return it } + fun getOrCreateModule(moduleLayout: SourceModuleLayout): KtSourceModule { + sourceModules[moduleLayout.path]?.let { return it } + modulesInProgress += moduleLayout.path val module = buildKtSourceModule(project) { - this.module = moduleProject - - bootClassPaths.forEach { addDependency(it) } - - moduleProject - .getCompileClasspaths(excludeSourceGeneratedClassPath = true) - .forEach { classpath -> - val libDep = libraryDependencies[classpath.toPath()] - if (libDep == null) { - logger.error( - "Skipping non-existent classpath classpath: {}", - classpath, - ) - return@forEach - } - addDependency(libDep) + this.layout = moduleLayout + + bootLibraries.forEach { addDependency(it) } + + moduleLayout.classpath.forEach { classpath -> + val libDep = libraryDependencies[classpath] + if (libDep == null) { + logger.error( + "Skipping non-existent classpath classpath: {}", + classpath, + ) + return@forEach } - - moduleProject.getCompileModuleProjects().forEach { dep -> - addDependency(getOrCreateModule(dep)) + addDependency(libDep) } + + // A dependency still being built closes a cycle; skipping it breaks the cycle, + // which ModuleProject.getCompileModuleProjects has already reported to the user. + moduleLayout.moduleDependencies + .filterNot { it in modulesInProgress } + .mapNotNull { layoutsByPath[it] } + .forEach { dep -> addDependency(getOrCreateModule(dep)) } + + // A friend is always a module dependency too, so it is built by now. + moduleLayout.friends + .mapNotNull { sourceModules[it] } + .forEach { addFriend(it) } } - subprojectsAsModules[moduleProject] = module - module.contentRoots.forEach { root -> sourceRootToModuleMap[root] = module } + modulesInProgress -= moduleLayout.path + sourceModules[moduleLayout.path] = module return module } - moduleProjects.forEach { addModule(getOrCreateModule(it)) } - } \ No newline at end of file + modules.forEach { add(getOrCreateModule(it)) } + } diff --git a/lsp/kotlin/src/main/java/dev/mutwakil/androidide/lsp/kotlin/compiler/index/IndexCommand.kt b/lsp/kotlin/src/main/java/dev/mutwakil/androidide/lsp/kotlin/compiler/index/IndexCommand.kt index 4787586865..420cd18752 100644 --- a/lsp/kotlin/src/main/java/dev/mutwakil/androidide/lsp/kotlin/compiler/index/IndexCommand.kt +++ b/lsp/kotlin/src/main/java/dev/mutwakil/androidide/lsp/kotlin/compiler/index/IndexCommand.kt @@ -40,4 +40,4 @@ internal sealed interface IndexCommand { data class RemoveFromIndex( val path: Path, ) : IndexCommand -} \ No newline at end of file +} diff --git a/lsp/kotlin/src/main/java/dev/mutwakil/androidide/lsp/kotlin/compiler/index/IndexWorker.kt b/lsp/kotlin/src/main/java/dev/mutwakil/androidide/lsp/kotlin/compiler/index/IndexWorker.kt index 6800318d02..9834c770f2 100644 --- a/lsp/kotlin/src/main/java/dev/mutwakil/androidide/lsp/kotlin/compiler/index/IndexWorker.kt +++ b/lsp/kotlin/src/main/java/dev/mutwakil/androidide/lsp/kotlin/compiler/index/IndexWorker.kt @@ -28,6 +28,8 @@ internal class IndexWorker( private val fileIndex: KtFileMetadataIndex, private val sourceIndex: JvmSymbolIndex, private val scope: CoroutineScope, + /** [KtSymbolIndex.resolvesTo]. */ + private val resolvesTo: (Path, KtFile) -> Boolean, ) { companion object { private val logger = LoggerFactory.getLogger(IndexWorker::class.java) @@ -59,7 +61,7 @@ internal class IndexWorker( logger.debug("Indexing modified file: {}", path) try { // Not counted in sourceIndexCount: this runs on another coroutine, and an edit is not part of a pass. - indexSourceFile(project, ktFile, fileIndex, sourceIndex, cancelChecker) + indexSourceFile(project, ktFile, fileIndex, sourceIndex, cancelChecker, resolvesTo) } catch (e: AnalysisPreemptedException) { // Preempted by higher-priority analysis; re-queue so the edit still gets indexed. logger.debug("Indexing of modified file {} preempted; re-queueing", path) @@ -206,7 +208,7 @@ internal class IndexWorker( } fileIndex.upsert(newFile) - scanCount++ + if (fileIndex.isOpen) scanCount++ } is IndexCommand.SourceScanningComplete -> { @@ -260,18 +262,20 @@ internal class IndexWorker( // cmd.vf.path is not a plain field read (it builds a system-independent // path string), so it must not be computed when nothing records it. val detail = if (Memprof.sink != null) cmd.vf.path else null - Memprof.section("Index Kotlin file", detail) { - indexSourceFile( - project = project, - ktFile = ktFile, - fileIndex = fileIndex, - symbolsIndex = sourceIndex, - // A real (cancellable) checker so the scheduler can preempt this pass - // in favour of completion/diagnostics. - cancelChecker = ICancelChecker.Default(), - ) - } - IndexOutcome.INDEXED + val wrote = + Memprof.section("Index Kotlin file", detail) { + indexSourceFile( + project = project, + ktFile = ktFile, + fileIndex = fileIndex, + symbolsIndex = sourceIndex, + // A real (cancellable) checker so the scheduler can preempt this pass + // in favour of completion/diagnostics. + cancelChecker = ICancelChecker.Default(), + resolvesTo = resolvesTo, + ) + } + if (wrote) IndexOutcome.INDEXED else IndexOutcome.SKIPPED } catch (e: AnalysisPreemptedException) { IndexOutcome.PREEMPTED } @@ -346,4 +350,4 @@ internal suspend fun applyRemovals( // Collapse all symbol removals into a single transaction. sourceIndex.removeBySources(paths) -} \ No newline at end of file +} diff --git a/lsp/kotlin/src/main/java/dev/mutwakil/androidide/lsp/kotlin/compiler/index/KtSymbolIndex.kt b/lsp/kotlin/src/main/java/dev/mutwakil/androidide/lsp/kotlin/compiler/index/KtSymbolIndex.kt index 071e3621d3..3a3dda9ab6 100644 --- a/lsp/kotlin/src/main/java/dev/mutwakil/androidide/lsp/kotlin/compiler/index/KtSymbolIndex.kt +++ b/lsp/kotlin/src/main/java/dev/mutwakil/androidide/lsp/kotlin/compiler/index/KtSymbolIndex.kt @@ -1,5 +1,6 @@ package dev.mutwakil.androidide.lsp.kotlin.compiler.index +import androidx.annotation.VisibleForTesting import com.github.benmanes.caffeine.cache.Caffeine import dev.mutwakil.androidide.lsp.kotlin.compiler.CompilationKind import dev.mutwakil.androidide.lsp.kotlin.compiler.modules.AnalysisPriority @@ -11,6 +12,8 @@ import dev.mutwakil.androidide.lsp.kotlin.compiler.modules.backingFilePath import dev.mutwakil.androidide.lsp.kotlin.compiler.read import dev.mutwakil.androidide.lsp.kotlin.compiler.services.ProjectStructureProvider import dev.mutwakil.androidide.lsp.kotlin.compiler.write +import dev.mutwakil.androidide.lsp.kotlin.compiler.writeUnlessDisposed +import dev.mutwakil.androidide.lsp.kotlin.utils.toNioPathOrNull import dev.mutwakil.androidide.lsp.kotlin.utils.toVirtualFileOrNull import dev.mutwakil.androidide.projects.FileManager import dev.mutwakil.androidide.utils.DocumentUtils @@ -37,11 +40,13 @@ import org.jetbrains.kotlin.com.intellij.openapi.vfs.VirtualFile import org.jetbrains.kotlin.com.intellij.psi.PsiManager import org.jetbrains.kotlin.com.intellij.psi.impl.PsiManagerEx import org.jetbrains.kotlin.com.intellij.psi.impl.file.impl.FileManagerImpl +import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.psi.KtElement import org.jetbrains.kotlin.psi.KtFile import org.jetbrains.kotlin.psi.KtPsiFactory import org.slf4j.LoggerFactory import java.nio.file.Path +import java.nio.file.Paths import java.util.concurrent.CompletableFuture import java.util.concurrent.ConcurrentHashMap import java.util.concurrent.ExecutorService @@ -88,6 +93,7 @@ internal class KtSymbolIndex( fileIndex = fileIndex, sourceIndex = sourceIndex, scope = scope, + resolvesTo = ::resolvesTo, ) private val scanningWorker = @@ -107,6 +113,15 @@ internal class KtSymbolIndex( .maximumSize(cacheSize) .build() + private val packageFiles = + PackageFileCache( + maxCachedFiles = PackageFileCache.DEFAULT_MAX_CACHED_FILES, + pathOf = { it.toNioPathOrNull()?.pathString.orEmpty() }, + query = ::findSourceFiles, + ) + + private val packageFilesRegistration: AutoCloseable = fileIndex.addWriteListener(packageFiles) + /** Set by AbstractCompilationEnvironment.initialize once the env's KtPsiFactory exists. */ lateinit var parser: KtPsiFactory @@ -209,6 +224,7 @@ internal class KtSymbolIndex( } suspend fun removeFromIndex(path: Path) { + ktFileCache.invalidate(path) indexWorker.submitCommand(IndexCommand.RemoveFromIndex(path)) } @@ -316,10 +332,15 @@ internal class KtSymbolIndex( return VersionedKtFile(version, newKtFile) } + /** Whether the disk copy of [path] is held in the parsed-file cache. */ + @VisibleForTesting + internal fun isDiskCopyCached(path: Path): Boolean = ktFileCache.getIfPresent(path) != null + fun evictDiskCopy(path: Path) { ktFileCache.invalidate(path) + if (project.isDisposed) return val vf = path.toVirtualFileOrNull() ?: return - project.write { + project.writeUnlessDisposed { ApplicationManager.getApplication().runWriteAction { (PsiManagerEx.getInstanceEx(project).fileManager as FileManagerImpl).setViewProvider(vf, null) } @@ -524,6 +545,25 @@ internal class KtSymbolIndex( } } + /** Returns the source files the metadata index lists for [packageFqName]. */ + internal fun sourceFilesForPackage(packageFqName: FqName): List = packageFiles.filesFor(packageFqName.asString()) + + private fun findSourceFiles(packageFqName: String): List = + fileIndex + .getFilePathsForPackage(packageFqName) + .mapNotNull { Paths.get(it).toVirtualFileOrNull() } + .toList() + + /** + * Whether FIR resolves [path] to [ktFile]. Non-blocking and never refreshes, so the indexer can ask + * under `project.read` without queueing more indexing. + */ + @OptIn(ResolutionSideKtFileAccess::class) + internal fun resolvesTo( + path: Path, + ktFile: KtFile, + ): Boolean = getKtFile(path) === ktFile + /** [getKtFile] for [vf], keyed by the path it maps to. */ @ResolutionSideKtFileAccess internal fun getKtFile(vf: VirtualFile): KtFile? = getKtFile(vf.toNioPath(), vf) @@ -581,10 +621,14 @@ internal class KtSymbolIndex( } suspend fun close() { - indexWorker.submitCommand(IndexCommand.Stop) + packageFilesRegistration.close() + /* + * Cancel the worker rather than queueing a stop: a stop waits behind every queued file, and + * a large pass outlasts the caller's bounded wait, so disposal would proceed under a live worker. + */ scanningJob?.cancelAndJoin() - indexingJob?.join() + indexingJob?.cancelAndJoin() /* * Cancel AND JOIN the index's own scope. Beyond the main worker loop drained above, the @@ -604,8 +648,6 @@ internal class KtSymbolIndex( internal fun KtSymbolIndex.packageExistsInSource(packageFqn: String) = fileIndex.packageExists(packageFqn) -internal fun KtSymbolIndex.filesForPackage(packageFqn: String) = fileIndex.getFilesForPackage(packageFqn) - internal fun KtSymbolIndex.subpackageNames(packageFqn: String) = fileIndex.getSubpackageNames(packageFqn) /** @@ -628,4 +670,4 @@ internal fun KtSymbolIndex.findSymbolBySimpleName( ) = ( sourceIndex.findBySimpleName(name, limit, kinds) + libraryIndex.findBySimpleName(name, limit, kinds) -).let { if (limit <= 0) it else it.take(limit) } \ No newline at end of file +).let { if (limit <= 0) it else it.take(limit) } diff --git a/lsp/kotlin/src/main/java/dev/mutwakil/androidide/lsp/kotlin/compiler/index/PackageFileCache.kt b/lsp/kotlin/src/main/java/dev/mutwakil/androidide/lsp/kotlin/compiler/index/PackageFileCache.kt new file mode 100644 index 0000000000..7da383af83 --- /dev/null +++ b/lsp/kotlin/src/main/java/dev/mutwakil/androidide/lsp/kotlin/compiler/index/PackageFileCache.kt @@ -0,0 +1,94 @@ +package dev.mutwakil.androidide.lsp.kotlin.compiler.index + +import com.github.benmanes.caffeine.cache.Caffeine +import org.appdevforall.codeonthego.indexing.jvm.KtFileMetadataWrite +import org.appdevforall.codeonthego.indexing.jvm.KtFileMetadataWriteListener +import java.util.concurrent.Executor +import java.util.concurrent.ForkJoinPool + +/** + * Caches the files of each package, dropping entries as index writes make them stale. + * + * The cache is bounded by the total number of files it lists, so retained memory stays small. + */ +internal class PackageFileCache( + maxCachedFiles: Long, + private val pathOf: (F) -> String, + private val query: (packageFqName: String) -> List, + executor: Executor = ForkJoinPool.commonPool(), +) : KtFileMetadataWriteListener { + private val lock = Any() + + /** Bumped by every write, under [lock]. A lookup only caches its result if no write ran meanwhile. */ + private var generation = 0L + + /** A package's files, with their paths converted once so writes only do set lookups. */ + private class Entry( + val files: List, + val paths: Set, + ) + + private val cache = + Caffeine + .newBuilder() + .executor(executor) + .maximumWeight(maxCachedFiles) + .weigher> { _, entry -> entry.files.size + 1 } + .build>() + + /** Returns the files declared in [packageFqName], querying only when the answer is not cached. */ + fun filesFor(packageFqName: String): List { + cache.getIfPresent(packageFqName)?.let { return it.files } + val observed = synchronized(lock) { generation } + val files = query(packageFqName) + val entry = Entry(files, files.mapTo(HashSet(), pathOf)) + synchronized(lock) { + if (generation == observed) cache.put(packageFqName, entry) + } + return files + } + + override fun onWrite(write: KtFileMetadataWrite) = + synchronized(lock) { + generation++ + when (write) { + is KtFileMetadataWrite.Upserted -> { + // A live edit re-upserts a file its package already lists; that list is still right. + invalidateUnlessListed(write.packageFqName, write.filePath) + invalidateContaining(setOf(write.filePath), except = write.packageFqName) + } + + is KtFileMetadataWrite.Removed -> { + invalidateContaining(write.filePaths.toSet()) + } + + KtFileMetadataWrite.Cleared -> { + cache.invalidateAll() + } + } + } + + private fun invalidateUnlessListed( + packageFqName: String, + path: String, + ) { + val entry = cache.getIfPresent(packageFqName) ?: return + if (path !in entry.paths) cache.invalidate(packageFqName) + } + + private fun invalidateContaining( + paths: Set, + except: String? = null, + ) { + val stale = + cache + .asMap() + .filter { (packageFqName, entry) -> packageFqName != except && paths.any { it in entry.paths } } + .keys + cache.invalidateAll(stale) + } + + companion object { + const val DEFAULT_MAX_CACHED_FILES = 2_000L + } +} diff --git a/lsp/kotlin/src/main/java/dev/mutwakil/androidide/lsp/kotlin/compiler/index/ScanningWorker.kt b/lsp/kotlin/src/main/java/dev/mutwakil/androidide/lsp/kotlin/compiler/index/ScanningWorker.kt index d4e2d7a736..230b2f4107 100644 --- a/lsp/kotlin/src/main/java/dev/mutwakil/androidide/lsp/kotlin/compiler/index/ScanningWorker.kt +++ b/lsp/kotlin/src/main/java/dev/mutwakil/androidide/lsp/kotlin/compiler/index/ScanningWorker.kt @@ -67,4 +67,4 @@ internal class ScanningWorker( if (!isActive) return@coroutineScope indexWorker.submitCommand(IndexCommand.IndexingComplete(pass)) } -} \ No newline at end of file +} diff --git a/lsp/kotlin/src/main/java/dev/mutwakil/androidide/lsp/kotlin/compiler/index/SourceFileIndexer.kt b/lsp/kotlin/src/main/java/dev/mutwakil/androidide/lsp/kotlin/compiler/index/SourceFileIndexer.kt index f58f1f7907..330ec567e8 100644 --- a/lsp/kotlin/src/main/java/dev/mutwakil/androidide/lsp/kotlin/compiler/index/SourceFileIndexer.kt +++ b/lsp/kotlin/src/main/java/dev/mutwakil/androidide/lsp/kotlin/compiler/index/SourceFileIndexer.kt @@ -57,6 +57,7 @@ import org.jetbrains.kotlin.utils.exceptions.KotlinExceptionWithAttachments import org.slf4j.LoggerFactory import java.io.FileNotFoundException import java.nio.file.NoSuchFileException +import java.nio.file.Path import java.time.Instant import kotlin.io.path.pathString @@ -78,6 +79,23 @@ internal fun Throwable.isMissingClasspathFile(): Boolean = .take(32) .any { it is NoSuchFileException || it is FileNotFoundException } +/** + * This resolver's answer, or null when it throws: e.g. the path's last refresh failed, so its future + * completed exceptionally. Callers run outside any catch on a scope with no exception handler. + */ +private fun ((Path, KtFile) -> Boolean).orNull( + path: Path, + ktFile: KtFile, +): Boolean? = + try { + invoke(path, ktFile) + } catch (e: CancellationException) { + throw e + } catch (e: Throwable) { + logger.warn("Could not tell which instance FIR resolves {} to", path, e) + null + } + internal fun KtFile.toMetadata( project: Project, isIndexed: Boolean = false, @@ -98,6 +116,14 @@ internal fun KtFile.toMetadata( ) } +/** + * Indexes [ktFile]'s declarations into [symbolsIndex] and records it in [fileIndex]. + * + * Returns true only when it wrote the file's symbols; false when the file was unchanged, could not + * be analyzed, is not the instance FIR resolves its path to, or an index was closed. + * + * [resolvesTo] tells whether FIR resolves a path to a given instance. It must not block or refresh. + */ @OptIn(UnpinnedAnalysis::class) internal suspend fun indexSourceFile( project: Project, @@ -105,7 +131,8 @@ internal suspend fun indexSourceFile( fileIndex: KtFileMetadataIndex, symbolsIndex: JvmSymbolIndex, cancelChecker: ICancelChecker, -) { + resolvesTo: (Path, KtFile) -> Boolean, +): Boolean { // Indexing runs at the lowest priority, yielding to completion and diagnostics. Wrapping the checker // lets the scheduler preempt an in-progress pass; the preemption surfaces as AnalysisPreemptedException // at the abortIfCancelled() checkpoints below, which IndexWorker catches to re-queue the file. @@ -114,20 +141,30 @@ internal suspend fun indexSourceFile( // Defensive backstop: this runs on the debounced/async index scope, so a disposal path that // didn't first drain & join the workers could otherwise touch PSI on a disposed project and // throw "Project is already disposed" (APPDEVFORALL-17R). Cheap fast-path before the reads below. - if (project.isDisposed) return + if (project.isDisposed) return false // Re-check disposal *inside* the read lock so it is atomic with toMetadata()'s PSI access: // the fast-path check above can race a concurrent disposal before toMetadata enters its read. val newFile = project.read { if (project.isDisposed) return@read null - ktFile.toMetadata(project, isIndexed = true) - } ?: return + val metadata = ktFile.toMetadata(project, isIndexed = true) + /* + * FIR resolves an open path to its newest parse, so analysing any other instance (the disk copy + * on a full pass, or an edit's superseded parse) finds no FIR for its declarations (ADFA-5763). + * Skip it: the refresh that produced the newer instance queued that instance's own pass. + */ + if (resolvesTo.orNull(Path.of(metadata.filePath), ktFile) != true) { + logger.debug("Skipping {}: FIR resolves its path to another instance", metadata.filePath) + return@read null + } + metadata + } ?: return false val existingFile = fileIndex.get(newFile.filePath) checker.abortIfCancelled() if (KtFileMetadata.shouldBeSkipped(existingFile, newFile) && existingFile?.isIndexed == true) { - return + return false } // Remove stale symbols written during the previous indexing pass. @@ -157,7 +194,7 @@ internal suspend fun indexSourceFile( object : KtTreeVisitorVoid() { override fun visitDeclaration(dcl: KtDeclaration) { checker.abortIfCancelled() - val symbol = with(session) { analyzeDeclaration(newFile.filePath, dcl) } + val symbol = with(session) { analyzeDeclaration(newFile.filePath, dcl, resolvesTo) } checker.abortIfCancelled() symbol?.let { list.add(it) } super.visitDeclaration(dcl) @@ -176,17 +213,20 @@ internal suspend fun indexSourceFile( logger.error("Failed to index {}", newFile.filePath, e) //Sentry.captureException(e) } - return + return false } symbolsIndex.insertAll(symbols.asSequence()) fileIndex.upsert(newFile.copy(symbolKeys = symbols.map { it.key })) + // A closed index drops writes silently; closing is one-way, so checking afterwards never over-reports. + return fileIndex.isOpen && symbolsIndex.isOpen } @OptIn(KaImplementationDetail::class) private fun KaSession.analyzeDeclaration( filePath: String, dcl: KtDeclaration, + resolvesTo: (Path, KtFile) -> Boolean, ): JvmSymbol? { dcl.name ?: return null return runCatching { @@ -208,6 +248,8 @@ private fun KaSession.analyzeDeclaration( /*Sentry.captureException(err) { scope -> scope.apply { setExtra("fpth", filePath) + // False means the instance was superseded mid-pass; true means the failure has another cause. + setTag("instanceMatches", resolvesTo.orNull(Path.of(filePath), dcl.containingKtFile)?.toString() ?: "unknown") setExtra("dcl", dcl.name) setExtra("dcl.dbg", dcl.getDebugText()) setExtra( @@ -588,4 +630,4 @@ private fun KaSession.analyzeTypeAlias( typeParameters = aliasSymbol.typeParameters.map { it.name.asString() }, ), ) -} \ No newline at end of file +} diff --git a/lsp/kotlin/src/main/java/dev/mutwakil/androidide/lsp/kotlin/compiler/modules/AbstractKtModule.kt b/lsp/kotlin/src/main/java/dev/mutwakil/androidide/lsp/kotlin/compiler/modules/AbstractKtModule.kt index 93501fd61a..7fefaefb3d 100644 --- a/lsp/kotlin/src/main/java/dev/mutwakil/androidide/lsp/kotlin/compiler/modules/AbstractKtModule.kt +++ b/lsp/kotlin/src/main/java/dev/mutwakil/androidide/lsp/kotlin/compiler/modules/AbstractKtModule.kt @@ -26,7 +26,7 @@ internal abstract class AbstractKtModule( _baseSearchScope = computeBaseContentScope() _contentScope = KaContentScopeProvider.getInstance(project).getRefinedContentScope(this) -// Sentry.addBreadcrumb("createSearchScopes(mod=$this, base=${_baseSearchScope?.hashCode()}, content=${_contentScope?.hashCode()})") + //Sentry.addBreadcrumb("createSearchScopes(mod=$this, base=${_baseSearchScope?.hashCode()}, content=${_contentScope?.hashCode()})") } /** @@ -44,7 +44,7 @@ internal abstract class AbstractKtModule( fun invalidateSearchScope() { synchronized(searchScopeLock) { -// Sentry.addBreadcrumb("invalidateSearchScope(mod=$this)") + //Sentry.addBreadcrumb("invalidateSearchScope(mod=$this)") _baseSearchScope = null _contentScope = null } diff --git a/lsp/kotlin/src/main/java/dev/mutwakil/androidide/lsp/kotlin/compiler/modules/KtFileExts.kt b/lsp/kotlin/src/main/java/dev/mutwakil/androidide/lsp/kotlin/compiler/modules/KtFileExts.kt index c18194c348..e3fc1611a8 100644 --- a/lsp/kotlin/src/main/java/dev/mutwakil/androidide/lsp/kotlin/compiler/modules/KtFileExts.kt +++ b/lsp/kotlin/src/main/java/dev/mutwakil/androidide/lsp/kotlin/compiler/modules/KtFileExts.kt @@ -126,6 +126,8 @@ internal inline fun analyzeMaybeDangling( crossinline action: KaSession.() -> R, ): R = withAnalysisLock(priority, cancelChecker) { + // A rebuild disposes the old environment under this lock; a request still holding it ends here. + if (useSiteElement.project.isDisposed) throw CancellationException("Kotlin analysis environment was disposed") if (useSiteElement is KtFile && useSiteElement.isDangling && useSiteElement.copyOrigin != null) { analyzeCopy(useSiteElement, KaDanglingFileResolutionMode.PREFER_SELF, action) } else { diff --git a/lsp/kotlin/src/main/java/dev/mutwakil/androidide/lsp/kotlin/compiler/modules/KtLibraryModule.kt b/lsp/kotlin/src/main/java/dev/mutwakil/androidide/lsp/kotlin/compiler/modules/KtLibraryModule.kt index c2cad8029a..1ceafb01fb 100644 --- a/lsp/kotlin/src/main/java/dev/mutwakil/androidide/lsp/kotlin/compiler/modules/KtLibraryModule.kt +++ b/lsp/kotlin/src/main/java/dev/mutwakil/androidide/lsp/kotlin/compiler/modules/KtLibraryModule.kt @@ -10,7 +10,6 @@ import org.jetbrains.kotlin.analysis.api.projectStructure.KaLibraryModule import org.jetbrains.kotlin.analysis.api.projectStructure.KaLibrarySourceModule import org.jetbrains.kotlin.cli.jvm.modules.CoreJrtFileSystem import org.jetbrains.kotlin.com.intellij.core.CoreApplicationEnvironment -import org.jetbrains.kotlin.com.intellij.openapi.module.Module import org.jetbrains.kotlin.com.intellij.openapi.project.Project import org.jetbrains.kotlin.com.intellij.openapi.vfs.StandardFileSystems.JAR_PROTOCOL import org.jetbrains.kotlin.com.intellij.openapi.vfs.VirtualFile @@ -37,9 +36,9 @@ internal class KtLibraryModule( private val jvmTarget: JvmTarget = DEFAULT_JVM_TARGET, override val librarySources: KaLibrarySourceModule? = null, ) : AbstractKtModule( - project, - dependencies, -), + project, + dependencies, + ), KaLibraryModule { class Builder( private val project: Project, @@ -100,17 +99,7 @@ internal class KtLibraryModule( .flatMap { LibraryUtils.getAllVirtualFilesFromRoot(it, includeRoot = true) } } - @OptIn(KaExperimentalApi::class) - override val baseContentScope: GlobalSearchScope by lazy { - val virtualFileUrls = computeFiles(extended = true).map { it.url }.toSet() - object : GlobalSearchScope(project) { - override fun contains(vf: VirtualFile): Boolean = vf.url in virtualFileUrls - - override fun isSearchInModuleContent(module: Module): Boolean = false - - override fun isSearchInLibraries(): Boolean = true - } - } + override fun computeBaseContentScope(): GlobalSearchScope = LibraryRootsScope(project, computeFiles(extended = false).toSet()) override val libraryName: String get() = id @@ -159,4 +148,4 @@ private fun getVirtualFileForLibraryRoot( // Regular .class files return project.read { VirtualFileManager.getInstance().findFileByNioPath(root) } -} \ No newline at end of file +} diff --git a/lsp/kotlin/src/main/java/dev/mutwakil/androidide/lsp/kotlin/compiler/modules/KtSourceModule.kt b/lsp/kotlin/src/main/java/dev/mutwakil/androidide/lsp/kotlin/compiler/modules/KtSourceModule.kt index 50225a2bc2..27df6bc4ae 100644 --- a/lsp/kotlin/src/main/java/dev/mutwakil/androidide/lsp/kotlin/compiler/modules/KtSourceModule.kt +++ b/lsp/kotlin/src/main/java/dev/mutwakil/androidide/lsp/kotlin/compiler/modules/KtSourceModule.kt @@ -2,7 +2,7 @@ package dev.mutwakil.androidide.lsp.kotlin.compiler.modules import dev.mutwakil.androidide.lsp.kotlin.compiler.DEFAULT_JVM_TARGET import dev.mutwakil.androidide.lsp.kotlin.compiler.DEFAULT_LANGUAGE_VERSION -import dev.mutwakil.androidide.projects.api.ModuleProject +import dev.mutwakil.androidide.lsp.kotlin.compiler.SourceModuleLayout import org.jetbrains.kotlin.analysis.api.KaExperimentalApi import org.jetbrains.kotlin.analysis.api.KaPlatformInterface import org.jetbrains.kotlin.analysis.api.projectStructure.KaSourceModule @@ -15,12 +15,14 @@ import org.jetbrains.kotlin.config.LanguageVersionSettingsImpl import org.jetbrains.kotlin.platform.TargetPlatform import org.jetbrains.kotlin.platform.jvm.JvmPlatforms import org.slf4j.LoggerFactory +import java.nio.file.Path @OptIn(KaPlatformInterface::class) internal class KtSourceModule( project: Project, - val module: ModuleProject, + val layout: SourceModuleLayout, directRegularDependencies: List, + override val directFriendDependencies: List, ) : AbstractSourceModule(project, directRegularDependencies), KaSourceModule { companion object { @@ -30,62 +32,44 @@ internal class KtSourceModule( class Builder( private val project: Project, ) { - lateinit var module: ModuleProject + lateinit var layout: SourceModuleLayout // A set: a jar on both the boot and compile classpath is one shared module (ADFA-6381). private val dependencies = linkedSetOf() + private val friends = linkedSetOf() + fun addDependency(dep: KtModule) { dependencies.add(dep) } - fun build(): KtSourceModule = KtSourceModule(project, module, dependencies.toList()) - } + /** Lets this module use [friend]'s `internal` declarations, as a test module does its main module's. */ + fun addFriend(friend: KtModule) { + friends.add(friend) + } - override val id: String - get() = module.path - - override val contentRoots by lazy { - module - .getSourceDirectories() - .asSequence() - .map { it.toPath() } - .toSet() + fun build(): KtSourceModule = KtSourceModule(project, layout, dependencies.toList(), friends.toList()) } - private val versions by lazy { - val kotlinCompilerSettings = - when { - module.hasJavaProject() -> { - module.javaProject - .kotlinCompilerSettings - } - - module.hasAndroidProject() -> { - module.androidProject - .kotlinCompilerSettings - } - - else -> { - null - } - } + override val id: String + get() = layout.path - if (kotlinCompilerSettings == null) { - return@lazy DEFAULT_LANGUAGE_VERSION to DEFAULT_JVM_TARGET - } + override val contentRoots: Set + get() = layout.sourceRoots + private val versions by lazy { val apiVersion = - LanguageVersion.fromVersionString(kotlinCompilerSettings.apiVersion) - ?: LanguageVersion.fromFullVersionString(kotlinCompilerSettings.apiVersion) + layout.apiVersion?.let { + LanguageVersion.fromVersionString(it) ?: LanguageVersion.fromFullVersionString(it) + } - val jvmTarget = JvmTarget.fromString(kotlinCompilerSettings.jvmTarget) + val jvmTarget = layout.jvmTarget?.let { JvmTarget.fromString(it) } (apiVersion ?: DEFAULT_LANGUAGE_VERSION) to (jvmTarget ?: DEFAULT_JVM_TARGET) } override val name: String - get() = module.name + get() = layout.name @OptIn(KaExperimentalApi::class) override val moduleDescription: String @@ -105,4 +89,4 @@ internal class KtSourceModule( internal fun buildKtSourceModule( project: Project, init: KtSourceModule.Builder.() -> Unit, -): KtSourceModule = KtSourceModule.Builder(project).apply(init).build() \ No newline at end of file +): KtSourceModule = KtSourceModule.Builder(project).apply(init).build() diff --git a/lsp/kotlin/src/main/java/dev/mutwakil/androidide/lsp/kotlin/compiler/modules/LibraryRootsScope.kt b/lsp/kotlin/src/main/java/dev/mutwakil/androidide/lsp/kotlin/compiler/modules/LibraryRootsScope.kt new file mode 100644 index 0000000000..dab86b6ae4 --- /dev/null +++ b/lsp/kotlin/src/main/java/dev/mutwakil/androidide/lsp/kotlin/compiler/modules/LibraryRootsScope.kt @@ -0,0 +1,33 @@ +package dev.mutwakil.androidide.lsp.kotlin.compiler.modules + +import org.jetbrains.kotlin.com.intellij.openapi.module.Module +import org.jetbrains.kotlin.com.intellij.openapi.project.Project +import org.jetbrains.kotlin.com.intellij.openapi.vfs.VirtualFile +import org.jetbrains.kotlin.com.intellij.psi.search.GlobalSearchScope + +/** + * A library scope that holds [roots] and every file below them, decided by walking a file's + * parents instead of by a per-entry set. + * + * A file whose top-most ancestor has the URL of a root also counts, so the entries of a JAR + * replaced on disk, which hang off a new root file, stay in a scope built from the old root. + */ +internal class LibraryRootsScope( + project: Project, + val roots: Set, +) : GlobalSearchScope(project) { + private val rootUrls = roots.mapTo(HashSet()) { it.url } + + override fun contains(file: VirtualFile): Boolean { + var top = file + while (true) { + if (top in roots) return true + top = top.parent ?: break + } + return top.url in rootUrls + } + + override fun isSearchInModuleContent(aModule: Module): Boolean = false + + override fun isSearchInLibraries(): Boolean = true +} diff --git a/lsp/kotlin/src/main/java/dev/mutwakil/androidide/lsp/kotlin/compiler/registrar/AnalysisApiServiceProviders.kt b/lsp/kotlin/src/main/java/dev/mutwakil/androidide/lsp/kotlin/compiler/registrar/AnalysisApiServiceProviders.kt index 2d7651b1da..1c85f4ecfe 100644 --- a/lsp/kotlin/src/main/java/dev/mutwakil/androidide/lsp/kotlin/compiler/registrar/AnalysisApiServiceProviders.kt +++ b/lsp/kotlin/src/main/java/dev/mutwakil/androidide/lsp/kotlin/compiler/registrar/AnalysisApiServiceProviders.kt @@ -72,4 +72,4 @@ internal object AnalysisApiServiceProviders { }.build() val Production = BaseProvider -} \ No newline at end of file +} diff --git a/lsp/kotlin/src/main/java/dev/mutwakil/androidide/lsp/kotlin/compiler/services/DeclarationsProvider.kt b/lsp/kotlin/src/main/java/dev/mutwakil/androidide/lsp/kotlin/compiler/services/DeclarationsProvider.kt index d742adc369..d87c9e8da6 100644 --- a/lsp/kotlin/src/main/java/dev/mutwakil/androidide/lsp/kotlin/compiler/services/DeclarationsProvider.kt +++ b/lsp/kotlin/src/main/java/dev/mutwakil/androidide/lsp/kotlin/compiler/services/DeclarationsProvider.kt @@ -2,7 +2,6 @@ package dev.mutwakil.androidide.lsp.kotlin.compiler.services import dev.mutwakil.androidide.lsp.kotlin.compiler.index.KtSymbolIndex import dev.mutwakil.androidide.lsp.kotlin.compiler.index.ResolutionSideKtFileAccess -import dev.mutwakil.androidide.lsp.kotlin.compiler.index.filesForPackage import dev.mutwakil.androidide.lsp.kotlin.compiler.modules.KtModule import dev.mutwakil.androidide.lsp.kotlin.compiler.read import org.jetbrains.kotlin.analysis.api.platform.declarations.KotlinCompositeDeclarationProvider @@ -15,15 +14,12 @@ import org.jetbrains.kotlin.analysis.api.projectStructure.KaModule import org.jetbrains.kotlin.cli.jvm.index.JavaRoot import org.jetbrains.kotlin.com.intellij.mock.MockProject import org.jetbrains.kotlin.com.intellij.openapi.project.Project -import org.jetbrains.kotlin.com.intellij.openapi.vfs.VirtualFileManager import org.jetbrains.kotlin.com.intellij.psi.search.GlobalSearchScope -import org.jetbrains.kotlin.com.intellij.psi.util.PsiTreeUtil import org.jetbrains.kotlin.fileClasses.javaFileFacadeFqName import org.jetbrains.kotlin.name.CallableId import org.jetbrains.kotlin.name.ClassId import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.name.Name -import org.jetbrains.kotlin.psi.KtCallableDeclaration import org.jetbrains.kotlin.psi.KtClassLikeDeclaration import org.jetbrains.kotlin.psi.KtClassOrObject import org.jetbrains.kotlin.psi.KtFile @@ -31,8 +27,6 @@ import org.jetbrains.kotlin.psi.KtNamedFunction import org.jetbrains.kotlin.psi.KtProperty import org.jetbrains.kotlin.psi.KtScript import org.jetbrains.kotlin.psi.KtTypeAlias -import org.jetbrains.kotlin.psi.psiUtil.isTopLevelKtOrJavaMember -import java.nio.file.Paths internal class DeclarationProviderFactory : KtLspService, @@ -88,32 +82,20 @@ internal abstract class AbstractDeclarationProvider( // that means we expect the kotlin stdlib to be included on the project emptyList() - override fun findFilesForFacadeByPackage(packageFqName: FqName): Collection = ktFilesForPackage(packageFqName).toList() + override fun findFilesForFacadeByPackage(packageFqName: FqName): Collection = + project.read { ktFilesForPackage(packageFqName).toList() } override fun findFilesForScript(scriptFqName: FqName): Collection = - ktFilesForPackage(scriptFqName).mapNotNull { it.script }.toList() + project.read { ktFilesForPackage(scriptFqName).mapNotNull { it.script }.toList() } override fun getAllClassesByClassId(classId: ClassId): Collection = - ktFilesForPackage(classId.packageFqName) - .flatMap { - project.read { - PsiTreeUtil.collectElementsOfType(it, KtClassOrObject::class.java).asSequence() - } - }.filter { it.getClassId() == classId } - .toList() + project.read { ktFilesForPackage(classId.packageFqName).classesWithId(classId).toList() } override fun getAllTypeAliasesByClassId(classId: ClassId): Collection = - ktFilesForPackage(classId.packageFqName) - .flatMap { - project.read { - PsiTreeUtil.collectElementsOfType(it, KtTypeAlias::class.java).asSequence() - } - }.filter { it.getClassId() == classId } - .toList() + project.read { ktFilesForPackage(classId.packageFqName).typeAliasesWithId(classId).toList() } override fun getClassLikeDeclarationByClassId(classId: ClassId): KtClassLikeDeclaration? = - getAllClassesByClassId(classId).firstOrNull() - ?: getAllTypeAliasesByClassId(classId).firstOrNull() + project.read { ktFilesForPackage(classId.packageFqName).classLikeWithId(classId) } override fun getTopLevelCallableFiles(callableId: CallableId): Collection = buildSet { @@ -122,50 +104,16 @@ internal abstract class AbstractDeclarationProvider( } override fun getTopLevelFunctions(callableId: CallableId): Collection = - ktFilesForPackage(callableId.packageName) - .flatMap { - project.read { - PsiTreeUtil - .collectElementsOfType(it, KtNamedFunction::class.java) - .asSequence() - } - }.filter { it.isTopLevel } - .filter { it.nameAsName == callableId.callableName } - .toList() + project.read { ktFilesForPackage(callableId.packageName).topLevelFunctions(callableId.callableName).toList() } override fun getTopLevelKotlinClassLikeDeclarationNamesInPackage(packageFqName: FqName): Set = - ktFilesForPackage(packageFqName) - .flatMap { - project.read { - PsiTreeUtil - .collectElementsOfType(it, KtClassLikeDeclaration::class.java) - .asSequence() - } - }.filter { it.isTopLevelKtOrJavaMember() } - .mapNotNull { it.nameAsName } - .toSet() + project.read { ktFilesForPackage(packageFqName).topLevelClassLikeNames().toSet() } override fun getTopLevelCallableNamesInPackage(packageFqName: FqName): Set = - ktFilesForPackage(packageFqName) - .flatMap { - project.read { - PsiTreeUtil - .collectElementsOfType(it, KtCallableDeclaration::class.java) - .asSequence() - } - }.filter { it.isTopLevelKtOrJavaMember() } - .mapNotNull { it.nameAsName } - .toSet() + project.read { ktFilesForPackage(packageFqName).topLevelCallableNames().toSet() } override fun getTopLevelProperties(callableId: CallableId): Collection = - ktFilesForPackage(callableId.packageName) - .flatMap { - project.read { - PsiTreeUtil.collectElementsOfType(it, KtProperty::class.java).asSequence() - } - }.filter { it.isTopLevel } - .filter { it.nameAsName == callableId.callableName } - .toList() + project.read { ktFilesForPackage(callableId.packageName).topLevelProperties(callableId.callableName).toList() } } internal class DeclarationProvider( @@ -176,11 +124,16 @@ internal class DeclarationProvider( override val hasSpecificCallablePackageNamesComputation = false override val hasSpecificClassifierPackageNamesComputation = false - @OptIn(ResolutionSideKtFileAccess::class) - override fun ktFilesForPackage(fqName: FqName): Sequence = - index - .filesForPackage(fqName.asString()) - .mapNotNull { VirtualFileManager.getInstance().findFileByNioPath(Paths.get(it.filePath)) } - .filter { it in scope } - .mapNotNull { index.getKtFile(it) } + override fun ktFilesForPackage(fqName: FqName): Sequence = index.ktFilesInPackage(fqName, scope) } + +/** The Kotlin files in [scope] that the file index records under [packageFqName]. */ +@OptIn(ResolutionSideKtFileAccess::class) +internal fun KtSymbolIndex.ktFilesInPackage( + packageFqName: FqName, + scope: GlobalSearchScope, +): Sequence = + sourceFilesForPackage(packageFqName) + .asSequence() + .filter { it in scope } + .mapNotNull { getKtFile(it) } diff --git a/lsp/kotlin/src/main/java/dev/mutwakil/androidide/lsp/kotlin/compiler/services/DirectInheritorsProvider.kt b/lsp/kotlin/src/main/java/dev/mutwakil/androidide/lsp/kotlin/compiler/services/DirectInheritorsProvider.kt index 0a07fe30a7..10ca5c8bd7 100644 --- a/lsp/kotlin/src/main/java/dev/mutwakil/androidide/lsp/kotlin/compiler/services/DirectInheritorsProvider.kt +++ b/lsp/kotlin/src/main/java/dev/mutwakil/androidide/lsp/kotlin/compiler/services/DirectInheritorsProvider.kt @@ -16,6 +16,7 @@ import org.jetbrains.kotlin.cli.jvm.index.JavaRoot import org.jetbrains.kotlin.com.intellij.mock.MockProject import org.jetbrains.kotlin.com.intellij.openapi.project.Project import org.jetbrains.kotlin.com.intellij.psi.search.GlobalSearchScope +import org.jetbrains.kotlin.com.intellij.psi.util.PsiTreeUtil import org.jetbrains.kotlin.fir.declarations.FirClass import org.jetbrains.kotlin.fir.resolve.providers.symbolProvider import org.jetbrains.kotlin.fir.symbols.SymbolInternals @@ -24,6 +25,8 @@ import org.jetbrains.kotlin.name.ClassId import org.jetbrains.kotlin.name.Name import org.jetbrains.kotlin.psi.KtClass import org.jetbrains.kotlin.psi.KtClassOrObject +import org.jetbrains.kotlin.psi.KtDeclaration +import org.jetbrains.kotlin.psi.KtFile import org.jetbrains.kotlin.psi.KtNullableType import org.jetbrains.kotlin.psi.KtTreeVisitorVoid import org.jetbrains.kotlin.psi.KtTypeAlias @@ -40,9 +43,6 @@ internal class DirectInheritorsProvider : private lateinit var modules: List private lateinit var project: Project - private val classesBySupertypeName = mutableMapOf>() - private val inheritableTypeAliasesByAliasedName = mutableMapOf>() - override fun setupWith( project: MockProject, index: KtSymbolIndex, @@ -60,16 +60,16 @@ internal class DirectInheritorsProvider : scope: GlobalSearchScope, includeLocalInheritors: Boolean, ): Iterable { - computeIndex() + val inheritors = computeIndex() val classId = ktClass.getClassId() ?: return emptyList() val baseModule = KotlinProjectStructureProvider.getModule(project, ktClass, useSiteModule = null) val baseFirClass = classId.toFirSymbol(baseModule)?.fir as? FirClass ?: return emptyList() val baseClassNames = mutableSetOf(classId.shortClassName) - calculateAliases(classId.shortClassName, baseClassNames) + calculateAliases(inheritors.inheritableTypeAliasesByAliasedName, classId.shortClassName, baseClassNames) - val possibleInheritors = baseClassNames.flatMap { classesBySupertypeName[it].orEmpty() } + val possibleInheritors = baseClassNames.flatMap { inheritors.classesBySupertypeName[it].orEmpty() } if (possibleInheritors.isEmpty()) { return emptyList() } @@ -77,11 +77,47 @@ internal class DirectInheritorsProvider : return possibleInheritors.filter { isValidInheritor(it, baseFirClass, scope, includeLocalInheritors) } } - // Let's say this operation is not frequently called, if we discover it's not the case we should cache it + /* + * Reads only the files of [ktClass]'s package. The sealed inheritors search calls this, and the + * whole-project walk of getDirectKotlinInheritors parsed every source file on each call: ~18 s of + * the first completion after a cold open on a phone. + */ + @OptIn(SymbolInternals::class) + override fun getSamePackageDirectKotlinInheritors( + ktClass: KtClass, + scope: GlobalSearchScope, + includeLocalInheritors: Boolean, + ): Iterable { + val classId = ktClass.getClassId() ?: return emptyList() + val baseModule = KotlinProjectStructureProvider.getModule(project, ktClass, useSiteModule = null) + val baseFirClass = classId.toFirSymbol(baseModule)?.fir as? FirClass ?: return emptyList() + + /* + * Every class with a supertype is a candidate: FIR's subclass check expands type aliases, so + * an inheritor written against an alias declared in another package is still found. + */ + return index + .ktFilesInPackage(classId.packageFqName, scope) + .flatMap { it.classesOrObjects(includeLocalInheritors) } + .filter { it.superTypeListEntries.isNotEmpty() } + .filter { isValidInheritor(it, baseFirClass, scope, includeLocalInheritors) } + .toList() + } + + /* + * Built per call and dropped on return: each KtClassOrObject pins its file's whole PSI tree, so a + * long-lived copy keeps every source file's tree in the heap. + */ + private class InheritorsIndex { + val classesBySupertypeName = mutableMapOf>() + val inheritableTypeAliasesByAliasedName = mutableMapOf>() + } + @OptIn(ResolutionSideKtFileAccess::class) - private fun computeIndex() { - classesBySupertypeName.clear() - inheritableTypeAliasesByAliasedName.clear() + private fun computeIndex(): InheritorsIndex { + val result = InheritorsIndex() + val classesBySupertypeName = result.classesBySupertypeName + val inheritableTypeAliasesByAliasedName = result.inheritableTypeAliasesByAliasedName modules .asFlatSequence() @@ -114,17 +150,19 @@ internal class DirectInheritorsProvider : }, ) } + return result } private fun calculateAliases( + aliasesByAliasedName: Map>, aliasedName: Name, aliases: MutableSet, ) { - inheritableTypeAliasesByAliasedName[aliasedName].orEmpty().forEach { alias -> + aliasesByAliasedName[aliasedName].orEmpty().forEach { alias -> val aliasName = alias.nameAsSafeName val isNewAliasName = aliases.add(aliasName) if (isNewAliasName) { - calculateAliases(aliasName, aliases) + calculateAliases(aliasesByAliasedName, aliasName, aliases) } } } @@ -186,3 +224,14 @@ private fun findInheritableSimpleNames(typeElement: KtTypeElement): List } } } + +private fun KtFile.classesOrObjects(includeLocal: Boolean): List = + if (includeLocal) { + PsiTreeUtil.collectElementsOfType(this, KtClassOrObject::class.java).toList() + } else { + declarations.nonLocalClassesOrObjects() + } + +// Descends through class bodies only, so lazily parsed function bodies stay unparsed. +private fun List.nonLocalClassesOrObjects(): List = + filterIsInstance().flatMap { listOf(it) + it.declarations.nonLocalClassesOrObjects() } diff --git a/lsp/kotlin/src/main/java/dev/mutwakil/androidide/lsp/kotlin/compiler/services/ProjectStructureProvider.kt b/lsp/kotlin/src/main/java/dev/mutwakil/androidide/lsp/kotlin/compiler/services/ProjectStructureProvider.kt index e32a12e7b9..24d6b79908 100644 --- a/lsp/kotlin/src/main/java/dev/mutwakil/androidide/lsp/kotlin/compiler/services/ProjectStructureProvider.kt +++ b/lsp/kotlin/src/main/java/dev/mutwakil/androidide/lsp/kotlin/compiler/services/ProjectStructureProvider.kt @@ -10,6 +10,7 @@ import org.jetbrains.kotlin.analysis.api.platform.projectStructure.KotlinProject import org.jetbrains.kotlin.analysis.api.platform.projectStructure.KotlinProjectStructureProviderBase import org.jetbrains.kotlin.analysis.api.projectStructure.KaModule import org.jetbrains.kotlin.analysis.api.projectStructure.KaNotUnderContentRootModule +import org.jetbrains.kotlin.analysis.api.projectStructure.copyOrigin import org.jetbrains.kotlin.analysis.low.level.api.fir.util.originalKtFile import org.jetbrains.kotlin.cli.jvm.index.JavaRoot import org.jetbrains.kotlin.com.intellij.mock.MockProject @@ -21,12 +22,12 @@ import java.nio.file.Paths import java.util.concurrent.ConcurrentHashMap import kotlin.io.path.pathString -internal class ProjectStructureProvider : KtLspService, KotlinProjectStructureProviderBase() { - +internal class ProjectStructureProvider : + KotlinProjectStructureProviderBase(), + KtLspService { companion object { - fun getInstance(project: Project): ProjectStructureProvider { - return KotlinProjectStructureProvider.getInstance(project) as ProjectStructureProvider - } + fun getInstance(project: Project): ProjectStructureProvider = + KotlinProjectStructureProvider.getInstance(project) as ProjectStructureProvider } private lateinit var modules: List @@ -35,7 +36,10 @@ internal class ProjectStructureProvider : KtLspService, KotlinProjectStructurePr private val inMemoryVfToModule = ConcurrentHashMap() private val pathToInMemoryVf = ConcurrentHashMap() - fun registerInMemoryFile(sourcePath: String, vf: VirtualFile) { + fun registerInMemoryFile( + sourcePath: String, + vf: VirtualFile, + ) { pathToInMemoryVf.remove(sourcePath)?.let { inMemoryVfToModule.remove(it) } val module = findModuleForSourceId(sourcePath) ?: return @@ -61,7 +65,7 @@ internal class ProjectStructureProvider : KtLspService, KotlinProjectStructurePr project: MockProject, index: KtSymbolIndex, modules: List, - libraryRoots: List + libraryRoots: List, ) { this.modules = modules this.project = project @@ -69,22 +73,30 @@ internal class ProjectStructureProvider : KtLspService, KotlinProjectStructurePr override fun getModule( element: PsiElement, - useSiteModule: KaModule? + useSiteModule: KaModule?, ): KaModule = getModuleImpl(element, useSiteModule) private fun getModuleImpl( element: PsiElement, - useSiteModule: KaModule? + useSiteModule: KaModule?, ): KaModule { - val virtualFile = element.containingFile?.virtualFile - ?: return notUnderContentRootModuleWithoutPsiFile + // A copy in its original's source module makes FIR see every declaration twice; give it a dangling module. + val containingFile = element.containingFile + if (containingFile is KtFile && containingFile.copyOrigin != null) { + computeSpecialModule(containingFile)?.let { return it } + } + + val virtualFile = + containingFile?.virtualFile + ?: return notUnderContentRootModuleWithoutPsiFile // Fast path: in-memory file registered by onFileContentChanged. inMemoryVfToModule[virtualFile]?.let { return it } - val backingFilePath = (element.containingFile as? KtFile)?.let { - it.backingFilePath ?: it.originalKtFile?.backingFilePath - } + val backingFilePath = + (element.containingFile as? KtFile)?.let { + it.backingFilePath ?: it.originalKtFile?.backingFilePath + } if (backingFilePath != null) { findModuleForSourceId(backingFilePath.pathString)?.let { return it } @@ -148,14 +160,12 @@ internal class ProjectStructureProvider : KtLspService, KotlinProjectStructurePr } @OptIn(KaPlatformInterface::class) - override fun getNotUnderContentRootModule(project: Project): KaNotUnderContentRootModule { - return notUnderContentRootModuleWithoutPsiFile - } + override fun getNotUnderContentRootModule(project: Project): KaNotUnderContentRootModule = notUnderContentRootModuleWithoutPsiFile private fun searchVirtualFileInModule( vf: VirtualFile, module: KaModule, - visited: MutableSet + visited: MutableSet, ): KaModule? { if (visited.contains(module)) return null if (module.contentScope.contains(vf)) return module diff --git a/lsp/kotlin/src/main/java/dev/mutwakil/androidide/lsp/kotlin/compiler/services/TopLevelDeclarations.kt b/lsp/kotlin/src/main/java/dev/mutwakil/androidide/lsp/kotlin/compiler/services/TopLevelDeclarations.kt new file mode 100644 index 0000000000..d7d1a33aff --- /dev/null +++ b/lsp/kotlin/src/main/java/dev/mutwakil/androidide/lsp/kotlin/compiler/services/TopLevelDeclarations.kt @@ -0,0 +1,72 @@ +package dev.mutwakil.androidide.lsp.kotlin.compiler.services + +import org.jetbrains.kotlin.name.ClassId +import org.jetbrains.kotlin.name.Name +import org.jetbrains.kotlin.psi.KtCallableDeclaration +import org.jetbrains.kotlin.psi.KtClassLikeDeclaration +import org.jetbrains.kotlin.psi.KtClassOrObject +import org.jetbrains.kotlin.psi.KtDeclaration +import org.jetbrains.kotlin.psi.KtFile +import org.jetbrains.kotlin.psi.KtNamedFunction +import org.jetbrains.kotlin.psi.KtProperty +import org.jetbrains.kotlin.psi.KtTypeAlias + +/* + * Declaration lookups that read only KtFile.declarations instead of walking the whole PSI tree. + * Local declarations have no ClassId and are never top-level, so they never match. + * + * The returned sequences are lazy and touch PSI while iterated, so callers must fully consume + * them under the project read lock. The name sequences may contain duplicates. + */ + +internal fun Sequence.classesWithId(classId: ClassId): Sequence = + declarationsAndNested() + .filterIsInstance() + .filter { it.getClassId() == classId } + +internal fun Sequence.typeAliasesWithId(classId: ClassId): Sequence = + declarationsAndNested() + .filterIsInstance() + .filter { it.getClassId() == classId } + +/** The class, or failing that the type alias, with [classId], found in one walk of the files. */ +internal fun Sequence.classLikeWithId(classId: ClassId): KtClassLikeDeclaration? { + var typeAlias: KtTypeAlias? = null + for (declaration in declarationsAndNested()) { + if (declaration !is KtClassLikeDeclaration || declaration.getClassId() != classId) continue + if (declaration is KtClassOrObject) return declaration + if (typeAlias == null) typeAlias = declaration as? KtTypeAlias + } + return typeAlias +} + +internal fun Sequence.topLevelFunctions(name: Name): Sequence = + flatMap { it.declarations } + .filterIsInstance() + .filter { it.nameAsName == name } + +internal fun Sequence.topLevelProperties(name: Name): Sequence = + flatMap { it.declarations } + .filterIsInstance() + .filter { it.nameAsName == name } + +internal fun Sequence.topLevelCallableNames(): Sequence = + flatMap { it.declarations } + .filterIsInstance() + .mapNotNull { it.nameAsName } + +internal fun Sequence.topLevelClassLikeNames(): Sequence = + flatMap { it.declarations } + .filterIsInstance() + .mapNotNull { it.nameAsName } + +private fun Sequence.declarationsAndNested(): Sequence = + flatMap { it.declarations }.flatMap { it.withNestedDeclarations() } + +private fun KtDeclaration.withNestedDeclarations(): Sequence = + sequence { + yield(this@withNestedDeclarations) + if (this@withNestedDeclarations is KtClassOrObject) { + for (member in declarations) yieldAll(member.withNestedDeclarations()) + } + } diff --git a/lsp/kotlin/src/main/java/dev/mutwakil/androidide/lsp/kotlin/compiler/vfs/ListingJarFileSystem.kt b/lsp/kotlin/src/main/java/dev/mutwakil/androidide/lsp/kotlin/compiler/vfs/ListingJarFileSystem.kt new file mode 100644 index 0000000000..f87ebfad11 --- /dev/null +++ b/lsp/kotlin/src/main/java/dev/mutwakil/androidide/lsp/kotlin/compiler/vfs/ListingJarFileSystem.kt @@ -0,0 +1,111 @@ +package dev.mutwakil.androidide.lsp.kotlin.compiler.vfs + +import dev.mutwakil.androidide.zipfs2.listing.JarListingCache +import org.jetbrains.kotlin.com.intellij.openapi.vfs.DeprecatedVirtualFileSystem +import org.jetbrains.kotlin.com.intellij.openapi.vfs.StandardFileSystems +import org.jetbrains.kotlin.com.intellij.openapi.vfs.VirtualFile +import org.slf4j.LoggerFactory +import java.io.IOException +import java.nio.file.NoSuchFileException +import java.nio.file.Path +import java.util.concurrent.ConcurrentHashMap + +private val logger = LoggerFactory.getLogger(ListingJarFileSystem::class.java) + +private const val JAR_SEPARATOR = "!/" + +/** + * A read-only `jar` file system that serves JAR entries from the shared [JarListing][dev.mutwakil.androidide.zipfs2.listing.JarListing]s + * of [cache], creating a [VirtualFile] for an entry only when something asks for it. + * + * Every lookup checks the JAR on disk through [cache], so a JAR replaced in place gets a fresh + * handler, and the files of the old one report [VirtualFile.isValid] as false. + */ +class ListingJarFileSystem( + private val cache: JarListingCache, +) : DeprecatedVirtualFileSystem() { + private val handlers = ConcurrentHashMap() + + init { + cache.addListener { jar -> handlers.remove(jar.toString())?.drop() } + } + + override fun getProtocol(): String = StandardFileSystems.JAR_PROTOCOL + + /** + * Returns the file at [path], written `!/`, or null if the JAR cannot be read + * or has no such entry. + * + * @throws IllegalArgumentException if [path] has no `!/` separator + */ + override fun findFileByPath(path: String): VirtualFile? { + val separator = path.indexOf(JAR_SEPARATOR) + require(separator >= 0) { "Path in JarFileSystem must contain a separator: $path" } + val jar = Path.of(path.substring(0, separator)).toAbsolutePath().normalize() + return handlerFor(jar)?.findFile(path.substring(separator + JAR_SEPARATOR.length)) + } + + override fun refresh(asynchronous: Boolean) = Unit + + override fun refreshAndFindFileByPath(path: String): VirtualFile? = findFileByPath(path) + + private fun handlerFor(jar: Path): ListingJarHandler? = snapshotOf(jar)?.let { handlerFor(jar.toString(), it) } + + /** + * Returns the handler for the JAR at [key], replacing the current one only if [snapshot] was + * built after it. + * + * A handler is returned only if it matches the snapshot the cache holds afterwards. Otherwise + * another consumer of the cache rebuilt the listing in between, and the listener may already + * have run, so the stale handler is removed and the lookup is retried once; if the JAR changes + * again, this returns null. + */ + internal fun handlerFor( + key: String, + snapshot: JarListingCache.Snapshot, + ): ListingJarHandler? { + val handler = install(key, snapshot) + if (isCurrent(handler)) return handler + retire(key, handler) + val retried = install(key, snapshotOf(Path.of(key)) ?: return null) + if (isCurrent(retried)) return retried + retire(key, retried) + logger.warn("JAR {} changed again while it was being looked up", key) + return null + } + + private fun snapshotOf(jar: Path): JarListingCache.Snapshot? = + try { + cache.snapshot(jar) + } catch (e: IOException) { + if (e is NoSuchFileException) handlers.remove(jar.toString())?.drop() + logger.warn("Cannot list JAR {}", jar, e) + null + } + + private fun install( + key: String, + snapshot: JarListingCache.Snapshot, + ): ListingJarHandler = + handlers.compute(key) { _, old -> + if (old != null && old.snapshot.generation() >= snapshot.generation()) { + old + } else { + old?.drop() + ListingJarHandler(this, key, snapshot) + } + }!! + + /** Reads only the cache's map: no stat and no path lock, so it is safe after any lookup. */ + private fun isCurrent(handler: ListingJarHandler): Boolean { + val current = cache.peek(Path.of(handler.jarPath)) ?: return false + return current.generation() <= handler.snapshot.generation() + } + + private fun retire( + key: String, + handler: ListingJarHandler, + ) { + if (handlers.remove(key, handler)) handler.drop() + } +} diff --git a/lsp/kotlin/src/main/java/dev/mutwakil/androidide/lsp/kotlin/compiler/vfs/ListingJarHandler.kt b/lsp/kotlin/src/main/java/dev/mutwakil/androidide/lsp/kotlin/compiler/vfs/ListingJarHandler.kt new file mode 100644 index 0000000000..db68583933 --- /dev/null +++ b/lsp/kotlin/src/main/java/dev/mutwakil/androidide/lsp/kotlin/compiler/vfs/ListingJarHandler.kt @@ -0,0 +1,247 @@ +package dev.mutwakil.androidide.lsp.kotlin.compiler.vfs + +import dev.mutwakil.androidide.zipfs2.listing.JarListing +import dev.mutwakil.androidide.zipfs2.listing.JarListingCache +import org.jetbrains.kotlin.com.intellij.util.containers.ContainerUtil +import org.slf4j.LoggerFactory +import java.io.FileNotFoundException +import java.io.IOException +import java.io.RandomAccessFile +import java.util.zip.DataFormatException +import java.util.zip.Inflater +import java.util.zip.ZipException + +private val logger = LoggerFactory.getLogger(ListingJarHandler::class.java) + +/** + * Serves the entries of one JAR, as listed by [snapshot], to [fileSystem], and keeps the + * [ListingJarVirtualFile]s it has created for as long as something references them. + * + * Entry contents are read through one file handle per handler, opened on the first read and + * closed by [drop]. The open handle keeps reading the file the listing was built from even if the + * JAR is replaced by a rename. + */ +internal class ListingJarHandler( + val fileSystem: ListingJarFileSystem, + val jarPath: String, + val snapshot: JarListingCache.Snapshot, +) { + val listing: JarListing = snapshot.listing() + + /** The JAR's modification time in milliseconds, which `CoreJarVirtualFile` reports for every file entry. */ + val jarTimeStamp: Long = Math.floorDiv(snapshot.modifiedNanos(), NANOS_PER_MILLI) + + private val files = ContainerUtil.createIntKeyWeakValueMap() + + private val jarLock = Any() + + /** Guarded by [jarLock]; a `RandomAccessFile`, unlike a `FileChannel`, is not closed by a thread interrupt. */ + private var jar: RandomAccessFile? = null + + @Volatile + var isValid = true + private set + + /** Returns the file for [entryPath], relative to the JAR root, or null if there is no such entry. */ + fun findFile(entryPath: String): ListingJarVirtualFile? { + val name = normalize(entryPath) + val index = if (name == "/") ROOT else listing.find(name) + return if (index < 0) null else fileAt(index) + } + + /** Returns the child of the directory at [dir] named [name], or null if it has none. */ + fun findChild( + dir: Int, + name: String, + ): ListingJarVirtualFile? { + if (name.isEmpty() || '/' in name) return null + val prefix = if (dir == ROOT) "" else listing.name(dir) + val index = listing.find("$prefix/$name") + return if (index < 0) null else fileAt(index) + } + + /** Returns the files for the children of the directory at [dir]. */ + fun childrenOf(dir: Int): List { + val children = mutableListOf() + var child = listing.firstChild(dir) + while (child != -1) { + children.add(fileAt(child)) + child = listing.nextSibling(child) + } + return children + } + + /** Returns the file for the entry at [index], creating it and its missing parents if needed. */ + fun fileAt(index: Int): ListingJarVirtualFile = + synchronized(files) { + files[index] ?: create(index).also { files.put(index, it) } + } + + /** + * Reads the uncompressed bytes of the entry at [index] from the JAR. + * + * @throws IOException if this handler was dropped, the JAR on disk no longer matches the + * listing, or the entry cannot be read + */ + fun contentsOf(index: Int): ByteArray { + if (listing.isDirectory(index)) throw FileNotFoundException("$jarPath!${listing.name(index)} is a directory") + val size = listing.size(index) + if (size > MAX_ENTRY_SIZE) throw ZipException("$jarPath!${listing.name(index)} is too large: $size bytes") + return when (val method = listing.method(index)) { + METHOD_STORED -> { + readCompressed(index, extra = 0) + } + + METHOD_DEFLATED -> { + // The output array is sized from metadata, so refuse a size no deflate stream of this length can produce. + if (size > (listing.compressedSize(index) + 1) * MAX_DEFLATE_RATIO) { + throw ZipException("$jarPath!${listing.name(index)}: $size bytes cannot inflate from ${listing.compressedSize(index)}") + } + inflate(readCompressed(index, extra = 1), size.toInt(), index) + } + + else -> { + throw ZipException("$jarPath!${listing.name(index)} has unsupported method $method") + } + } + } + + /** + * Marks every file of this handler invalid and closes its file handle; called once the JAR's + * listing is dropped. + * + * Created files stay cached, so a file reached from a dead one is still the same object. + */ + fun drop() { + synchronized(jarLock) { + isValid = false + try { + jar?.close() + } catch (e: IOException) { + logger.warn("Cannot close JAR {}", jarPath, e) + } + jar = null + } + } + + /** Returns how many created files are still referenced. */ + fun createdFileCount(): Int = synchronized(files) { files.size() } + + private fun create(index: Int): ListingJarVirtualFile { + val parent = listing.parent(index) + return ListingJarVirtualFile(this, index, if (parent < 0) null else fileAt(parent)) + } + + /** Reads the entry's raw data, followed by [extra] zero bytes, after checking its local header. */ + private fun readCompressed( + index: Int, + extra: Int, + ): ByteArray { + val compressedSize = listing.compressedSize(index) + if (compressedSize > MAX_ENTRY_SIZE) throw ZipException("$jarPath!${listing.name(index)} is too large: $compressedSize bytes") + // Checked before allocating, so a corrupt central directory cannot claim more heap than the file holds. + if (listing.localHeaderOffset(index) + LOC_HEADER_SIZE + compressedSize > snapshot.size()) { + throw ZipException("$jarPath!${listing.name(index)}: $compressedSize bytes run past the end of the JAR") + } + val data = ByteArray(compressedSize.toInt() + extra) + val header = ByteArray(LOC_HEADER_SIZE) + synchronized(jarLock) { + val file = openLocked() + val offset = listing.localHeaderOffset(index) + file.seek(offset) + file.readFully(header) + if (u32(header, 0) != LOC_SIGNATURE) throw ZipException("$jarPath!${listing.name(index)}: bad local header") + val name = ByteArray(u16(header, LOC_NAME_LENGTH)) + file.readFully(name) + if (!namesMatch(name, index)) throw IOException("$jarPath changed on disk: ${listing.name(index)} is not at its listed offset") + file.seek(offset + LOC_HEADER_SIZE + name.size + u16(header, LOC_EXTRA_LENGTH)) + file.readFully(data, 0, compressedSize.toInt()) + } + return data + } + + /** Returns whether a local header's raw [name] is the listed name of the entry at [index]. */ + private fun namesMatch( + name: ByteArray, + index: Int, + ): Boolean { + val listed = listing.nameBytes(index) + if (name.size == listed.size - 1 && name.contentEquals(listed.copyOfRange(1, listed.size))) return true + // Listed names are normalized; compare a raw name with odd slashes the same way. + return "/" + + name + .decodeToString() + .split('/') + .filter { it.isNotEmpty() } + .joinToString("/") == listing.name(index) + } + + private fun openLocked(): RandomAccessFile { + if (!isValid) throw IOException("$jarPath was replaced on disk") + jar?.let { return it } + val opened = RandomAccessFile(jarPath, "r") + try { + if (opened.length() != snapshot.size()) throw IOException("$jarPath changed on disk since it was listed") + } catch (e: IOException) { + opened.close() + throw e + } + jar = opened + return opened + } + + /** Inflates [compressed], whose trailing zero byte is the dummy input a nowrap `Inflater` may need. */ + private fun inflate( + compressed: ByteArray, + size: Int, + index: Int, + ): ByteArray { + val out = ByteArray(size) + val inflater = Inflater(true) + try { + inflater.setInput(compressed) + var read = 0 + while (read < size) { + val n = + try { + inflater.inflate(out, read, size - read) + } catch (e: DataFormatException) { + throw ZipException("$jarPath!${listing.name(index)}: corrupt deflate data").apply { initCause(e) } + } + if (n == 0 && (inflater.finished() || inflater.needsInput() || inflater.needsDictionary())) break + read += n + } + if (read != size) throw ZipException("$jarPath!${listing.name(index)}: inflated $read of $size bytes") + } finally { + inflater.end() + } + return out + } + + private fun normalize(entryPath: String): String = "/" + entryPath.split('/').filter { it.isNotEmpty() }.joinToString("/") + + private companion object { + const val ROOT = 0 + const val NANOS_PER_MILLI = 1_000_000L + const val MAX_ENTRY_SIZE = Int.MAX_VALUE - 16L + + // Deflate's upper bound: a 258-byte match costs at least 2 bits (1-bit length and distance codes). + const val MAX_DEFLATE_RATIO = 1032L + const val METHOD_STORED = 0 + const val METHOD_DEFLATED = 8 + const val LOC_SIGNATURE = 0x04034b50L + const val LOC_HEADER_SIZE = 30 + const val LOC_NAME_LENGTH = 26 + const val LOC_EXTRA_LENGTH = 28 + + fun u16( + bytes: ByteArray, + at: Int, + ): Int = (bytes[at].toInt() and 0xFF) or ((bytes[at + 1].toInt() and 0xFF) shl 8) + + fun u32( + bytes: ByteArray, + at: Int, + ): Long = (u16(bytes, at).toLong()) or (u16(bytes, at + 2).toLong() shl 16) + } +} diff --git a/lsp/kotlin/src/main/java/dev/mutwakil/androidide/lsp/kotlin/compiler/vfs/ListingJarVirtualFile.kt b/lsp/kotlin/src/main/java/dev/mutwakil/androidide/lsp/kotlin/compiler/vfs/ListingJarVirtualFile.kt new file mode 100644 index 0000000000..57b45014de --- /dev/null +++ b/lsp/kotlin/src/main/java/dev/mutwakil/androidide/lsp/kotlin/compiler/vfs/ListingJarVirtualFile.kt @@ -0,0 +1,76 @@ +package dev.mutwakil.androidide.lsp.kotlin.compiler.vfs + +import org.jetbrains.kotlin.com.intellij.openapi.util.io.BufferExposingByteArrayInputStream +import org.jetbrains.kotlin.com.intellij.openapi.util.io.FileUtil +import org.jetbrains.kotlin.com.intellij.openapi.vfs.VirtualFile +import org.jetbrains.kotlin.com.intellij.openapi.vfs.VirtualFileSystem +import java.io.InputStream +import java.io.OutputStream + +/** + * A JAR entry, or the JAR root, served from a [ListingJarHandler]. + * + * Paths, lengths and time stamps follow IntelliJ's `CoreJarVirtualFile`: a directory has length + * -1 and time stamp -1, and a file has the JAR's modification time. + */ +internal class ListingJarVirtualFile( + val handler: ListingJarHandler, + private val index: Int, + private val parent: ListingJarVirtualFile?, +) : VirtualFile() { + private val name = handler.listing.shortName(index) + + private val path: String = + if (parent == null) { + FileUtil.toSystemIndependentName(handler.jarPath) + "!/" + } else { + parent.path.let { if (it.endsWith('/')) it + name else "$it/$name" } + } + + private val isDirectory = handler.listing.isDirectory(index) + + override fun getName(): String = name + + override fun getFileSystem(): VirtualFileSystem = handler.fileSystem + + override fun getPath(): String = path + + override fun isWritable(): Boolean = false + + override fun isDirectory(): Boolean = isDirectory + + override fun isValid(): Boolean = handler.isValid + + override fun getParent(): VirtualFile? = parent + + override fun getChildren(): Array = if (isDirectory) handler.childrenOf(index).toTypedArray() else EMPTY_ARRAY + + override fun findChild(name: String): VirtualFile? = if (isDirectory) handler.findChild(index, name) else null + + override fun getOutputStream( + requestor: Any?, + newModificationStamp: Long, + newTimeStamp: Long, + ): OutputStream = throw UnsupportedOperationException("JarFileSystem is read-only") + + override fun contentsToByteArray(): ByteArray = handler.contentsOf(index) + + override fun getTimeStamp(): Long = if (isDirectory) DIRECTORY_STAMP else handler.jarTimeStamp + + override fun getLength(): Long = if (isDirectory) DIRECTORY_LENGTH else handler.listing.size(index) + + override fun refresh( + asynchronous: Boolean, + recursive: Boolean, + postRunnable: Runnable?, + ) = Unit + + override fun getInputStream(): InputStream = BufferExposingByteArrayInputStream(contentsToByteArray()) + + override fun getModificationStamp(): Long = 0 + + private companion object { + const val DIRECTORY_LENGTH = -1L + const val DIRECTORY_STAMP = -1L + } +} diff --git a/lsp/kotlin/src/main/java/dev/mutwakil/androidide/lsp/kotlin/completion/KotlinCompletions.kt b/lsp/kotlin/src/main/java/dev/mutwakil/androidide/lsp/kotlin/completion/KotlinCompletions.kt index d2ea5b6b96..2ee286fd39 100644 --- a/lsp/kotlin/src/main/java/dev/mutwakil/androidide/lsp/kotlin/completion/KotlinCompletions.kt +++ b/lsp/kotlin/src/main/java/dev/mutwakil/androidide/lsp/kotlin/completion/KotlinCompletions.kt @@ -4,7 +4,7 @@ package dev.mutwakil.androidide.lsp.kotlin.completion import dev.mutwakil.androidide.lookup.Lookup import dev.mutwakil.androidide.lsp.api.describeSnippet -import dev.mutwakil.androidide.lsp.kotlin.compiler.CompilationEnvironment +import dev.mutwakil.androidide.lsp.kotlin.compiler.AbstractCompilationEnvironment import dev.mutwakil.androidide.lsp.kotlin.compiler.modules.AnalysisPreemptedException import dev.mutwakil.androidide.lsp.kotlin.compiler.modules.AnalysisPriority import dev.mutwakil.androidide.lsp.kotlin.compiler.modules.ScheduledCancelChecker @@ -130,11 +130,11 @@ private fun Throwable.isCancellation(): Boolean = isAnalysisCancellation() || th /** * Provide code completion for the given completion parameters. * - * @param CompilationEnvironment The compilation environment to use for the code completion. + * @param env The compilation environment to use for the code completion. * @param params The completion parameters. * @return The completion result. */ -context(env: CompilationEnvironment) +context(env: AbstractCompilationEnvironment) internal fun codeComplete(params: CompletionParams): CompletionResult { return try { doComplete(params) @@ -189,7 +189,7 @@ internal fun completionRequestBuffer(params: CompletionParams): CompletionReques * is never preempted by lower-priority work, but is superseded (cancelled and discarded) by a newer * completion request as the user keeps typing. */ -context(env: CompilationEnvironment) +context(env: AbstractCompilationEnvironment) internal fun doComplete(params: CompletionParams): CompletionResult { val result = env.ktSymbolIndex.withLiveKtFile(params.file) { live -> @@ -376,7 +376,7 @@ private fun KaSession.collectExtensionFunctions( to += toCompletionItems(extensionSymbols) } -context(env: CompilationEnvironment, ctx: AnalysisContext) +context(env: AbstractCompilationEnvironment, ctx: AnalysisContext) private fun KaSession.collectScopeCompletions(to: MutableList) { if (ctx.partial.isBlank()) { logger.warn("cannot complete for blank partial candidate") @@ -422,7 +422,7 @@ private fun KaSession.collectScopeCompletions(to: MutableList) { collectKeywordCompletions(to) } -context(env: CompilationEnvironment, ctx: AnalysisContext) +context(env: AbstractCompilationEnvironment, ctx: AnalysisContext) private fun KaSession.collectUnimportedSymbols(to: MutableList) { val currentPackage = ctx.ktElement.containingKtFile.packageDirective @@ -450,12 +450,7 @@ private fun KaSession.collectUnimportedSymbols(to: MutableList) return true } - /* - * Source first, library last. One shared cap across the indexes means whichever is queried last - * loses when the cap binds, and a symbol from the user's own project is likelier to be the one - * they are reaching for than one from a dependency. - */ - val indexes = listOfNotNull(env.sourceIndex, env.generatedIndex, env.libraryIndex) + val indexes = env.unimportedSymbolIndexes collectUnimportedSymbolMatches( indexes = indexes, diff --git a/lsp/kotlin/src/main/java/dev/mutwakil/androidide/lsp/kotlin/completion/KotlinSnippetRepository.kt b/lsp/kotlin/src/main/java/dev/mutwakil/androidide/lsp/kotlin/completion/KotlinSnippetRepository.kt index 48a56b5e73..38073582b2 100644 --- a/lsp/kotlin/src/main/java/dev/mutwakil/androidide/lsp/kotlin/completion/KotlinSnippetRepository.kt +++ b/lsp/kotlin/src/main/java/dev/mutwakil/androidide/lsp/kotlin/completion/KotlinSnippetRepository.kt @@ -5,12 +5,12 @@ import dev.mutwakil.androidide.lsp.snippets.SnippetParser import dev.mutwakil.androidide.lsp.snippets.SnippetRegistry object KotlinSnippetRepository { - val snippets: Map> - get() = KotlinSnippetScope.entries.associateWith { scope -> - SnippetRegistry.getSnippets("kt", scope.filename) - } + val snippets: Map> + get() = KotlinSnippetScope.entries.associateWith { scope -> + SnippetRegistry.getSnippets("kt", scope.filename) + } - fun init() { - SnippetRegistry.initBuiltIn("kt", KotlinSnippetScope.entries) - } + fun init() { + SnippetRegistry.initBuiltIn("kt", KotlinSnippetScope.entries) + } } \ No newline at end of file diff --git a/lsp/kotlin/src/main/java/dev/mutwakil/androidide/lsp/kotlin/diagnostic/KotlinDiagnosticProvider.kt b/lsp/kotlin/src/main/java/dev/mutwakil/androidide/lsp/kotlin/diagnostic/KotlinDiagnosticProvider.kt index 22c5bcbfdc..85d7c67f31 100644 --- a/lsp/kotlin/src/main/java/dev/mutwakil/androidide/lsp/kotlin/diagnostic/KotlinDiagnosticProvider.kt +++ b/lsp/kotlin/src/main/java/dev/mutwakil/androidide/lsp/kotlin/diagnostic/KotlinDiagnosticProvider.kt @@ -1,6 +1,6 @@ package dev.mutwakil.androidide.lsp.kotlin.diagnostic -import dev.mutwakil.androidide.lsp.kotlin.compiler.CompilationEnvironment +import dev.mutwakil.androidide.lsp.kotlin.compiler.AbstractCompilationEnvironment import dev.mutwakil.androidide.lsp.kotlin.compiler.modules.AnalysisPriority import dev.mutwakil.androidide.lsp.kotlin.compiler.modules.ScheduledCancelChecker import dev.mutwakil.androidide.lsp.kotlin.utils.toRange @@ -24,7 +24,7 @@ import java.nio.file.Path private val logger = LoggerFactory.getLogger("KotlinDiagnosticProvider") internal data class KotlinDiagnosticExtra( - val compilationEnv: CompilationEnvironment, + val compilationEnv: AbstractCompilationEnvironment, val action: ActionT, ) @@ -42,11 +42,25 @@ internal sealed interface DiagnosticAction { data object NullSafetyFix : DiagnosticAction } -context(env: CompilationEnvironment) +/** What one diagnostics run for a file produced. */ +internal sealed interface DiagnosticsOutcome { + /** The diagnostics of the file's current text. */ + data class Collected( + val result: DiagnosticResult, + ) : DiagnosticsOutcome + + /** The document changed while the run was in progress, so its diagnostics describe replaced text. */ + data object Superseded : DiagnosticsOutcome + + /** The file could not be analyzed: it is not accessible, or analysis failed. */ + data object Unavailable : DiagnosticsOutcome +} + +context(env: AbstractCompilationEnvironment) internal fun collectDiagnosticsFor( file: Path, cancelChecker: ICancelChecker, -): DiagnosticResult { +): DiagnosticsOutcome { try { logger.info("analyzing file: {}", file) return doAnalyze(file, cancelChecker) @@ -56,16 +70,16 @@ internal fun collectDiagnosticsFor( throw err } logger.error("an error occurred analyzing file: {}", file, err) - return DiagnosticResult.NO_UPDATE + return DiagnosticsOutcome.Unavailable } } @OptIn(KaExperimentalApi::class) -context(env: CompilationEnvironment) +context(env: AbstractCompilationEnvironment) private fun doAnalyze( file: Path, cancelChecker: ICancelChecker, -): DiagnosticResult { +): DiagnosticsOutcome { /* * Diagnostics yield to completion but preempt indexing. The wrapped checker turns a scheduler * preemption into an AnalysisPreemptedException, which CompilationEnvironment's fileAnalyzer catches @@ -142,22 +156,15 @@ private fun doAnalyze( } if (result != null) { - return result + return DiagnosticsOutcome.Collected(result) } if (superseded) { logger.debug("dropping superseded diagnostics for {}", file) - /* - * On the debounced path this is a self-send: doAnalyze runs as fileAnalyzer's own action, so the - * send reads to the worker as a newer key and cancels the run it came from. Deliberate - the - * reschedule still lands, and the only casualty is the NO_UPDATE publish below, which had nothing - * to say anyway. Reached from KotlinLanguageServer.analyze() instead, it is a plain reschedule. - */ - env.fileAnalyzer.schedule(file) - } else { - logger.warn("File {} is not accessible", file) + return DiagnosticsOutcome.Superseded } - return DiagnosticResult.NO_UPDATE + logger.warn("File {} is not accessible", file) + return DiagnosticsOutcome.Unavailable } private fun KaDiagnosticWithPsi<*>.toDiagnosticItem(): DiagnosticItem { diff --git a/lsp/kotlin/src/main/java/dev/mutwakil/androidide/lsp/kotlin/format/KotlinCodeFormatter.kt b/lsp/kotlin/src/main/java/dev/mutwakil/androidide/lsp/kotlin/format/KotlinCodeFormatter.kt index 3ecc8dad62..7962420dbb 100644 --- a/lsp/kotlin/src/main/java/dev/mutwakil/androidide/lsp/kotlin/format/KotlinCodeFormatter.kt +++ b/lsp/kotlin/src/main/java/dev/mutwakil/androidide/lsp/kotlin/format/KotlinCodeFormatter.kt @@ -6,15 +6,15 @@ import dev.mutwakil.androidide.lsp.models.CodeFormatException import dev.mutwakil.androidide.lsp.models.CodeFormatResult internal object KotlinCodeFormatter { - fun format(content: CharSequence): CodeFormatResult { - val formatted = - try { - Formatter.format(Formatter.KOTLINLANG_FORMAT, content.toString()) - } catch (e: ParseError) { - val strippedShebangLines = if (content.startsWith("#!")) 1 else 0 - val line = e.lineColumn.line + 1 + strippedShebangLines - throw CodeFormatException("$line:${e.lineColumn.column + 1}: ${e.errorDescription}", e) - } - return CodeFormatResult.forWholeContent(content, formatted) - } -} \ No newline at end of file + fun format(content: CharSequence): CodeFormatResult { + val formatted = + try { + Formatter.format(Formatter.KOTLINLANG_FORMAT, content.toString()) + } catch (e: ParseError) { + val strippedShebangLines = if (content.startsWith("#!")) 1 else 0 + val line = e.lineColumn.line + 1 + strippedShebangLines + throw CodeFormatException("$line:${e.lineColumn.column + 1}: ${e.errorDescription}", e) + } + return CodeFormatResult.forWholeContent(content, formatted) + } +} diff --git a/lsp/kotlin/src/main/java/dev/mutwakil/androidide/lsp/kotlin/navigation/FindUsages.kt b/lsp/kotlin/src/main/java/dev/mutwakil/androidide/lsp/kotlin/navigation/FindUsages.kt index 62f01c8955..335654dfa6 100644 --- a/lsp/kotlin/src/main/java/dev/mutwakil/androidide/lsp/kotlin/navigation/FindUsages.kt +++ b/lsp/kotlin/src/main/java/dev/mutwakil/androidide/lsp/kotlin/navigation/FindUsages.kt @@ -318,14 +318,26 @@ private fun KaSession.scopeOf( val module = moduleOf(declaration) ?: return fileOnly ?: UsageSearchScope.Modules(sourceModules()) - // internal is module-wide, and there is no associated test module to widen to: this project model - // builds one module per Gradle module from the main source set only. A file-confined target with no - // derivable path lands here too - it cannot be narrowed to one file, but it is still unreferenceable - // outside its own module, so it must not fall through to the dependents below. - if (fileConfined || symbol.visibility == KaSymbolVisibility.INTERNAL) { + // A file-confined target with no derivable path cannot be narrowed to one file, but it is still + // unreferenceable outside its own module, so it must not fall through to the dependents below. + if (fileConfined) { return UsageSearchScope.Modules(listOf(module)) } + // internal reaches its own module and that module's friends: the test modules layered over a main + // module. An internal override in a test module answers calls written against main's declaration + // (R3), so every match-set member's module is a root, as below. + if (symbol.visibility == KaSymbolVisibility.INTERNAL) { + val roots = LinkedHashSet() + roots.add(module) + for (member in matchSet) { + val memberDeclaration = member.sourcePsiSafe() ?: continue + moduleOf(memberDeclaration)?.let(roots::add) + } + val friends = sourceModules().filter { candidate -> candidate.directFriendDependencies.any { it in roots } } + return UsageSearchScope.Modules((roots + friends).toList()) + } + // Anything more visible can be referenced from any module that depends on this one. Dependents, // not all modules: a module that cannot see the declaration cannot reference it. // diff --git a/lsp/kotlin/src/main/java/dev/mutwakil/androidide/lsp/kotlin/signaturehelp/KotlinSignatureHelp.kt b/lsp/kotlin/src/main/java/dev/mutwakil/androidide/lsp/kotlin/signaturehelp/KotlinSignatureHelp.kt index d0a6c1f2ab..0f7ff48c8c 100644 --- a/lsp/kotlin/src/main/java/dev/mutwakil/androidide/lsp/kotlin/signaturehelp/KotlinSignatureHelp.kt +++ b/lsp/kotlin/src/main/java/dev/mutwakil/androidide/lsp/kotlin/signaturehelp/KotlinSignatureHelp.kt @@ -1,6 +1,6 @@ package dev.mutwakil.androidide.lsp.kotlin.signaturehelp -import dev.mutwakil.androidide.lsp.kotlin.compiler.CompilationEnvironment +import dev.mutwakil.androidide.lsp.kotlin.compiler.AbstractCompilationEnvironment import dev.mutwakil.androidide.lsp.kotlin.compiler.modules.AnalysisPreemptedException import dev.mutwakil.androidide.lsp.kotlin.compiler.modules.AnalysisPriority import dev.mutwakil.androidide.lsp.kotlin.compiler.modules.ScheduledCancelChecker @@ -84,7 +84,7 @@ private val logger = LoggerFactory.getLogger("KotlinSignatureHelp") * Computes [SignatureHelp] for the request described by [params], using the given * [CompilationEnvironment] to resolve the enclosing call and analyze it. */ -context(env: CompilationEnvironment) +context(env: AbstractCompilationEnvironment) internal suspend fun doSignatureHelp(params: SignatureHelpParams): SignatureHelp { logger.debug("doSignatureHelp requested for file={} position={}", params.file, params.position) diff --git a/lsp/kotlin/src/main/java/dev/mutwakil/androidide/lsp/kotlin/utils/ContextResolver.kt b/lsp/kotlin/src/main/java/dev/mutwakil/androidide/lsp/kotlin/utils/ContextResolver.kt index 5e9db679a5..85fde3460f 100644 --- a/lsp/kotlin/src/main/java/dev/mutwakil/androidide/lsp/kotlin/utils/ContextResolver.kt +++ b/lsp/kotlin/src/main/java/dev/mutwakil/androidide/lsp/kotlin/utils/ContextResolver.kt @@ -1,6 +1,6 @@ package dev.mutwakil.androidide.lsp.kotlin.utils -import dev.mutwakil.androidide.lsp.kotlin.compiler.CompilationEnvironment +import dev.mutwakil.androidide.lsp.kotlin.compiler.AbstractCompilationEnvironment import dev.mutwakil.androidide.lsp.kotlin.completion.DeclarationContext import dev.mutwakil.androidide.lsp.kotlin.completion.DeclarationKind import dev.mutwakil.androidide.lsp.models.MatchLevel @@ -34,7 +34,7 @@ private val logger = LoggerFactory.getLogger("ContextResolver") * Defines context at the cursor position. */ internal data class AnalysisContext( - val env: CompilationEnvironment, + val env: AbstractCompilationEnvironment, val file: Path, val psiElement: PsiElement, val ktFile: KtFile, @@ -60,11 +60,11 @@ internal data class AnalysisContext( * @param partial The partial identifier at the cursor position. */ internal fun KaSession.resolveAnalysisContext( - env: CompilationEnvironment, + env: AbstractCompilationEnvironment, file: Path, ktFile: KtFile, offset: Int, - partial: String + partial: String, ): AnalysisContext? { val psiElement = ktFile.findElementAt(offset) if (psiElement == null) { @@ -84,11 +84,13 @@ internal fun KaSession.resolveAnalysisContext( // The element is typically a KtModifierList, an error node, // or the incomplete declaration itself. val modifierList = ktElement.getParentOfType(strict = false) - val existingModifiers = modifierList - ?.node?.getChildren(MODIFIER_KEYWORDS) - ?.mapNotNull { it.elementType as? KtModifierKeywordToken } - ?.toSet() - ?: emptySet() + val existingModifiers = + modifierList + ?.node + ?.getChildren(MODIFIER_KEYWORDS) + ?.mapNotNull { it.elementType as? KtModifierKeywordToken } + ?.toSet() + ?: emptySet() val declarationKind = resolveDeclarationKind(ktElement) val declarationContext = resolveDeclarationContext(ktElement) @@ -114,23 +116,36 @@ private fun resolveDeclarationContext(element: KtElement): DeclarationContext { when (ancestor) { is KtClassBody -> { return when (val owner = ancestor.parent) { - is KtClass -> when { - owner.isInterface() -> DeclarationContext.INTERFACE_BODY - owner.isEnum() -> DeclarationContext.ENUM_BODY - owner.isAnnotation() -> DeclarationContext.ANNOTATION_BODY - else -> DeclarationContext.CLASS_BODY + is KtClass -> { + when { + owner.isInterface() -> DeclarationContext.INTERFACE_BODY + owner.isEnum() -> DeclarationContext.ENUM_BODY + owner.isAnnotation() -> DeclarationContext.ANNOTATION_BODY + else -> DeclarationContext.CLASS_BODY + } } - is KtObjectDeclaration -> DeclarationContext.OBJECT_BODY - else -> DeclarationContext.CLASS_BODY + is KtObjectDeclaration -> { + DeclarationContext.OBJECT_BODY + } + + else -> { + DeclarationContext.CLASS_BODY + } } } - is KtBlockExpression -> return DeclarationContext.FUNCTION_BODY - is KtFile -> return if (ancestor.isScript()) - DeclarationContext.SCRIPT_TOP_LEVEL - else - DeclarationContext.TOP_LEVEL + is KtBlockExpression -> { + return DeclarationContext.FUNCTION_BODY + } + + is KtFile -> { + return if (ancestor.isScript()) { + DeclarationContext.SCRIPT_TOP_LEVEL + } else { + DeclarationContext.TOP_LEVEL + } + } } } return DeclarationContext.TOP_LEVEL @@ -139,21 +154,46 @@ private fun resolveDeclarationContext(element: KtElement): DeclarationContext { private fun resolveDeclarationKind(element: KtElement): DeclarationKind { // Walk up to the nearest declaration owning this modifier list / position return when (val declaration = element.getNonStrictParentOfType()) { - is KtClass -> when { - declaration.isInterface() -> DeclarationKind.INTERFACE - declaration.isEnum() -> DeclarationKind.ENUM_CLASS - declaration.isAnnotation() -> DeclarationKind.ANNOTATION_CLASS - else -> DeclarationKind.CLASS + is KtClass -> { + when { + declaration.isInterface() -> DeclarationKind.INTERFACE + declaration.isEnum() -> DeclarationKind.ENUM_CLASS + declaration.isAnnotation() -> DeclarationKind.ANNOTATION_CLASS + else -> DeclarationKind.CLASS + } } - is KtObjectDeclaration -> DeclarationKind.OBJECT - is KtNamedFunction -> DeclarationKind.FUN - is KtProperty -> if (declaration.isVar) DeclarationKind.PROPERTY_VAR - else DeclarationKind.PROPERTY_VAL + is KtObjectDeclaration -> { + DeclarationKind.OBJECT + } + + is KtNamedFunction -> { + DeclarationKind.FUN + } - is KtTypeAlias -> DeclarationKind.TYPEALIAS - is KtConstructor<*> -> DeclarationKind.CONSTRUCTOR - null -> DeclarationKind.UNKNOWN // pure modifier list, no keyword yet - else -> DeclarationKind.UNKNOWN + is KtProperty -> { + if (declaration.isVar) { + DeclarationKind.PROPERTY_VAR + } else { + DeclarationKind.PROPERTY_VAL + } + } + + is KtTypeAlias -> { + DeclarationKind.TYPEALIAS + } + + is KtConstructor<*> -> { + DeclarationKind.CONSTRUCTOR + } + + null -> { + DeclarationKind.UNKNOWN + } + + // pure modifier list, no keyword yet + else -> { + DeclarationKind.UNKNOWN + } } } diff --git a/lsp/kotlin/src/main/java/dev/mutwakil/androidide/lsp/kotlin/utils/SymbolVisibilityChecker.kt b/lsp/kotlin/src/main/java/dev/mutwakil/androidide/lsp/kotlin/utils/SymbolVisibilityChecker.kt index 90e5f2e44f..dd760442c5 100644 --- a/lsp/kotlin/src/main/java/dev/mutwakil/androidide/lsp/kotlin/utils/SymbolVisibilityChecker.kt +++ b/lsp/kotlin/src/main/java/dev/mutwakil/androidide/lsp/kotlin/utils/SymbolVisibilityChecker.kt @@ -24,8 +24,9 @@ internal class SymbolVisibilityChecker( useSiteModule: KaModule, useSitePackage: String? = null, ): Boolean { - val declaringModule = structureProvider.findModuleForSourceId(symbol.sourceId) - ?: return false + val declaringModule = + structureProvider.findModuleForSourceId(symbol.sourceId) + ?: return false if (!isReachable(useSiteModule, declaringModule)) return false if (!arePlatformCompatible(useSiteModule, declaringModule)) return false @@ -34,7 +35,10 @@ internal class SymbolVisibilityChecker( return true } - fun isReachable(useSiteModule: KaModule, declaringModule: KaModule): Boolean { + fun isReachable( + useSiteModule: KaModule, + declaringModule: KaModule, + ): Boolean { if (useSiteModule == declaringModule) return true if (moduleVisibilityCache[useSiteModule]?.contains(declaringModule) == true) return true @@ -54,7 +58,10 @@ internal class SymbolVisibilityChecker( return false } - fun arePlatformCompatible(useSiteModule: KaModule, declaringModule: KaModule): Boolean { + fun arePlatformCompatible( + useSiteModule: KaModule, + declaringModule: KaModule, + ): Boolean { val usePlatform = useSiteModule.targetPlatform val declPlatform = declaringModule.targetPlatform @@ -84,7 +91,7 @@ internal class SymbolVisibilityChecker( return when (symbol.visibility) { JvmVisibility.PUBLIC -> true JvmVisibility.PRIVATE -> false - JvmVisibility.INTERNAL -> useSiteModule == declaringModule + JvmVisibility.INTERNAL -> useSiteModule == declaringModule || declaringModule in useSiteModule.directFriendDependencies JvmVisibility.PROTECTED -> isSamePackage || isDescendant JvmVisibility.PACKAGE_PRIVATE -> isSamePackage } diff --git a/lsp/kotlin/src/test/java/dev/mutwakil/androidide/lsp/kotlin/CompilerSessionTest.kt b/lsp/kotlin/src/test/java/dev/mutwakil/androidide/lsp/kotlin/CompilerSessionTest.kt new file mode 100644 index 0000000000..e33b6c1e28 --- /dev/null +++ b/lsp/kotlin/src/test/java/dev/mutwakil/androidide/lsp/kotlin/CompilerSessionTest.kt @@ -0,0 +1,362 @@ +package dev.mutwakil.androidide.lsp.kotlin + +import com.google.common.truth.Truth.assertThat +import dev.mutwakil.androidide.logging.provider.IdeLogRouter +import dev.mutwakil.androidide.lsp.kotlin.compiler.KotlinModuleLayout +import dev.mutwakil.androidide.lsp.kotlin.fixtures.gradleProject +import dev.mutwakil.androidide.projects.api.GradleProject +import dev.mutwakil.androidide.projects.api.Workspace +import kotlinx.coroutines.CompletableDeferred +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.cancel +import kotlinx.coroutines.delay +import kotlinx.coroutines.runBlocking +import kotlinx.coroutines.withTimeout +import org.appdevforall.codeonthego.indexing.service.IndexRegistryClosedException +import org.appdevforall.codeonthego.indexing.service.IndexingServiceManager +import org.junit.After +import org.junit.Before +import org.junit.Test +import org.slf4j.event.Level +import java.nio.file.Path +import java.util.Collections +import java.util.IdentityHashMap +import java.util.concurrent.ConcurrentHashMap +import java.util.concurrent.ConcurrentLinkedDeque +import java.util.concurrent.CopyOnWriteArrayList + +class CompilerSessionTest { + private val scope = CoroutineScope(SupervisorJob()) + private val lifecycle = FakeLifecycle() + private val session = CompilerSession(scope, lifecycle) + private val logs: MutableList> = CopyOnWriteArrayList() + private val sink = IdeLogRouter.ExternalSink { level, _, message, _ -> logs += level to message } + + @Before + fun installSink() { + IdeLogRouter.addSink(sink) + } + + @After + fun tearDown() { + IdeLogRouter.removeSink(sink) + lifecycle.gates.values.forEach { it.complete(Unit) } + lifecycle.awaitClosedGate?.complete(Unit) + lifecycle.prepareGate?.complete(Unit) + scope.cancel() + } + + @Test + fun `an unchanged layout keeps the compiler`(): Unit = + runBlocking { + session.submit(workspace(LAYOUT_A)) + awaitEvent("ready c1") + session.submit(workspace(LAYOUT_A)) + awaitEvent("ready c1", times = 2) + + assertThat(lifecycle.builds).isEqualTo(1) + assertThat(lifecycle.events.filter { it.startsWith("close") }).isEmpty() + assertThat(session.current).isEqualTo("c1") + } + + @Test + fun `an update waits for the previous close before preparing`(): Unit = + runBlocking { + session.submit(workspace(LAYOUT_A)) + awaitEvent("ready c1") + + val events = lifecycle.events.toList() + assertThat(events.indexOf("awaitClosed")).isLessThan(events.indexOf("prepare")) + } + + @Test + fun `a changed layout closes the old compiler before building the new one`(): Unit = + runBlocking { + session.submit(workspace(LAYOUT_A)) + awaitEvent("ready c1") + session.submit(workspace(LAYOUT_B)) + awaitEvent("ready c2") + + val events = lifecycle.events.toList() + assertThat(events.indexOf("close c1")).isLessThan(events.lastIndexOf("awaitClosed")) + assertThat(events.lastIndexOf("awaitClosed")).isLessThan(events.indexOf("build c2 for B")) + assertThat(session.current).isEqualTo("c2") + } + + @Test + fun `current is null while a rebuild is in progress`(): Unit = + runBlocking { + session.submit(workspace(LAYOUT_A)) + awaitEvent("ready c1") + val gate = lifecycle.gate(build = 2) + + session.submit(workspace(LAYOUT_B)) + awaitEvent("building c2") + + assertThat(session.current).isNull() + gate.complete(Unit) + awaitEvent("ready c2") + } + + @Test + fun `updates during a build collapse to the latest`(): Unit = + runBlocking { + val gate = lifecycle.gate(build = 1) + session.submit(workspace(LAYOUT_A)) + awaitEvent("building c1") + + session.submit(workspace(LAYOUT_B)) + session.submit(workspace(LAYOUT_C)) + session.submit(workspace(LAYOUT_D)) + gate.complete(Unit) + awaitEvent("ready c2") + + assertThat(lifecycle.events.filter { it.startsWith("build ") }) + .containsExactly("build c1 for A", "build c2 for D") + .inOrder() + } + + @Test + fun `shutdown during a build closes the new compiler instead of publishing it`(): Unit = + runBlocking { + val gate = lifecycle.gate(build = 1) + session.submit(workspace(LAYOUT_A)) + awaitEvent("building c1") + + session.shutdown() + gate.complete(Unit) + awaitEvent("close c1") + + assertThat(session.current).isNull() + assertThat(lifecycle.events).doesNotContain("ready c1") + } + + @Test + fun `shutdown while waiting for the previous close stops the update before preparing`(): Unit = + runBlocking { + val gate = CompletableDeferred() + lifecycle.awaitClosedGate = gate + session.submit(workspace(LAYOUT_A)) + awaitEvent("awaitClosed") + + session.shutdown() + gate.complete(Unit) + delay(SETTLE_MILLIS) + + assertThat(lifecycle.events).doesNotContain("prepare") + assertThat(lifecycle.builds).isEqualTo(0) + } + + @Test + fun `shutdown while preparing stops the update before building`(): Unit = + runBlocking { + val gate = CompletableDeferred() + lifecycle.prepareGate = gate + session.submit(workspace(LAYOUT_A)) + awaitEvent("prepare") + + session.shutdown() + gate.complete(Unit) + delay(SETTLE_MILLIS) + + assertThat(lifecycle.builds).isEqualTo(0) + } + + @Test + fun `a failed build is retried by the next update with the same layout`(): Unit = + runBlocking { + lifecycle.failingBuilds += 1 + session.submit(workspace(LAYOUT_A)) + awaitEvent("build failed c1") + + session.submit(workspace(LAYOUT_A)) + awaitEvent("ready c2") + + assertThat(session.current).isEqualTo("c2") + } + + @Test + fun `a skipped update is retried by the next update`(): Unit = + runBlocking { + lifecycle.awaitClosedResults += false + session.submit(workspace(LAYOUT_A)) + awaitEvent("awaitClosed") + + session.submit(workspace(LAYOUT_A)) + awaitEvent("ready c1") + + assertThat(lifecycle.builds).isEqualTo(1) + assertThat(session.current).isEqualTo("c1") + } + + @Test + fun `a build that hits the closed registry logs no error`(): Unit = + runBlocking { + lifecycle.closedBuilds += 1 + session.submit(workspace(LAYOUT_A)) + awaitEvent("build failed c1") + delay(SETTLE_MILLIS) + + assertThat(updateFailures()).isEmpty() + assertThat(logs.filter { it.first == Level.INFO && "Project closed" in it.second }).hasSize(1) + } + + @Test + fun `a wrapped closed-registry failure logs no error`(): Unit = + runBlocking { + lifecycle.wrappedClosedBuilds += 1 + session.submit(workspace(LAYOUT_A)) + awaitEvent("build failed c1") + delay(SETTLE_MILLIS) + + assertThat(updateFailures()).isEmpty() + } + + @Test + fun `a failed build still logs an error`(): Unit = + runBlocking { + lifecycle.failingBuilds += 1 + session.submit(workspace(LAYOUT_A)) + awaitEvent("build failed c1") + delay(SETTLE_MILLIS) + + assertThat(updateFailures()).hasSize(1) + } + + private fun updateFailures() = logs.filter { it.first == Level.ERROR && "Kotlin project update failed" in it.second } + + @Test + fun `an update binds one manager for prepare and build`(): Unit = + runBlocking { + session.submit(workspace(LAYOUT_A)) + awaitEvent("ready c1") + + assertThat(lifecycle.obtainedManagers).hasSize(1) + assertThat(lifecycle.preparedWith.single()).isSameInstanceAs(lifecycle.builtWith.single()) + } + + @Test + fun `shutdown before binding obtains no manager`(): Unit = + runBlocking { + val gate = CompletableDeferred() + lifecycle.awaitClosedGate = gate + session.submit(workspace(LAYOUT_A)) + awaitEvent("awaitClosed") + + session.shutdown() + gate.complete(Unit) + delay(SETTLE_MILLIS) + + assertThat(lifecycle.obtainedManagers).isEmpty() + } + + private fun workspace(layout: KotlinModuleLayout): Workspace = + Workspace( + rootProject = GradleProject(gradleProject(":")), + subProjects = emptyList(), + syncIssues = emptyList(), + ).also { lifecycle.layouts[it] = layout } + + private suspend fun awaitEvent( + event: String, + times: Int = 1, + ) { + withTimeout(5_000) { + while (lifecycle.events.count { it == event } < times) delay(10) + } + } + + private class FakeLifecycle : CompilerLifecycle { + val events: MutableList = CopyOnWriteArrayList() + val layouts: MutableMap = Collections.synchronizedMap(IdentityHashMap()) + val gates = ConcurrentHashMap>() + val failingBuilds: MutableSet = Collections.synchronizedSet(mutableSetOf()) + val closedBuilds: MutableSet = Collections.synchronizedSet(mutableSetOf()) + val wrappedClosedBuilds: MutableSet = Collections.synchronizedSet(mutableSetOf()) + val awaitClosedResults = ConcurrentLinkedDeque() + + @Volatile + var builds = 0 + + fun gate(build: Int) = CompletableDeferred().also { gates[build] = it } + + @Volatile + var awaitClosedGate: CompletableDeferred? = null + + @Volatile + var prepareGate: CompletableDeferred? = null + + val obtainedManagers: MutableList = CopyOnWriteArrayList() + val preparedWith: MutableList = CopyOnWriteArrayList() + val builtWith: MutableList = CopyOnWriteArrayList() + + override fun currentManager() = IndexingServiceManager().also { obtainedManagers += it } + + override fun prepare( + workspace: Workspace, + manager: IndexingServiceManager, + ) { + preparedWith += manager + events += "prepare" + prepareGate?.let { runBlocking { it.await() } } + } + + override fun layoutOf(workspace: Workspace) = layouts.getValue(workspace) + + override fun awaitClosed(): Boolean { + events += "awaitClosed" + awaitClosedGate?.let { runBlocking { it.await() } } + return awaitClosedResults.pollFirst() ?: true + } + + override fun build( + workspace: Workspace, + layout: KotlinModuleLayout, + manager: IndexingServiceManager, + ): String { + builtWith += manager + val n = ++builds + events += "building c$n" + gates[n]?.let { runBlocking { it.await() } } + if (n in failingBuilds) { + events += "build failed c$n" + throw IllegalStateException("build $n failed") + } + if (n in closedBuilds) { + events += "build failed c$n" + throw IndexRegistryClosedException("registry closed during build $n") + } + if (n in wrappedClosedBuilds) { + events += "build failed c$n" + throw RuntimeException("build $n failed", IndexRegistryClosedException("registry closed during build $n")) + } + events += "build c$n for ${LAYOUT_NAMES.getValue(layout)}" + return "c$n" + } + + override fun close(compiler: String) { + events += "close $compiler" + } + + override fun onReady( + workspace: Workspace, + compiler: String, + ) { + events += "ready $compiler" + } + } + + private companion object { + /** Long enough for a released worker to reach its next lifecycle call. */ + const val SETTLE_MILLIS = 200L + + fun layout(name: String) = KotlinModuleLayout(listOf(Path.of("/$name.jar")), emptySet(), emptyList()) + + val LAYOUT_A = layout("A") + val LAYOUT_B = layout("B") + val LAYOUT_C = layout("C") + val LAYOUT_D = layout("D") + val LAYOUT_NAMES = mapOf(LAYOUT_A to "A", LAYOUT_B to "B", LAYOUT_C to "C", LAYOUT_D to "D") + } +} diff --git a/lsp/kotlin/src/test/java/dev/mutwakil/androidide/lsp/kotlin/VariantSourceSetsTest.kt b/lsp/kotlin/src/test/java/dev/mutwakil/androidide/lsp/kotlin/VariantSourceSetsTest.kt new file mode 100644 index 0000000000..ffb806bcc3 --- /dev/null +++ b/lsp/kotlin/src/test/java/dev/mutwakil/androidide/lsp/kotlin/VariantSourceSetsTest.kt @@ -0,0 +1,116 @@ +package dev.mutwakil.androidide.lsp.kotlin + +import com.google.common.truth.Truth.assertThat +import dev.mutwakil.androidide.eventbus.events.editor.DocumentCloseEvent +import dev.mutwakil.androidide.eventbus.events.editor.DocumentOpenEvent +import dev.mutwakil.androidide.lsp.kotlin.compiler.KotlinModuleLayout +import dev.mutwakil.androidide.lsp.kotlin.completion.doComplete +import dev.mutwakil.androidide.lsp.kotlin.diagnostic.DiagnosticsOutcome +import dev.mutwakil.androidide.lsp.kotlin.diagnostic.collectDiagnosticsFor +import dev.mutwakil.androidide.lsp.kotlin.fixtures.KtLspTest +import dev.mutwakil.androidide.lsp.kotlin.fixtures.variantLayout +import dev.mutwakil.androidide.lsp.kotlin.navigation.findDefinitionAt +import dev.mutwakil.androidide.lsp.models.CompletionParams +import dev.mutwakil.androidide.lsp.models.DefinitionParams +import dev.mutwakil.androidide.lsp.models.DiagnosticSeverity +import dev.mutwakil.androidide.models.Position +import dev.mutwakil.androidide.progress.ICancelChecker +import dev.mutwakil.androidide.projects.FileManager +import dev.mutwakil.androidide.projects.ProjectManagerImpl +import kotlinx.coroutines.runBlocking +import org.junit.After +import org.junit.Test +import java.nio.file.Path +import kotlin.io.path.createParentDirectories +import kotlin.io.path.readText +import kotlin.io.path.writeText + +/** + * `VariantConfig` is declared in both `src/debug` and `src/release`, each with its own property. + * With `debug` selected, Kotlin analysis must see the debug declaration and never the release one. + */ +class VariantSourceSetsTest : KtLspTest() { + // Completion runs on the opened document's live KtFile, which must be physical as in production. + override val enableParserEventSystem = true + + private lateinit var use: Path + private lateinit var completion: Path + private lateinit var releaseConfig: Path + + override fun layout(baseDir: Path): KotlinModuleLayout { + use = write(baseDir, "src/main/kotlin/p/Use.kt", USE) + completion = write(baseDir, "src/main/kotlin/p/Complete.kt", "package p\n\nfun c() = VariantConfig.\n") + write(baseDir, "src/debug/kotlin/p/VariantConfig.kt", "package p\n\nobject VariantConfig {\n\tval debugOnly = 1\n}\n") + releaseConfig = write(baseDir, "src/release/kotlin/p/VariantConfig.kt", RELEASE_CONFIG) + return variantLayout(baseDir, listOf("debug", "release"), selected = "debug") + } + + @After + fun tearDown() { + FileManager.onDocumentClose(DocumentCloseEvent(completion)) + ProjectManagerImpl.getInstance().workspace = null + } + + @Test + fun `diagnostics resolve the selected variant's sources and flag another variant's`() { + val outcome = context(env) { collectDiagnosticsFor(use, ICancelChecker.NOOP) } + + val errors = (outcome as DiagnosticsOutcome.Collected).result.diagnostics.filter { it.severity == DiagnosticSeverity.ERROR } + + // Line 4 reads releaseOnly; line 2 reads debugOnly and must resolve. + assertThat(errors.map { it.range.start.line }.distinct()).containsExactly(4) + } + + @Test + fun `definition goes to the selected variant's declaration`() { + val offset = use.readText().indexOf("VariantConfig.debugOnly") + 2 + + val files = + runBlocking { context(env) { findDefinitionAt(DefinitionParams(use, Position(0, 0, offset), ICancelChecker.NOOP)) } } + .locations + .map { it.file.toString() } + + assertThat(files).isNotEmpty() + assertThat(files.filterNot { "/src/debug/kotlin/" in it }).isEmpty() + } + + @Test + fun `completion offers the selected variant's members and not another variant's`() { + val text = completion.readText() + FileManager.onDocumentOpen(DocumentOpenEvent(completion, text, 1)) + val offset = text.indexOf("VariantConfig.") + "VariantConfig.".length + + val labels = + context(env) { doComplete(CompletionParams(Position(0, 0, offset), completion, ICancelChecker.NOOP).apply { prefix = "" }) } + .items + .map { it.ideLabel.toString() } + + assertThat(labels).contains("debugOnly") + assertThat(labels).doesNotContain("releaseOnly") + } + + @Test + fun `a source of a variant that is not selected gets no diagnostics`() { + val server = KotlinLanguageServer() + try { + val result = runBlocking { server.analyze(releaseConfig) } + + // Cleared for this file, not merely "no update": an earlier variant's errors must go away. + assertThat(result.file).isEqualTo(releaseConfig) + assertThat(result.diagnostics).isEmpty() + } finally { + server.shutdown() + } + } + + private companion object { + const val RELEASE_CONFIG = "package p\n\nobject VariantConfig {\n\tval releaseOnly = 2\n}\n" + const val USE = "package p\n\nfun d() = VariantConfig.debugOnly\n\nfun r() = VariantConfig.releaseOnly\n" + } + + private fun write( + baseDir: Path, + relativePath: String, + content: String, + ): Path = baseDir.resolve(relativePath).also { it.createParentDirectories().writeText(content) } +} diff --git a/lsp/kotlin/src/test/java/dev/mutwakil/androidide/lsp/kotlin/compiler/CollectKtModulesTest.kt b/lsp/kotlin/src/test/java/dev/mutwakil/androidide/lsp/kotlin/compiler/CollectKtModulesTest.kt index de3dd3f275..325a9e311b 100644 --- a/lsp/kotlin/src/test/java/dev/mutwakil/androidide/lsp/kotlin/compiler/CollectKtModulesTest.kt +++ b/lsp/kotlin/src/test/java/dev/mutwakil/androidide/lsp/kotlin/compiler/CollectKtModulesTest.kt @@ -4,20 +4,42 @@ import com.google.common.truth.Truth.assertThat import dev.mutwakil.androidide.lsp.kotlin.compiler.modules.KtLibraryModule import dev.mutwakil.androidide.lsp.kotlin.compiler.modules.KtSourceModule import dev.mutwakil.androidide.lsp.kotlin.fixtures.KtLspTest -import dev.mutwakil.androidide.project.AndroidModels -import dev.mutwakil.androidide.project.GradleModels -import dev.mutwakil.androidide.project.JavaModels +import dev.mutwakil.androidide.lsp.kotlin.fixtures.TestSources +import dev.mutwakil.androidide.lsp.kotlin.fixtures.gradleProject +import dev.mutwakil.androidide.projects.ProjectManagerImpl import dev.mutwakil.androidide.projects.api.AndroidModule import dev.mutwakil.androidide.projects.api.GradleProject import dev.mutwakil.androidide.projects.api.JavaModule import dev.mutwakil.androidide.projects.api.ModuleProject import dev.mutwakil.androidide.projects.api.Workspace +import org.junit.After import org.junit.Test import java.nio.file.Path import kotlin.io.path.createFile import kotlin.io.path.pathString class CollectKtModulesTest : KtLspTest() { + @After + fun clearWorkspace() { + ProjectManagerImpl.getInstance().workspace = null + } + + @Test + fun `a module dependency cycle builds each source module once`() { + val sourceModules = + collect( + listOf( + AndroidModule(gradleProject(":liba", projectDeps = listOf(":libb"))), + AndroidModule(gradleProject(":libb", projectDeps = listOf(":liba"))), + ), + ) + + val libA = sourceModules.single { it.id == ":liba" } + val libB = sourceModules.single { it.id == ":libb" } + // Before ADFA-5320 this recursed :liba -> :libb -> :liba until the stack overflowed. + assertThat(libA.directRegularDependencies.filterIsInstance()).containsExactly(libB) + } + @Test fun `modules sharing android jar share one library module`() { val androidJar = tempJar("android.jar") @@ -36,7 +58,7 @@ class CollectKtModulesTest : KtLspTest() { fun `modules sharing a compile classpath jar share one library module`() { val libJar = tempJar("lib.jar") - val sourceModules = collect(listOf(":a", ":b").map { JavaModule(gradleProject(it, compileJar = libJar)) }) + val sourceModules = collect(listOf(":a", ":b").map { JavaModule(gradleProject(it, compileJars = listOf(libJar))) }) val libJarDeps = sourceModules.map { it.libraryDeps(libJar) } libJarDeps.forEach { assertThat(it).hasSize(1) } @@ -53,63 +75,173 @@ class CollectKtModulesTest : KtLspTest() { collect( listOf( AndroidModule(gradleProject(":a", bootClassPath = androidJar)), - JavaModule(gradleProject(":j", compileJar = androidJar)), + JavaModule(gradleProject(":j", compileJars = listOf(androidJar))), ), ) assertThat(sourceModules.single { it.id == ":j" }.libraryDeps(androidJar)).hasSize(1) } + @Test + fun `each test source set is its own module over main`() { + val junit = tempJar("junit.jar") + val espresso = tempJar("espresso.jar") + val sourceModules = + collect( + listOf( + AndroidModule( + gradleProject( + ":app", + unitTests = TestSources(listOf(tempDir("app/src/test/java")), listOf(junit)), + androidTests = TestSources(listOf(tempDir("app/src/androidTest/java")), listOf(espresso)), + ), + ), + ), + ) + + val main = sourceModules.single { it.id == ":app" } + val unit = sourceModules.single { it.id == ":app[unitTest]" } + val device = sourceModules.single { it.id == ":app[androidTest]" } + + assertThat(main.contentRoots).containsNoneIn(unit.contentRoots + device.contentRoots) + for (test in listOf(unit, device)) { + assertThat(test.directRegularDependencies).contains(main) + assertThat(test.directFriendDependencies).containsExactly(main) + } + assertThat(main.directFriendDependencies).isEmpty() + + // The scopes are isolated: neither test module, nor main, sees the other's sources or jars. + assertThat(unit.directRegularDependencies).doesNotContain(device) + assertThat(device.directRegularDependencies).doesNotContain(unit) + assertThat(unit.libraryDeps(junit)).hasSize(1) + assertThat(unit.libraryDeps(espresso)).isEmpty() + assertThat(device.libraryDeps(espresso)).hasSize(1) + assertThat(device.libraryDeps(junit)).isEmpty() + assertThat(main.libraryDeps(junit) + main.libraryDeps(espresso)).isEmpty() + } + + @Test + fun `a test module also depends on what main depends on`() { + val sourceModules = + collect( + listOf( + AndroidModule(gradleProject(":lib", bootClassPath = tempJar("android.jar"))), + AndroidModule( + gradleProject( + ":app", + projectDeps = listOf(":lib"), + unitTests = TestSources(listOf(tempDir("app/src/test/java"))), + ), + ), + ), + ) + + val lib = sourceModules.single { it.id == ":lib" } + val unit = sourceModules.single { it.id == ":app[unitTest]" } + assertThat(unit.directRegularDependencies).contains(lib) + // lib's internals stay hidden: only the test module's own main module is a friend. + assertThat(unit.directFriendDependencies.map { it.id }).containsExactly(":app") + } + + @Test + fun `a test-only project dependency is a source module of that test scope only`() { + val sourceModules = + collect( + listOf( + AndroidModule(gradleProject(":lib", bootClassPath = tempJar("android.jar"))), + AndroidModule( + gradleProject( + ":app", + unitTests = TestSources(listOf(tempDir("app/src/test/java")), projects = listOf(":lib")), + androidTests = TestSources(listOf(tempDir("app/src/androidTest/java"))), + ), + ), + ), + ) + + val lib = sourceModules.single { it.id == ":lib" } + assertThat(sourceModules.single { it.id == ":app[unitTest]" }.directRegularDependencies).contains(lib) + assertThat(sourceModules.single { it.id == ":app[androidTest]" }.directRegularDependencies).doesNotContain(lib) + assertThat(sourceModules.single { it.id == ":app" }.directRegularDependencies).doesNotContain(lib) + } + + @Test + fun `req 5 - a test module depends on the module's test fixtures module but not the reverse`() { + val sourceModules = + collect( + listOf( + AndroidModule( + gradleProject( + ":app", + unitTests = TestSources(listOf(tempDir("app/src/test/java"))), + testFixtures = TestSources(listOf(tempDir("app/src/testFixtures/java"))), + ), + ), + ), + ) + + val fixtures = sourceModules.single { it.id == ":app[testFixtures]" } + val unit = sourceModules.single { it.id == ":app[unitTest]" } + assertThat(unit.directRegularDependencies).contains(fixtures) + assertThat(fixtures.directRegularDependencies).doesNotContain(unit) + assertThat(sourceModules.single { it.id == ":app" }.directRegularDependencies).doesNotContain(fixtures) + } + + @Test + fun `req 10 - a unit test module depends on another module's test fixtures module`() { + val sourceModules = + collect( + listOf( + AndroidModule( + gradleProject( + ":lib", + bootClassPath = tempJar("android.jar"), + testFixtures = TestSources(listOf(tempDir("lib/src/testFixtures/java"))), + ), + ), + AndroidModule( + gradleProject( + ":app", + unitTests = TestSources(listOf(tempDir("app/src/test/java")), fixtureProjects = listOf(":lib")), + androidTests = TestSources(listOf(tempDir("app/src/androidTest/java"))), + ), + ), + ), + ) + + val libFixtures = sourceModules.single { it.id == ":lib[testFixtures]" } + assertThat(sourceModules.single { it.id == ":app[unitTest]" }.directRegularDependencies).contains(libFixtures) + assertThat(sourceModules.single { it.id == ":app[androidTest]" }.directRegularDependencies).doesNotContain(libFixtures) + assertThat(sourceModules.single { it.id == ":app" }.directRegularDependencies).doesNotContain(libFixtures) + } + + private fun tempDir(name: String): Path = + lspTestRule.tempDir.root + .toPath() + .resolve(name) + .also { it.toFile().mkdirs() } + private fun tempJar(name: String): Path = lspTestRule.tempDir.root .toPath() .resolve(name) .createFile() - private fun collect(subProjects: List): List = - Workspace( - rootProject = GradleProject(gradleProject(":")), - subProjects = subProjects, - syncIssues = emptyList(), - ).collectKtModules(env.project, env.applicationEnv) + // Module dependencies resolve through the global workspace, so this one is installed there. + private fun collect(subProjects: List): List { + val workspace = + Workspace( + rootProject = GradleProject(gradleProject(":")), + subProjects = subProjects, + syncIssues = emptyList(), + ) + ProjectManagerImpl.getInstance().workspace = workspace + return workspace + .kotlinModuleLayout() + .toKtModules(env.project, env.applicationEnv) .filterIsInstance() + } private fun KtSourceModule.libraryDeps(jar: Path) = directRegularDependencies.filterIsInstance().filter { it.id == jar.pathString } - - private fun gradleProject( - path: String, - bootClassPath: Path? = null, - compileJar: Path? = null, - ): GradleModels.GradleProject { - val dir = "/tmp/collect-kt-modules${path.replace(':', '/')}" - return GradleModels.GradleProject - .newBuilder() - .setName(path.trimStart(':')) - .setPath(path) - .setProjectDirPath(dir) - .setBuildDirPath("$dir/build") - .setBuildScriptPath("$dir/build.gradle") - .apply { - if (bootClassPath != null) { - setAndroidProject( - AndroidModels.AndroidProject - .newBuilder() - .setProjectType(AndroidModels.ProjectType.LibraryProject) - .addBootClassPaths(bootClassPath.pathString), - ) - } - if (compileJar != null) { - setJavaProject( - JavaModels.JavaProject.newBuilder().addDependency( - JavaModels.JavaDependency - .newBuilder() - .setJarFilePath(compileJar.pathString) - .setScope(JavaModule.SCOPE_COMPILE) - .setExternalLibrary(JavaModels.JavaExternalLibraryDependency.getDefaultInstance()), - ), - ) - } - }.build() - } } diff --git a/lsp/kotlin/src/test/java/dev/mutwakil/androidide/lsp/kotlin/compiler/CompilationEnvironmentCloseTest.kt b/lsp/kotlin/src/test/java/dev/mutwakil/androidide/lsp/kotlin/compiler/CompilationEnvironmentCloseTest.kt new file mode 100644 index 0000000000..e496687063 --- /dev/null +++ b/lsp/kotlin/src/test/java/dev/mutwakil/androidide/lsp/kotlin/compiler/CompilationEnvironmentCloseTest.kt @@ -0,0 +1,95 @@ +package dev.mutwakil.androidide.lsp.kotlin.compiler + +import com.google.common.truth.Truth.assertThat +import dev.mutwakil.androidide.lsp.kotlin.compiler.modules.AnalysisPriority +import dev.mutwakil.androidide.lsp.kotlin.compiler.modules.ScheduledCancelChecker +import dev.mutwakil.androidide.lsp.kotlin.compiler.modules.UnpinnedAnalysis +import dev.mutwakil.androidide.lsp.kotlin.compiler.modules.analyzeMaybeDangling +import dev.mutwakil.androidide.lsp.kotlin.fixtures.KtLspTest +import dev.mutwakil.androidide.lsp.kotlin.fixtures.closeInWriteAction +import dev.mutwakil.androidide.progress.ICancelChecker +import org.junit.Assert.assertThrows +import org.junit.Test +import java.util.concurrent.CancellationException +import java.util.concurrent.CountDownLatch +import java.util.concurrent.TimeUnit +import java.util.concurrent.atomic.AtomicBoolean +import kotlin.concurrent.thread + +@OptIn(UnpinnedAnalysis::class) +class CompilationEnvironmentCloseTest : KtLspTest() { + @Test + fun `close waits for an in-flight read before disposing the project`() { + val entered = CountDownLatch(1) + val release = CountDownLatch(1) + val disposedDuringRead = AtomicBoolean() + + val reader = + thread { + env.project.read { + entered.countDown() + release.await(5, TimeUnit.SECONDS) + disposedDuringRead.set(env.project.isDisposed) + } + } + entered.await(5, TimeUnit.SECONDS) + + closeWhileBlocked(release) + reader.join(5_000) + + assertThat(disposedDuringRead.get()).isFalse() + assertThat(env.project.isDisposed).isTrue() + } + + @Test + fun `close waits for a running analysis before disposing the project`() { + val file = createSourceFile("Running.kt", "fun running() = 0") + val entered = CountDownLatch(1) + val release = CountDownLatch(1) + val disposedDuringAnalysis = AtomicBoolean() + + val analysis = + thread { + analyzeMaybeDangling(file, AnalysisPriority.INTERACTIVE, ScheduledCancelChecker(ICancelChecker.NOOP)) { + entered.countDown() + release.await(5, TimeUnit.SECONDS) + disposedDuringAnalysis.set(env.project.isDisposed) + } + } + entered.await(5, TimeUnit.SECONDS) + + closeWhileBlocked(release) + analysis.join(5_000) + + assertThat(disposedDuringAnalysis.get()).isFalse() + assertThat(env.project.isDisposed).isTrue() + } + + @Test + fun `analysis of a closed environment is cancelled`() { + val file = createSourceFile("Closed.kt", "fun closed() = 0") + env.closeInWriteAction() + + assertThrows(CancellationException::class.java) { + analyzeMaybeDangling(file, AnalysisPriority.INTERACTIVE, ScheduledCancelChecker(ICancelChecker.NOOP)) { } + } + } + + @Test + fun `evicting a file of a closed environment does not touch the disposed project`() { + val path = createSourceFile("Evicted.kt", "fun evicted() = 0").virtualFile.toNioPath() + env.closeInWriteAction() + + env.ktSymbolIndex.evictDiskCopy(path) + + assertThat(env.project.isDisposed).isTrue() + } + + // Starts the close, gives it time to dispose if it is going to, then lets the blocker finish. + private fun closeWhileBlocked(release: CountDownLatch) { + val closer = thread { env.closeInWriteAction() } + closer.join(500) + release.countDown() + closer.join(5_000) + } +} diff --git a/lsp/kotlin/src/test/java/dev/mutwakil/androidide/lsp/kotlin/compiler/KotlinModuleLayoutTest.kt b/lsp/kotlin/src/test/java/dev/mutwakil/androidide/lsp/kotlin/compiler/KotlinModuleLayoutTest.kt new file mode 100644 index 0000000000..d1e64c0727 --- /dev/null +++ b/lsp/kotlin/src/test/java/dev/mutwakil/androidide/lsp/kotlin/compiler/KotlinModuleLayoutTest.kt @@ -0,0 +1,90 @@ +package dev.mutwakil.androidide.lsp.kotlin.compiler + +import com.google.common.truth.Truth.assertThat +import dev.mutwakil.androidide.lsp.kotlin.fixtures.TestSources +import dev.mutwakil.androidide.lsp.kotlin.fixtures.gradleProject +import dev.mutwakil.androidide.projects.api.AndroidModule +import dev.mutwakil.androidide.projects.api.GradleProject +import dev.mutwakil.androidide.projects.api.JavaModule +import dev.mutwakil.androidide.projects.api.Workspace +import org.junit.Rule +import org.junit.Test +import org.junit.rules.TemporaryFolder +import java.nio.file.Path +import kotlin.io.path.createFile + +class KotlinModuleLayoutTest { + @get:Rule + val tempDir = TemporaryFolder() + + @Test + fun `two workspaces with the same structure have equal layouts`() { + val jar = tempJar("lib.jar") + + assertThat(layoutOf(compileJars = listOf(jar))).isEqualTo(layoutOf(compileJars = listOf(jar))) + } + + @Test + fun `adding a compile jar changes the layout`() { + val lib = tempJar("lib.jar") + val added = tempJar("added.jar") + + assertThat(layoutOf(compileJars = listOf(lib, added))).isNotEqualTo(layoutOf(compileJars = listOf(lib))) + } + + @Test + fun `the same compile jars in another order are the same layout`() { + val a = tempJar("a.jar") + val b = tempJar("b.jar") + + assertThat(layoutOf(compileJars = listOf(b, a))).isEqualTo(layoutOf(compileJars = listOf(a, b))) + } + + @Test + fun `a missing jar that appears changes the layout`() { + val jar = tempDir.root.toPath().resolve("late.jar") + val before = layoutOf(compileJars = listOf(jar)) + + jar.createFile() + + assertThat(layoutOf(compileJars = listOf(jar))).isNotEqualTo(before) + } + + @Test + fun `a changed jvm target changes the layout`() { + assertThat(layoutOf(jvmTarget = "17")).isNotEqualTo(layoutOf(jvmTarget = "11")) + } + + @Test + fun `a source dir that appears changes the layout`() { + val dir = tempDir.root.toPath().resolve("app/src/test/java") + val before = layoutWithUnitTests(dir) + + dir.toFile().mkdirs() + + assertThat(layoutWithUnitTests(dir)).isNotEqualTo(before) + } + + private fun layoutWithUnitTests(dir: Path): KotlinModuleLayout = + Workspace( + rootProject = GradleProject(gradleProject(":")), + subProjects = listOf(AndroidModule(gradleProject(":app", unitTests = TestSources(listOf(dir))))), + syncIssues = emptyList(), + ).kotlinModuleLayout() + + private fun tempJar(name: String): Path = + tempDir.root + .toPath() + .resolve(name) + .createFile() + + private fun layoutOf( + compileJars: List = emptyList(), + jvmTarget: String? = null, + ): KotlinModuleLayout = + Workspace( + rootProject = GradleProject(gradleProject(":")), + subProjects = listOf(JavaModule(gradleProject(":app", compileJars = compileJars, jvmTarget = jvmTarget))), + syncIssues = emptyList(), + ).kotlinModuleLayout() +} diff --git a/lsp/kotlin/src/test/java/dev/mutwakil/androidide/lsp/kotlin/compiler/KotlinProjectModelIndexTest.kt b/lsp/kotlin/src/test/java/dev/mutwakil/androidide/lsp/kotlin/compiler/KotlinProjectModelIndexTest.kt new file mode 100644 index 0000000000..918f98b11a --- /dev/null +++ b/lsp/kotlin/src/test/java/dev/mutwakil/androidide/lsp/kotlin/compiler/KotlinProjectModelIndexTest.kt @@ -0,0 +1,26 @@ +package dev.mutwakil.androidide.lsp.kotlin.compiler + +import com.google.common.truth.Truth.assertThat +import org.appdevforall.codeonthego.indexing.InMemoryIndex +import org.appdevforall.codeonthego.indexing.jvm.JVM_LIBRARY_SYMBOL_INDEX +import org.appdevforall.codeonthego.indexing.jvm.JvmSymbolDescriptor +import org.appdevforall.codeonthego.indexing.jvm.JvmSymbolIndex +import org.appdevforall.codeonthego.indexing.service.IndexRegistry +import org.appdevforall.codeonthego.indexing.util.BackgroundIndexer +import org.junit.Test + +class KotlinProjectModelIndexTest { + @Test + fun `index getters read the bound registry, not the global manager`() { + val registry = IndexRegistry() + val backing = InMemoryIndex(JvmSymbolDescriptor) + val library = JvmSymbolIndex(backing, BackgroundIndexer(backing)) + registry.register(JVM_LIBRARY_SYMBOL_INDEX, library) + + val libraryIndex = runCatching { newModel(registry).libraryIndex } + + assertThat(libraryIndex.getOrNull()).isSameInstanceAs(library) + } + + private fun newModel(registry: IndexRegistry) = KotlinProjectModel(registry) +} diff --git a/lsp/kotlin/src/test/java/dev/mutwakil/androidide/lsp/kotlin/compiler/index/InBodyEditRedeclarationTest.kt b/lsp/kotlin/src/test/java/dev/mutwakil/androidide/lsp/kotlin/compiler/index/InBodyEditRedeclarationTest.kt new file mode 100644 index 0000000000..74aedb0b0b --- /dev/null +++ b/lsp/kotlin/src/test/java/dev/mutwakil/androidide/lsp/kotlin/compiler/index/InBodyEditRedeclarationTest.kt @@ -0,0 +1,82 @@ +package dev.mutwakil.androidide.lsp.kotlin.compiler.index + +import com.google.common.truth.Truth.assertThat +import dev.mutwakil.androidide.eventbus.events.editor.ChangeType +import dev.mutwakil.androidide.eventbus.events.editor.DocumentChangeEvent +import dev.mutwakil.androidide.eventbus.events.editor.DocumentCloseEvent +import dev.mutwakil.androidide.eventbus.events.editor.DocumentOpenEvent +import dev.mutwakil.androidide.lsp.kotlin.compiler.modules.AnalysisPriority +import dev.mutwakil.androidide.lsp.kotlin.fixtures.KtLspTest +import dev.mutwakil.androidide.models.Range +import dev.mutwakil.androidide.projects.FileManager +import org.jetbrains.kotlin.analysis.api.components.KaDiagnosticCheckerFilter +import org.jetbrains.kotlin.com.intellij.psi.util.PsiTreeUtil +import org.jetbrains.kotlin.psi.KtElement +import org.junit.After +import org.junit.Test +import java.nio.file.Path + +/** + * Typing inside a function body must not make the enclosing class a redeclaration of itself. + * + * Reproduces GitHub issue #2152: open a file, let diagnostics run, type one space inside an empty + * function body, and the next diagnostics run reports `Redeclaration: class LocalC : Any` across the + * whole class. + */ +internal class InBodyEditRedeclarationTest : KtLspTest() { + override val enableParserEventSystem = true + + private val openedPaths = mutableListOf() + + @After + fun closeDocs() { + openedPaths.forEach { FileManager.onDocumentClose(DocumentCloseEvent(it)) } + openedPaths.clear() + } + + private fun localC(bodyLine: String) = "package p\n\nclass LocalC {\n fun ori() {\n$bodyLine\n }\n}\n" + + private val original = localC(" ") + + private val withSpaceInBody = localC(" ") + + private fun diagnosticsFor(path: Path): List = + env.ktSymbolIndex.withLiveKtFile(path) { live -> + live.analyzing(AnalysisPriority.DIAGNOSTICS, noopCancelChecker()) { ktFile -> + ktFile + .collectDiagnostics(KaDiagnosticCheckerFilter.EXTENDED_AND_COMMON_CHECKERS) + .map { "${it.factoryName}: ${it.defaultMessage}" } + } + }!! + + /** What a completion request does with the buffer: analyse a placeholder copy and resolve the caret's scope. */ + private fun completeAt( + path: Path, + offset: Int, + ) { + val buffer = FileManager.getDocumentContents(path) + val withPlaceholder = buffer.substring(0, offset) + "KT_COMPLETION_PLACEHOLDER" + buffer.substring(offset) + env.ktSymbolIndex.withLiveKtFile(path) { live -> + live.analyzingVariant(path.fileName.toString(), withPlaceholder, AnalysisPriority.INTERACTIVE, noopCancelChecker()) { variant -> + val position = PsiTreeUtil.getParentOfType(variant.findElementAt(offset), KtElement::class.java)!! + variant.scopeContext(position).scopes.size + } + } + } + + @Test + fun `typing a space inside a function body reports no redeclaration`() { + createSourceFile("LocalC.kt", original) + val path = env.sourceRoots.first().resolve("LocalC.kt") + FileManager.onDocumentOpen(DocumentOpenEvent(path, original, 1)) + openedPaths.add(path) + assertThat(diagnosticsFor(path)).isEmpty() + + FileManager.onDocumentContentChange( + DocumentChangeEvent(path, " ", withSpaceInBody, 2, ChangeType.INSERT, 1, Range.NONE), + ) + completeAt(path, withSpaceInBody.indexOf("ori() {\n") + "ori() {\n ".length) + + assertThat(diagnosticsFor(path)).isEmpty() + } +} diff --git a/lsp/kotlin/src/test/java/dev/mutwakil/androidide/lsp/kotlin/compiler/index/IndexWorkerDisposalTest.kt b/lsp/kotlin/src/test/java/dev/mutwakil/androidide/lsp/kotlin/compiler/index/IndexWorkerDisposalTest.kt index d1b14125d7..e439b035e3 100644 --- a/lsp/kotlin/src/test/java/dev/mutwakil/androidide/lsp/kotlin/compiler/index/IndexWorkerDisposalTest.kt +++ b/lsp/kotlin/src/test/java/dev/mutwakil/androidide/lsp/kotlin/compiler/index/IndexWorkerDisposalTest.kt @@ -45,6 +45,7 @@ class IndexWorkerDisposalTest : KtLspTest() { fileIndex = fileIndex(), sourceIndex = jvmIndex(), scope = CoroutineScope(Dispatchers.Default + SupervisorJob()), + resolvesTo = env.ktSymbolIndex::resolvesTo, ) /* diff --git a/lsp/kotlin/src/test/java/dev/mutwakil/androidide/lsp/kotlin/compiler/index/IndexWorkerOpenFileTest.kt b/lsp/kotlin/src/test/java/dev/mutwakil/androidide/lsp/kotlin/compiler/index/IndexWorkerOpenFileTest.kt new file mode 100644 index 0000000000..55133d2049 --- /dev/null +++ b/lsp/kotlin/src/test/java/dev/mutwakil/androidide/lsp/kotlin/compiler/index/IndexWorkerOpenFileTest.kt @@ -0,0 +1,69 @@ +package dev.mutwakil.androidide.lsp.kotlin.compiler.index + +import com.google.common.truth.Truth.assertThat +import dev.mutwakil.androidide.eventbus.events.editor.DocumentCloseEvent +import dev.mutwakil.androidide.eventbus.events.editor.DocumentOpenEvent +import dev.mutwakil.androidide.lsp.kotlin.fixtures.KtLspTest +import dev.mutwakil.androidide.projects.FileManager +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.runBlocking +import kotlinx.coroutines.withTimeout +import org.appdevforall.codeonthego.indexing.InMemoryIndex +import org.appdevforall.codeonthego.indexing.jvm.JvmSymbolDescriptor +import org.appdevforall.codeonthego.indexing.jvm.JvmSymbolIndex +import org.appdevforall.codeonthego.indexing.jvm.KtFileMetadataDescriptor +import org.appdevforall.codeonthego.indexing.jvm.KtFileMetadataIndex +import org.appdevforall.codeonthego.indexing.util.BackgroundIndexer +import org.junit.After +import org.junit.Test +import java.nio.file.Path + +/** + * A full pass over an open file must not analyse PsiManager's disk copy: FIR resolves the path to the + * live buffer's parse, so the disk copy's declarations have no FIR ("No fir element was found", + * ADFA-5763). The refresh that made the live parse queues its own index pass. + */ +internal class IndexWorkerOpenFileTest : KtLspTest() { + override val enableParserEventSystem = true + + private var openedPath: Path? = null + + @After + fun closeDoc() { + openedPath?.let { FileManager.onDocumentClose(DocumentCloseEvent(it)) } + } + + @Test + fun `a full pass skips the disk copy of an open file`(): Unit = + runBlocking { + val onDisk = "package p\n\nfun onDisk() = 0\n" + val vf = createSourceFile("Main.kt", onDisk).virtualFile + val path = env.sourceRoots.first().resolve("Main.kt") + FileManager.onDocumentOpen(DocumentOpenEvent(path, "$onDisk\nfun onlyInBuffer() = 1\n", 1)) + openedPath = path + env.ktSymbolIndex.refreshCurrentKtFile(path) + + val backing = InMemoryIndex(JvmSymbolDescriptor) + val sourceIndex = + object : JvmSymbolIndex(backing, BackgroundIndexer(backing)) { + override fun visibleSourceIds(): Collection? = null + } + val worker = + IndexWorker( + project = env.project, + queue = WorkerQueue(), + fileIndex = KtFileMetadataIndex(InMemoryIndex(KtFileMetadataDescriptor)), + sourceIndex = sourceIndex, + scope = CoroutineScope(Dispatchers.Default + SupervisorJob()), + resolvesTo = env.ktSymbolIndex::resolvesTo, + ) + + worker.submitCommand(IndexCommand.IndexSourceFile(vf)) + worker.submitCommand(IndexCommand.Stop) + withTimeout(10_000) { worker.start() } + + assertThat(sourceIndex.findByPrefix("").map { it.shortName }.toList()).isEmpty() + } +} diff --git a/lsp/kotlin/src/test/java/dev/mutwakil/androidide/lsp/kotlin/compiler/index/IndexWorkerPhaseLifecycleTest.kt b/lsp/kotlin/src/test/java/dev/mutwakil/androidide/lsp/kotlin/compiler/index/IndexWorkerPhaseLifecycleTest.kt index a06b3dec1c..a520528f63 100644 --- a/lsp/kotlin/src/test/java/dev/mutwakil/androidide/lsp/kotlin/compiler/index/IndexWorkerPhaseLifecycleTest.kt +++ b/lsp/kotlin/src/test/java/dev/mutwakil/androidide/lsp/kotlin/compiler/index/IndexWorkerPhaseLifecycleTest.kt @@ -18,8 +18,10 @@ import kotlinx.coroutines.launch import kotlinx.coroutines.runBlocking import kotlinx.coroutines.withTimeout import org.appdevforall.codeonthego.indexing.InMemoryIndex +import org.appdevforall.codeonthego.indexing.api.Index import org.appdevforall.codeonthego.indexing.jvm.JvmSymbolDescriptor import org.appdevforall.codeonthego.indexing.jvm.JvmSymbolIndex +import org.appdevforall.codeonthego.indexing.jvm.KtFileMetadata import org.appdevforall.codeonthego.indexing.jvm.KtFileMetadataDescriptor import org.appdevforall.codeonthego.indexing.jvm.KtFileMetadataIndex import org.appdevforall.codeonthego.indexing.util.BackgroundIndexer @@ -31,6 +33,7 @@ import org.jetbrains.kotlin.psi.KtFile import org.junit.After import org.junit.Test import java.nio.file.Path +import java.time.Instant import java.util.Collections import java.util.concurrent.locks.ReentrantReadWriteLock @@ -52,7 +55,7 @@ class IndexWorkerPhaseLifecycleTest { unmockkAll() } - private fun worker(): IndexWorker { + private fun worker(fileIndex: KtFileMetadataIndex = KtFileMetadataIndex(InMemoryIndex(KtFileMetadataDescriptor))): IndexWorker { val project = mockk() every { project.isDisposed } returns false every { project.getUserData(any>()) } returns ReentrantReadWriteLock() @@ -66,9 +69,10 @@ class IndexWorkerPhaseLifecycleTest { return IndexWorker( project = project, queue = WorkerQueue(), - fileIndex = KtFileMetadataIndex(InMemoryIndex(KtFileMetadataDescriptor)), + fileIndex = fileIndex, sourceIndex = sourceIndex, scope = CoroutineScope(Dispatchers.Default + SupervisorJob()), + resolvesTo = { _, _ -> true }, ) } @@ -200,9 +204,10 @@ class IndexWorkerPhaseLifecycleTest { mockPsiManager(ktFile = mockk()) mockkStatic("dev.mutwakil.androidide.lsp.kotlin.compiler.index.SourceFileIndexerKt") var attempts = 0 - coEvery { indexSourceFile(any(), any(), any(), any(), any()) } answers { + coEvery { indexSourceFile(any(), any(), any(), any(), any(), any()) } answers { if (++attempts == 1) throw AnalysisPreemptedException() sink.events += "indexed retry" + true } val worker = worker() @@ -233,7 +238,10 @@ class IndexWorkerPhaseLifecycleTest { runBlocking { Memprof.sink = sink mockkStatic("dev.mutwakil.androidide.lsp.kotlin.compiler.index.SourceFileIndexerKt") - coEvery { indexSourceFile(any(), any(), any(), any(), any()) } answers { sink.events += "indexed edit" } + coEvery { indexSourceFile(any(), any(), any(), any(), any(), any()) } answers { + sink.events += "indexed edit" + true + } val editedFile = mockk() every { editedFile.getUserData(any>()) } returns Path.of("/project/src/Edited.kt") val worker = worker() @@ -254,6 +262,55 @@ class IndexWorkerPhaseLifecycleTest { assertThat(sink.values["source_index_complete.indexed"]).isEqualTo(0L) } + @Test + fun `a file whose index pass writes nothing is not counted`(): Unit = + runBlocking { + Memprof.sink = sink + mockPsiManager(ktFile = mockk()) + mockkStatic("dev.mutwakil.androidide.lsp.kotlin.compiler.index.SourceFileIndexerKt") + coEvery { indexSourceFile(any(), any(), any(), any(), any(), any()) } returns false + val worker = worker() + + worker.submitCommand(IndexCommand.SourceScanningStarted(pass = 1)) + worker.submitCommand(IndexCommand.SourceScanningComplete(pass = 1)) + worker.submitCommand(IndexCommand.IndexSourceFile(sourceFile(), pass = 1)) + worker.submitCommand(IndexCommand.IndexingComplete(pass = 1)) + worker.submitCommand(IndexCommand.Stop) + + withTimeout(5_000) { worker.start() } + + assertThat(sink.values["source_index_complete.indexed"]).isEqualTo(0L) + } + + @Test + fun `a scan upsert into a closed index is not counted`(): Unit = + runBlocking { + Memprof.sink = sink + mockPsiManager(ktFile = mockk()) + mockkStatic("dev.mutwakil.androidide.lsp.kotlin.compiler.index.SourceFileIndexerKt") + every { any().toMetadata(any(), any()) } returns + KtFileMetadata( + filePath = "/project/src/Sample.kt", + packageFqName = "sample", + lastModified = Instant.EPOCH, + modificationStamp = 1L, + ) + val closedIndex = + object : Index by InMemoryIndex(KtFileMetadataDescriptor) { + override val isOpen = false + } + val worker = worker(fileIndex = KtFileMetadataIndex(closedIndex)) + + worker.submitCommand(IndexCommand.SourceScanningStarted(pass = 1)) + worker.submitCommand(IndexCommand.ScanSourceFile(sourceFile())) + worker.submitCommand(IndexCommand.SourceScanningComplete(pass = 1)) + worker.submitCommand(IndexCommand.Stop) + + withTimeout(5_000) { worker.start() } + + assertThat(sink.values["source_scan_complete.files"]).isEqualTo(0L) + } + private fun mockPsiManager(ktFile: KtFile?) { val psiManager = mockk() every { psiManager.findFile(any()) } returns ktFile diff --git a/lsp/kotlin/src/test/java/dev/mutwakil/androidide/lsp/kotlin/compiler/index/KotlinFileRemovalTest.kt b/lsp/kotlin/src/test/java/dev/mutwakil/androidide/lsp/kotlin/compiler/index/KotlinFileRemovalTest.kt new file mode 100644 index 0000000000..8f79bec3ec --- /dev/null +++ b/lsp/kotlin/src/test/java/dev/mutwakil/androidide/lsp/kotlin/compiler/index/KotlinFileRemovalTest.kt @@ -0,0 +1,118 @@ +package dev.mutwakil.androidide.lsp.kotlin.compiler.index + +import com.google.common.truth.Truth.assertThat +import dev.mutwakil.androidide.eventbus.events.editor.DocumentCloseEvent +import dev.mutwakil.androidide.eventbus.events.editor.DocumentOpenEvent +import dev.mutwakil.androidide.lsp.kotlin.fixtures.KtLspTest +import dev.mutwakil.androidide.projects.FileManager +import kotlinx.coroutines.delay +import kotlinx.coroutines.runBlocking +import kotlinx.coroutines.withTimeoutOrNull +import org.jetbrains.kotlin.analysis.api.components.KaDiagnosticCheckerFilter +import org.jetbrains.kotlin.com.intellij.openapi.application.ApplicationManager +import org.jetbrains.kotlin.psi.KtFile +import org.junit.After +import org.junit.Test +import java.nio.file.Files +import java.nio.file.Path +import kotlin.io.path.pathString +import kotlin.time.Duration.Companion.milliseconds +import kotlin.time.Duration.Companion.seconds + +/** + * A Kotlin file deleted from disk must leave the index: its metadata row, its cached disk copy, and + * every resolution that went through it. + */ +internal class KotlinFileRemovalTest : KtLspTest() { + private val openedPaths = mutableListOf() + + @After + fun closeDocs() { + openedPaths.forEach { FileManager.onDocumentClose(DocumentCloseEvent(it)) } + openedPaths.clear() + } + + private val declaringContent = "package p\n\nfun foo() = 1\n" + + private class Sources( + val declaring: Path, + val calling: KtFile, + ) + + /** A file declaring `foo`, and a caller whose analysis loads the declaring file's disk copy. */ + private fun createSources(): Sources { + createSourceFile("p/A.kt", declaringContent) + val calling = createSourceFile("p/B.kt", "package p\n\nfun bar() = foo()\n") + return Sources(env.sourceRoots.first().resolve("p/A.kt"), calling) + } + + private fun diagnosticNames(ktFile: KtFile): List = + analyze(ktFile) { + ktFile.collectDiagnostics(KaDiagnosticCheckerFilter.EXTENDED_AND_COMMON_CHECKERS).map { it.factoryName } + } + + /** Whether the index worker drops the metadata row for [path] within the timeout. */ + private fun rowRemoved(path: Path): Boolean = + runBlocking { + withTimeoutOrNull(10.seconds) { + while (env.ktSymbolIndex.fileIndex.contains(path.pathString)) { + delay(20.milliseconds) + } + } != null + } + + /* + * The unit-test application grants platform write access only inside runWriteAction, and the + * modification events onFileRemoved publishes assert it. Production's MockApplication always grants it. + */ + private fun removeInWriteAction(path: Path) { + ApplicationManager.getApplication().runWriteAction { runBlocking { env.onFileRemoved(path) } } + } + + @Test + fun deletedFileLosesItsRowAndDiskCopy() { + val sources = createSources() + assertThat(diagnosticNames(sources.calling)).doesNotContain("UNRESOLVED_REFERENCE") + assertThat(env.ktSymbolIndex.isDiskCopyCached(sources.declaring)).isTrue() + + Files.delete(sources.declaring) + env.ktSymbolIndex.syncIndexInBackground() + removeInWriteAction(sources.declaring) + val rowRemoved = rowRemoved(sources.declaring) + + assertThat(rowRemoved).isTrue() + assertThat(env.ktSymbolIndex.isDiskCopyCached(sources.declaring)).isFalse() + assertThat(diagnosticNames(sources.calling)).contains("UNRESOLVED_REFERENCE") + } + + /* + * The removal handler used to run only for paths that still existed, so a gone path reaching it is + * new: the VirtualFile may be stale or missing. The index worker is not started, so the deleted + * file's row stays and nothing but the invalidation can drop the caller's earlier resolution. + */ + @Test + fun removalOfAGoneFileInvalidatesTheModule() { + val sources = createSources() + assertThat(diagnosticNames(sources.calling)).doesNotContain("UNRESOLVED_REFERENCE") + + Files.delete(sources.declaring) + val failure = runCatching { removeInWriteAction(sources.declaring) }.exceptionOrNull() + + assertThat(failure).isNull() + assertThat(diagnosticNames(sources.calling)).contains("UNRESOLVED_REFERENCE") + } + + @Test + fun removalOfAnOpenFileClearsItsRow() { + val sources = createSources() + FileManager.onDocumentOpen(DocumentOpenEvent(sources.declaring, declaringContent, 1)) + openedPaths.add(sources.declaring) + assertThat(diagnosticNames(sources.calling)).doesNotContain("UNRESOLVED_REFERENCE") + + Files.delete(sources.declaring) + env.ktSymbolIndex.syncIndexInBackground() + removeInWriteAction(sources.declaring) + + assertThat(rowRemoved(sources.declaring)).isTrue() + } +} diff --git a/lsp/kotlin/src/test/java/dev/mutwakil/androidide/lsp/kotlin/compiler/index/KtSymbolIndexCloseTest.kt b/lsp/kotlin/src/test/java/dev/mutwakil/androidide/lsp/kotlin/compiler/index/KtSymbolIndexCloseTest.kt new file mode 100644 index 0000000000..6c5f9888db --- /dev/null +++ b/lsp/kotlin/src/test/java/dev/mutwakil/androidide/lsp/kotlin/compiler/index/KtSymbolIndexCloseTest.kt @@ -0,0 +1,68 @@ +package dev.mutwakil.androidide.lsp.kotlin.compiler.index + +import com.google.common.truth.Truth.assertThat +import dev.mutwakil.androidide.lsp.kotlin.fixtures.KtLspTest +import kotlinx.coroutines.delay +import kotlinx.coroutines.runBlocking +import org.appdevforall.codeonthego.indexing.InMemoryIndex +import org.appdevforall.codeonthego.indexing.api.Index +import org.appdevforall.codeonthego.indexing.jvm.JvmSymbolDescriptor +import org.appdevforall.codeonthego.indexing.jvm.JvmSymbolIndex +import org.appdevforall.codeonthego.indexing.jvm.KtFileMetadata +import org.appdevforall.codeonthego.indexing.jvm.KtFileMetadataDescriptor +import org.appdevforall.codeonthego.indexing.jvm.KtFileMetadataIndex +import org.appdevforall.codeonthego.indexing.util.BackgroundIndexer +import org.junit.Test +import java.nio.file.Paths +import java.util.concurrent.atomic.AtomicInteger + +class KtSymbolIndexCloseTest : KtLspTest() { + private val fileIndexReads = AtomicInteger() + + private fun slowFileIndex(): KtFileMetadataIndex { + val backing = InMemoryIndex(KtFileMetadataDescriptor) + return KtFileMetadataIndex( + object : Index by backing { + override suspend fun get(key: String): KtFileMetadata? { + fileIndexReads.incrementAndGet() + delay(READ_DELAY_MILLIS) + return backing.get(key) + } + }, + ) + } + + private fun jvmIndex(): JvmSymbolIndex { + val backing = InMemoryIndex(JvmSymbolDescriptor) + return object : JvmSymbolIndex(backing, BackgroundIndexer(backing)) { + override fun visibleSourceIds(): Collection? = null + } + } + + @Test + fun `close stops the worker without draining queued index work`(): Unit = + runBlocking { + val path = Paths.get(createSourceFile("Sample.kt", "fun foo() = 1").virtualFile.path) + val symbols = jvmIndex() + val index = + KtSymbolIndex( + kind = env.ktSymbolIndex.kind, + project = env.project, + modules = emptyList(), + fileIndex = slowFileIndex(), + sourceIndex = symbols, + libraryIndex = symbols, + ) + index.refreshSources() + repeat(QUEUED_FILES) { index.submitForIndexing(path) } + + index.close() + + assertThat(fileIndexReads.get()).isLessThan(QUEUED_FILES) + } + + private companion object { + const val QUEUED_FILES = 30 + const val READ_DELAY_MILLIS = 20L + } +} diff --git a/lsp/kotlin/src/test/java/dev/mutwakil/androidide/lsp/kotlin/compiler/index/PackageFileCacheTest.kt b/lsp/kotlin/src/test/java/dev/mutwakil/androidide/lsp/kotlin/compiler/index/PackageFileCacheTest.kt new file mode 100644 index 0000000000..8ea4d0cd1f --- /dev/null +++ b/lsp/kotlin/src/test/java/dev/mutwakil/androidide/lsp/kotlin/compiler/index/PackageFileCacheTest.kt @@ -0,0 +1,194 @@ +package dev.mutwakil.androidide.lsp.kotlin.compiler.index + +import com.google.common.truth.Truth.assertThat +import org.appdevforall.codeonthego.indexing.jvm.KtFileMetadataWrite +import org.junit.Test +import java.util.concurrent.CountDownLatch +import java.util.concurrent.TimeUnit +import java.util.concurrent.atomic.AtomicInteger +import java.util.concurrent.atomic.AtomicReference +import kotlin.concurrent.thread + +internal class PackageFileCacheTest { + private val backing = mutableMapOf>() + private val queries = AtomicInteger() + private val pathConversions = AtomicInteger() + + private val entered = AtomicReference() + private val release = AtomicReference() + private var held: CountDownLatch? = null + + private fun cache(max: Long = 100) = + PackageFileCache( + maxCachedFiles = max, + pathOf = { + pathConversions.incrementAndGet() + it + }, + query = { pkg -> + queries.incrementAndGet() + val snapshot = backing[pkg].orEmpty() + entered.getAndSet(null)?.countDown() + release.getAndSet(null)?.await(5, TimeUnit.SECONDS) + snapshot + }, + executor = Runnable::run, + ) + + private fun upserted( + path: String, + pkg: String, + ) = KtFileMetadataWrite.Upserted(path, pkg) + + @Test + fun secondLookupDoesNotQueryAgain() { + backing["p"] = listOf("/a.kt") + val cache = cache() + cache.filesFor("p") + assertThat(cache.filesFor("p")).containsExactly("/a.kt") + assertThat(queries.get()).isEqualTo(1) + } + + @Test + fun upsertDropsItsPackage() { + backing["p"] = listOf("/a.kt") + val cache = cache() + cache.filesFor("p") + backing["p"] = listOf("/a.kt", "/b.kt") + cache.onWrite(upserted("/b.kt", "p")) + assertThat(cache.filesFor("p")).containsExactly("/a.kt", "/b.kt") + } + + @Test + fun upsertDropsThePackageThatListedThePath() { + backing["old"] = listOf("/a.kt") + val cache = cache() + cache.filesFor("old") + backing["old"] = emptyList() + backing["new"] = listOf("/a.kt") + cache.onWrite(upserted("/a.kt", "new")) + assertThat(cache.filesFor("old")).isEmpty() + } + + @Test + fun upsertOfAFileAlreadyListedKeepsItsPackage() { + backing["p"] = listOf("/a.kt", "/b.kt") + val cache = cache() + cache.filesFor("p") + cache.onWrite(upserted("/a.kt", "p")) + assertThat(cache.filesFor("p")).containsExactly("/a.kt", "/b.kt") + assertThat(queries.get()).isEqualTo(1) + } + + @Test + fun writesDoNotConvertCachedPaths() { + backing["p"] = listOf("/a.kt", "/b.kt", "/c.kt") + val cache = cache() + cache.filesFor("p") + pathConversions.set(0) + cache.onWrite(KtFileMetadataWrite.Removed(listOf("/other.kt"))) + cache.onWrite(upserted("/other.kt", "q")) + assertThat(pathConversions.get()).isEqualTo(0) + } + + @Test + fun removedPathDropsItsPackage() { + backing["p"] = listOf("/a.kt", "/b.kt") + val cache = cache() + cache.filesFor("p") + backing["p"] = listOf("/b.kt") + cache.onWrite(KtFileMetadataWrite.Removed(listOf("/a.kt"))) + assertThat(cache.filesFor("p")).containsExactly("/b.kt") + } + + @Test + fun clearDropsEveryPackage() { + backing["p"] = listOf("/a.kt") + backing["q"] = listOf("/b.kt") + val cache = cache() + cache.filesFor("p") + cache.filesFor("q") + backing.clear() + cache.onWrite(KtFileMetadataWrite.Cleared) + assertThat(cache.filesFor("p")).isEmpty() + assertThat(cache.filesFor("q")).isEmpty() + } + + @Test + fun rootPackageIsCachedAndInvalidated() { + backing[""] = listOf("/a.kt") + val cache = cache() + cache.filesFor("") + cache.filesFor("") + assertThat(queries.get()).isEqualTo(1) + backing[""] = listOf("/a.kt", "/b.kt") + cache.onWrite(upserted("/b.kt", "")) + assertThat(cache.filesFor("")).containsExactly("/a.kt", "/b.kt") + } + + @Test + fun lookupRacingAWriteDoesNotCacheTheOldList() { + backing["p"] = listOf("/a.kt") + val cache = cache() + val racing = startLookupBlockedInQuery(cache, "p") + + backing["p"] = listOf("/a.kt", "/b.kt") + cache.onWrite(upserted("/b.kt", "p")) + finish(racing) + + assertThat(cache.filesFor("p")).containsExactly("/a.kt", "/b.kt") + assertThat(queries.get()).isEqualTo(2) + } + + @Test + fun evictedPackagesAreRebuilt() { + val cache = cache(max = 3) + val names = listOf("a", "b", "c", "d") + names.forEach { + backing[it] = listOf("/$it.kt") + cache.filesFor(it) + } + val evicted = + names.first { name -> + val before = queries.get() + cache.filesFor(name) + queries.get() != before + } + backing[evicted] = listOf("/changed.kt") + cache.onWrite(upserted("/changed.kt", evicted)) + assertThat(cache.filesFor(evicted)).containsExactly("/changed.kt") + } + + @Test + fun evictionRacingInvalidationLeavesNoStaleList() { + backing["a"] = listOf("/a.kt") + backing["b"] = listOf("/b.kt") + val cache = cache(max = 2) + val racing = startLookupBlockedInQuery(cache, "a") + + cache.filesFor("b") + backing["a"] = listOf("/a2.kt") + cache.onWrite(upserted("/a2.kt", "a")) + finish(racing) + + assertThat(cache.filesFor("a")).containsExactly("/a2.kt") + } + + private fun startLookupBlockedInQuery( + cache: PackageFileCache, + pkg: String, + ): Thread { + val enteredLatch = CountDownLatch(1) + entered.set(enteredLatch) + held = CountDownLatch(1).also { release.set(it) } + val thread = thread { cache.filesFor(pkg) } + assertThat(enteredLatch.await(5, TimeUnit.SECONDS)).isTrue() + return thread + } + + private fun finish(racing: Thread) { + held?.countDown() + racing.join(5000) + assertThat(racing.isAlive).isFalse() + } +} diff --git a/lsp/kotlin/src/test/java/dev/mutwakil/androidide/lsp/kotlin/compiler/index/SourceFileIndexerTest.kt b/lsp/kotlin/src/test/java/dev/mutwakil/androidide/lsp/kotlin/compiler/index/SourceFileIndexerTest.kt index 63e0f8643f..5138116ba7 100644 --- a/lsp/kotlin/src/test/java/dev/mutwakil/androidide/lsp/kotlin/compiler/index/SourceFileIndexerTest.kt +++ b/lsp/kotlin/src/test/java/dev/mutwakil/androidide/lsp/kotlin/compiler/index/SourceFileIndexerTest.kt @@ -4,11 +4,17 @@ import com.google.common.truth.Truth.assertThat import dev.mutwakil.androidide.lsp.kotlin.fixtures.KtLspTest import dev.mutwakil.androidide.progress.ICancelChecker import io.mockk.mockk +import kotlinx.coroutines.CancellationException import kotlinx.coroutines.runBlocking import org.appdevforall.codeonthego.indexing.InMemoryIndex +import org.appdevforall.codeonthego.indexing.api.Index +import org.appdevforall.codeonthego.indexing.jvm.JvmSymbol import org.appdevforall.codeonthego.indexing.jvm.JvmSymbolDescriptor import org.appdevforall.codeonthego.indexing.jvm.JvmSymbolIndex +import org.appdevforall.codeonthego.indexing.jvm.KtFileMetadataDescriptor +import org.appdevforall.codeonthego.indexing.jvm.KtFileMetadataIndex import org.appdevforall.codeonthego.indexing.util.BackgroundIndexer +import org.jetbrains.kotlin.psi.KtFile import org.junit.Test import java.io.FileNotFoundException import java.nio.file.NoSuchFileException @@ -21,6 +27,14 @@ class SourceFileIndexerTest : KtLspTest() { } } + private fun buildFileIndex() = KtFileMetadataIndex(InMemoryIndex(KtFileMetadataDescriptor)) + + private suspend fun index( + file: KtFile, + fileIndex: KtFileMetadataIndex, + symbolsIndex: JvmSymbolIndex, + ) = indexSourceFile(env.project, file, fileIndex, symbolsIndex, ICancelChecker.NOOP, env.ktSymbolIndex::resolvesTo) + @Test fun `indexer ignores local property inside function body`(): Unit = runBlocking { @@ -46,7 +60,7 @@ class SourceFileIndexerTest : KtLspTest() { val symbolsIndex = buildSymbolIndex() - indexSourceFile(env.project, file, mockk(relaxed = true), symbolsIndex, ICancelChecker.NOOP) + index(file, mockk(relaxed = true), symbolsIndex) val names = symbolsIndex.findByPrefix("").map { it.shortName }.toSet() assertThat(names).containsExactly("doWork", "fetchStatus") @@ -68,7 +82,7 @@ class SourceFileIndexerTest : KtLspTest() { val symbolsIndex = buildSymbolIndex() - indexSourceFile(env.project, file, mockk(relaxed = true), symbolsIndex, ICancelChecker.NOOP) + index(file, mockk(relaxed = true), symbolsIndex) val names = symbolsIndex.findByPrefix("").map { it.shortName }.toSet() assertThat(names).containsExactly("outer") @@ -88,12 +102,78 @@ class SourceFileIndexerTest : KtLspTest() { val symbolsIndex = buildSymbolIndex() - indexSourceFile(env.project, file, mockk(relaxed = true), symbolsIndex, ICancelChecker.NOOP) + index(file, mockk(relaxed = true), symbolsIndex) val names = symbolsIndex.findByPrefix("").map { it.shortName }.toSet() assertThat(names).containsExactly("globalConfig", "compute") } + @Test + fun `indexing a new file reports a write`(): Unit = + runBlocking { + val file = createSourceFile("Fresh.kt", "fun fresh() = 0") + + val wrote = index(file, buildFileIndex(), buildSymbolIndex()) + + assertThat(wrote).isTrue() + } + + @Test + fun `indexing an unchanged file reports no write`(): Unit = + runBlocking { + val file = createSourceFile("Unchanged.kt", "fun unchanged() = 0") + val fileIndex = buildFileIndex() + val symbolsIndex = buildSymbolIndex() + index(file, fileIndex, symbolsIndex) + + val wrote = index(file, fileIndex, symbolsIndex) + + assertThat(wrote).isFalse() + } + + @Test + fun `indexing into a closed symbol index reports no write`(): Unit = + runBlocking { + val file = createSourceFile("Closed.kt", "fun closed() = 0") + val closedBacking = + object : Index by InMemoryIndex(JvmSymbolDescriptor) { + override val isOpen = false + } + val symbolsIndex = + object : JvmSymbolIndex(closedBacking, BackgroundIndexer(closedBacking)) { + override fun visibleSourceIds(): Collection? = null + } + + val wrote = index(file, buildFileIndex(), symbolsIndex) + + assertThat(wrote).isFalse() + } + + @Test + fun `a throwing resolver skips the file instead of escaping`(): Unit = + runBlocking { + val file = createSourceFile("Throws.kt", "fun throws() = 0") + val symbolsIndex = buildSymbolIndex() + + val wrote = + indexSourceFile(env.project, file, buildFileIndex(), symbolsIndex, ICancelChecker.NOOP) { _, _ -> + throw IllegalStateException("refresh failed") + } + + assertThat(wrote).isFalse() + assertThat(symbolsIndex.findByPrefix("").toList()).isEmpty() + } + + @Test(expected = CancellationException::class) + fun `a cancelled resolver still cancels the pass`(): Unit = + runBlocking { + val file = createSourceFile("Cancelled.kt", "fun cancelled() = 0") + + indexSourceFile(env.project, file, buildFileIndex(), buildSymbolIndex(), ICancelChecker.NOOP) { _, _ -> + throw CancellationException("cancelled") + } + } + @Test fun `isMissingClasspathFile detects a direct NoSuchFileException`() { assertThat(NoSuchFileException("/caches/transforms/x/classes.jar").isMissingClasspathFile()) diff --git a/lsp/kotlin/src/test/java/dev/mutwakil/androidide/lsp/kotlin/compiler/modules/KtLibraryModuleScopeTest.kt b/lsp/kotlin/src/test/java/dev/mutwakil/androidide/lsp/kotlin/compiler/modules/KtLibraryModuleScopeTest.kt new file mode 100644 index 0000000000..2f1429e666 --- /dev/null +++ b/lsp/kotlin/src/test/java/dev/mutwakil/androidide/lsp/kotlin/compiler/modules/KtLibraryModuleScopeTest.kt @@ -0,0 +1,121 @@ +package dev.mutwakil.androidide.lsp.kotlin.compiler.modules + +import com.google.common.truth.Truth.assertThat +import dev.mutwakil.androidide.lsp.kotlin.fixtures.KtLspTest +import org.jetbrains.kotlin.analysis.api.KaImplementationDetail +import org.jetbrains.kotlin.analysis.api.impl.base.util.LibraryUtils +import org.jetbrains.kotlin.com.intellij.openapi.vfs.VirtualFile +import org.junit.Test +import java.nio.file.Path +import java.util.zip.ZipEntry +import java.util.zip.ZipOutputStream +import kotlin.io.path.createDirectories +import kotlin.io.path.name +import kotlin.io.path.outputStream +import kotlin.io.path.writeBytes + +@OptIn(KaImplementationDetail::class) +class KtLibraryModuleScopeTest : KtLspTest() { + @Test + fun `scope contains every entry of its jar and nothing of another jar`() { + val a = libraryModule(writeJar("a.jar", "p/A.class", "p/q/B.class")) + val b = libraryModule(writeJar("b.jar", "p/A.class", "r/C.class")) + + val scope = a.baseContentScope + + assertThat(entriesOf(a).filterNot { scope.contains(it) }).isEmpty() + assertThat(entriesOf(b).filter { scope.contains(it) }).isEmpty() + } + + @Test + fun `scope matches the old url-set scope on a jar and a class directory`() { + val jar = libraryModule(writeJar("a.jar", "p/A.class", "p/q/B.class")) + val classDir = libraryModule(writeClassDirectory("classes", "p/D.class", "p/s/E.class")) + val foreign = libraryModule(writeJar("b.jar", "p/A.class", "r/C.class")) + val module = libraryModule(jar.contentRoots + classDir.contentRoots) + val oldUrls = module.computeFiles(extended = true).map { it.url }.toSet() + + val scope = module.baseContentScope + + val everyFile = listOf(jar, classDir, foreign).flatMap { entriesOf(it) } + assertThat(everyFile.associate { it.url to scope.contains(it) }) + .isEqualTo(everyFile.associate { it.url to (it.url in oldUrls) }) + } + + @Test + fun `class file added to a class directory after the scope is built is contained`() { + val dir = writeClassDirectory("classes", "p/D.class") + val module = libraryModule(dir) + val scope = module.baseContentScope + + val added = dir.resolve("p/Added.class").also { it.writeBytes(byteArrayOf(1)) } + val addedFile = findAfterRefresh(module, added) + + assertThat(scope.contains(addedFile)).isTrue() + } + + @Test + fun `library module base scope holds only its roots`() { + val module = libraryModule(writeJar("a.jar", "p/A.class", "p/q/B.class")) + + val scope = module.baseContentScope as LibraryRootsScope + + assertThat(scope.roots).isEqualTo(module.computeFiles(extended = false).toSet()) + } + + private fun libraryModule(vararg roots: Path): KtLibraryModule = libraryModule(roots.toSet()) + + private fun libraryModule(roots: Set): KtLibraryModule = + buildKtLibraryModule(env.project, env.applicationEnv) { + id = roots.joinToString { it.name } + roots.forEach { addContentRoot(it) } + } + + private fun entriesOf(module: KtLibraryModule): List = + module.computeFiles(extended = false).flatMap { LibraryUtils.getAllVirtualFilesFromRoot(it, includeRoot = true) }.toList() + + private fun findAfterRefresh( + module: KtLibraryModule, + path: Path, + ): VirtualFile { + val root = module.computeFiles(extended = false).single() + root.refresh(false, true) + return LibraryUtils + .getAllVirtualFilesFromRoot(root, includeRoot = true) + .single { it.name == path.name } + } + + private fun writeJar( + name: String, + vararg entries: String, + ): Path { + val jar = + lspTestRule.tempDir.root + .toPath() + .resolve(name) + ZipOutputStream(jar.outputStream()).use { zip -> + entries.forEach { + zip.putNextEntry(ZipEntry(it)) + zip.write(1) + zip.closeEntry() + } + } + return jar + } + + private fun writeClassDirectory( + name: String, + vararg entries: String, + ): Path { + val dir = + lspTestRule.tempDir.root + .toPath() + .resolve(name) + entries.forEach { + val file = dir.resolve(it) + file.parent.createDirectories() + file.writeBytes(byteArrayOf(1)) + } + return dir + } +} diff --git a/lsp/kotlin/src/test/java/dev/mutwakil/androidide/lsp/kotlin/compiler/modules/LibraryRootsScopeTest.kt b/lsp/kotlin/src/test/java/dev/mutwakil/androidide/lsp/kotlin/compiler/modules/LibraryRootsScopeTest.kt new file mode 100644 index 0000000000..9c53772fd5 --- /dev/null +++ b/lsp/kotlin/src/test/java/dev/mutwakil/androidide/lsp/kotlin/compiler/modules/LibraryRootsScopeTest.kt @@ -0,0 +1,73 @@ +package dev.mutwakil.androidide.lsp.kotlin.compiler.modules + +import com.google.common.truth.Truth.assertThat +import dev.mutwakil.androidide.lsp.kotlin.compiler.vfs.ListingJarFileSystem +import dev.mutwakil.androidide.lsp.kotlin.fixtures.KtLspTest +import dev.mutwakil.androidide.zipfs2.listing.JarListing +import dev.mutwakil.androidide.zipfs2.listing.JarListingCache +import org.junit.Test +import java.nio.file.Files +import java.nio.file.Path +import java.nio.file.attribute.FileTime +import java.util.zip.ZipEntry +import java.util.zip.ZipOutputStream +import kotlin.io.path.outputStream + +class LibraryRootsScopeTest : KtLspTest() { + private val fileSystem = ListingJarFileSystem(JarListingCache(JarListing::read)) + + @Test + fun `scope still contains an entry of a jar replaced in place`() { + val jar = writeJar("a.jar", "p/A.class") + val oldRoot = fileSystem.findFileByPath("$jar!/")!! + val scope = LibraryRootsScope(env.project, setOf(oldRoot)) + + writeJar("a.jar", "p/A.class", "p/B.class") + Files.setLastModifiedTime(jar, FileTime.fromMillis(Files.getLastModifiedTime(jar).toMillis() + 10_000)) + val replaced = fileSystem.findFileByPath("$jar!/p/B.class")!! + + assertThat(oldRoot.isValid).isFalse() + assertThat(scope.contains(replaced)).isTrue() + } + + @Test + fun `library jar roots come from the listing jar file system`() { + val module = + buildKtLibraryModule(env.project, env.applicationEnv) { + id = "a" + addContentRoot(writeJar("a.jar", "p/A.class")) + } + + val root = module.computeFiles(extended = false).single() + + assertThat(env.applicationEnv.jarFileSystem).isInstanceOf(ListingJarFileSystem::class.java) + assertThat(root.fileSystem).isSameInstanceAs(env.applicationEnv.jarFileSystem) + } + + @Test + fun `scope does not contain an entry of another jar`() { + val scope = LibraryRootsScope(env.project, setOf(fileSystem.findFileByPath("${writeJar("a.jar", "p/A.class")}!/")!!)) + + val foreign = fileSystem.findFileByPath("${writeJar("b.jar", "p/A.class")}!/p/A.class")!! + + assertThat(scope.contains(foreign)).isFalse() + } + + private fun writeJar( + name: String, + vararg entries: String, + ): Path { + val jar = + lspTestRule.tempDir.root + .toPath() + .resolve(name) + ZipOutputStream(jar.outputStream()).use { zip -> + entries.forEach { + zip.putNextEntry(ZipEntry(it)) + zip.write(1) + zip.closeEntry() + } + } + return jar + } +} diff --git a/lsp/kotlin/src/test/java/dev/mutwakil/androidide/lsp/kotlin/compiler/services/ClassLikeWithIdTest.kt b/lsp/kotlin/src/test/java/dev/mutwakil/androidide/lsp/kotlin/compiler/services/ClassLikeWithIdTest.kt new file mode 100644 index 0000000000..14a82673d8 --- /dev/null +++ b/lsp/kotlin/src/test/java/dev/mutwakil/androidide/lsp/kotlin/compiler/services/ClassLikeWithIdTest.kt @@ -0,0 +1,55 @@ +package dev.mutwakil.androidide.lsp.kotlin.compiler.services + +import com.google.common.truth.Truth.assertThat +import dev.mutwakil.androidide.lsp.kotlin.compiler.read +import dev.mutwakil.androidide.lsp.kotlin.fixtures.KtLspTest +import org.jetbrains.kotlin.name.ClassId +import org.jetbrains.kotlin.name.FqName +import org.jetbrains.kotlin.name.Name +import org.jetbrains.kotlin.psi.KtClassLikeDeclaration +import org.jetbrains.kotlin.psi.KtClassOrObject +import org.jetbrains.kotlin.psi.KtFile +import org.jetbrains.kotlin.psi.KtTypeAlias +import org.junit.Test + +class ClassLikeWithIdTest : KtLspTest() { + private var passes = 0 + + private fun parse(vararg sources: String): List = + env.project.read { sources.mapIndexed { i, text -> env.parser.createFile("F$i.kt", text) } } + + private fun lookup( + files: List, + name: String, + ): KtClassLikeDeclaration? = + env.project.read { + val counted = + sequence { + passes++ + yieldAll(files) + } + counted.classLikeWithId(ClassId(FqName("p"), Name.identifier(name))) + } + + @Test + fun aMissWalksThePackageOnce() { + val files = parse("package p\n\nclass A\n", "package p\n\nfun b() = 1\n") + + assertThat(lookup(files, "Missing")).isNull() + assertThat(passes).isEqualTo(1) + } + + @Test + fun aClassWinsOverATypeAliasListedBeforeIt() { + val files = parse("package p\n\ntypealias X = Int\n", "package p\n\nclass X\n") + + assertThat(lookup(files, "X")).isInstanceOf(KtClassOrObject::class.java) + } + + @Test + fun aTypeAliasIsFoundWhenNoClassMatches() { + val files = parse("package p\n\nclass A\n", "package p\n\ntypealias X = Int\n") + + assertThat(lookup(files, "X")).isInstanceOf(KtTypeAlias::class.java) + } +} diff --git a/lsp/kotlin/src/test/java/dev/mutwakil/androidide/lsp/kotlin/compiler/services/DeclarationStalenessTest.kt b/lsp/kotlin/src/test/java/dev/mutwakil/androidide/lsp/kotlin/compiler/services/DeclarationStalenessTest.kt new file mode 100644 index 0000000000..f508bdc33d --- /dev/null +++ b/lsp/kotlin/src/test/java/dev/mutwakil/androidide/lsp/kotlin/compiler/services/DeclarationStalenessTest.kt @@ -0,0 +1,161 @@ +package dev.mutwakil.androidide.lsp.kotlin.compiler.services + +import com.google.common.truth.Truth.assertThat +import dev.mutwakil.androidide.eventbus.events.editor.ChangeType +import dev.mutwakil.androidide.eventbus.events.editor.DocumentChangeEvent +import dev.mutwakil.androidide.eventbus.events.editor.DocumentCloseEvent +import dev.mutwakil.androidide.eventbus.events.editor.DocumentOpenEvent +import dev.mutwakil.androidide.lsp.kotlin.fixtures.KtLspTest +import dev.mutwakil.androidide.models.Range +import dev.mutwakil.androidide.projects.FileManager +import kotlinx.coroutines.runBlocking +import org.jetbrains.kotlin.analysis.api.components.KaDiagnosticCheckerFilter +import org.jetbrains.kotlin.name.FqName +import org.jetbrains.kotlin.psi.KtFile +import org.junit.After +import org.junit.Test +import java.nio.file.Path + +/** + * The declaration provider must never answer from a stale package file list. + * + * Each test edits one file the way the editor does, then analyses another file in the same package. + */ +internal class DeclarationStalenessTest : KtLspTest() { + override val enableParserEventSystem = true + + private val openedPaths = mutableListOf() + + @After + fun closeDocs() { + openedPaths.forEach { FileManager.onDocumentClose(DocumentCloseEvent(it)) } + openedPaths.clear() + } + + @Test + fun addedFunctionResolvesInAnotherFile() = assertAddedDeclarationResolves("fun foo() = 1", "fun b() = foo()") + + @Test + fun removedFunctionIsUnresolvedInAnotherFile() = assertRemovedDeclarationIsUnresolved("fun foo() = 1", "fun b() = foo()") + + @Test + fun addedPropertyResolvesInAnotherFile() = assertAddedDeclarationResolves("val foo = 1", "fun b() = foo") + + @Test + fun removedPropertyIsUnresolvedInAnotherFile() = assertRemovedDeclarationIsUnresolved("val foo = 1", "fun b() = foo") + + @Test + fun addedClassResolvesInAnotherFile() = assertAddedDeclarationResolves("class Foo", "fun b() = Foo()") + + @Test + fun removedClassIsUnresolvedInAnotherFile() = assertRemovedDeclarationIsUnresolved("class Foo", "fun b() = Foo()") + + @Test + fun addedTypealiasResolvesInAnotherFile() = assertAddedDeclarationResolves("typealias Foo = String", "fun b(x: Foo) = x") + + @Test + fun removedTypealiasIsUnresolvedInAnotherFile() = assertRemovedDeclarationIsUnresolved("typealias Foo = String", "fun b(x: Foo) = x") + + @Test + fun addedNestedClassResolvesInAnotherFile() = + assertAddedDeclarationResolves("class Outer { class Inner }", "fun b() = Outer.Inner()", without = "class Outer") + + @Test + fun removedNestedClassIsUnresolvedInAnotherFile() = + assertRemovedDeclarationIsUnresolved("class Outer { class Inner }", "fun b() = Outer.Inner()", without = "class Outer") + + @Test + fun newFileInPackageIsFound() { + val b = createSourceFile("B.kt", "package p\nfun b() = bar()") + env.ktSymbolIndex.sourceFilesForPackage(FqName("p")) + + createSourceFile("C.kt", "package p\nfun bar() = 1") + + assertThat(diagnosticsOf(b)).doesNotContain(UNRESOLVED_REFERENCE) + } + + @Test + fun packageChangeMovesTheFile() { + createSourceFile("C.kt", "package p\nfun bar() = 1") + val path = sourcePath("C.kt") + env.ktSymbolIndex.sourceFilesForPackage(FqName("p")) + env.ktSymbolIndex.sourceFilesForPackage(FqName("q")) + + env.ktSymbolIndex.evictDiskCopy(path) + val moved = createSourceFile("C.kt", "package q\nfun bar() = 1") + assertThat(moved.packageFqName.asString()).isEqualTo("q") + + assertThat(pathsIn("p")).doesNotContain(path) + assertThat(pathsIn("q")).contains(path) + } + + /** A's disk copy lacks [declaration]; only the live document has it. */ + private fun assertAddedDeclarationResolves( + declaration: String, + usage: String, + without: String = "", + ) { + val withoutText = "package p\n$without" + val a = openDocument("A.kt", withoutText) + val b = createSourceFile("B.kt", "package p\n$usage") + + edit(a, withoutText, "package p\n$declaration", 2) + + assertThat(diagnosticsOf(b)).doesNotContain(UNRESOLVED_REFERENCE) + } + + /** A's disk copy has [declaration]; only the live document has dropped it. */ + private fun assertRemovedDeclarationIsUnresolved( + declaration: String, + usage: String, + without: String = "", + ) { + val withText = "package p\n$declaration" + val a = openDocument("A.kt", withText) + val b = createSourceFile("B.kt", "package p\n$usage") + + edit(a, withText, "package p\n$without", 2) + + assertThat(diagnosticsOf(b)).contains(UNRESOLVED_REFERENCE) + } + + private fun openDocument( + relativePath: String, + text: String, + ): Path { + createSourceFile(relativePath, text) + val path = sourcePath(relativePath) + FileManager.onDocumentOpen(DocumentOpenEvent(path, text, 1)) + openedPaths.add(path) + return path + } + + /** Changes the open document at [path], then waits for the live refresh, as the editor's next request would. */ + private fun edit( + path: Path, + oldText: String, + newText: String, + version: Int, + ) { + FileManager.onDocumentContentChange( + DocumentChangeEvent(path, oldText, newText, version, ChangeType.NEW_TEXT, 0, Range.NONE), + ) + runBlocking { env.ktSymbolIndex.refreshCurrentKtFile(path) } + } + + private fun diagnosticsOf(file: KtFile): List = + analyzeMaybeDanglingForTest(file) { + file + .collectDiagnostics(KaDiagnosticCheckerFilter.EXTENDED_AND_COMMON_CHECKERS) + .map { it.factoryName } + } + + private fun pathsIn(packageFqName: String): List = + env.ktSymbolIndex.sourceFilesForPackage(FqName(packageFqName)).map { it.toNioPath() } + + private fun sourcePath(relativePath: String): Path = env.sourceRoots.first().resolve(relativePath) + + private companion object { + const val UNRESOLVED_REFERENCE = "UNRESOLVED_REFERENCE" + } +} diff --git a/lsp/kotlin/src/test/java/dev/mutwakil/androidide/lsp/kotlin/compiler/services/DirectInheritorsProviderTest.kt b/lsp/kotlin/src/test/java/dev/mutwakil/androidide/lsp/kotlin/compiler/services/DirectInheritorsProviderTest.kt new file mode 100644 index 0000000000..598f2c3edf --- /dev/null +++ b/lsp/kotlin/src/test/java/dev/mutwakil/androidide/lsp/kotlin/compiler/services/DirectInheritorsProviderTest.kt @@ -0,0 +1,82 @@ +package dev.mutwakil.androidide.lsp.kotlin.compiler.services + +import dev.mutwakil.androidide.lsp.kotlin.fixtures.KtLspTest +import org.jetbrains.kotlin.analysis.api.platform.declarations.KotlinDirectInheritorsProvider +import org.jetbrains.kotlin.analysis.api.platform.projectStructure.KotlinProjectStructureProvider +import org.jetbrains.kotlin.com.intellij.psi.impl.source.PsiFileImpl +import org.jetbrains.kotlin.com.intellij.psi.search.GlobalSearchScope +import org.jetbrains.kotlin.psi.KtClass +import org.jetbrains.kotlin.psi.KtClassOrObject +import org.jetbrains.kotlin.psi.KtFile +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Test + +class DirectInheritorsProviderTest : KtLspTest() { + @Test + fun `same-package search finds inheritors declared in other files of the base class's package`() { + val base = createSourceFile("p/Base.kt", "package p\nsealed class Base") + createSourceFile("p/A.kt", "package p\nclass A : Base()") + createSourceFile("p/Outer.kt", "package p\nclass Outer { class B : Base() }") + createSourceFile("p/Unrelated.kt", "package p\nclass Unrelated : Any()") + + assertEquals(listOf("p.A", "p.Outer.B"), samePackageInheritorsOf(base, "Base")) + } + + @Test + fun `same-package search finds inheritors that extend the base class through a type alias from another package`() { + val base = createSourceFile("p/Base.kt", "package p\nsealed class Base") + createSourceFile("q/Alias.kt", "package q\ntypealias Aliased = p.Base") + createSourceFile("p/ViaAlias.kt", "package p\nimport q.Aliased\nclass ViaAlias : Aliased()") + + assertEquals(listOf("p.ViaAlias"), samePackageInheritorsOf(base, "Base")) + } + + @Test + fun `same-package search does not load files outside the base class's package`() { + val base = createSourceFile("p/Base.kt", "package p\nsealed class Base") + // Not registered with the file index, so nothing but a whole-module walk can reach it. + val otherPackage = env.createFile("src", "q/Other.kt", "package q\nclass Other : Any()") as PsiFileImpl + assertNull(otherPackage.treeElement) + + samePackageInheritorsOf(base, "Base") + + assertNull(otherPackage.treeElement) + } + + @Test + fun `full search still finds inheritors in other packages`() { + val base = createSourceFile("p/Base.kt", "package p\nopen class Base") + createSourceFile("p/A.kt", "package p\nclass A : Base()") + createSourceFile("q/B.kt", "package q\nclass B : p.Base()") + + val all = inheritorsOf(base, "Base") { ktClass, scope -> getDirectKotlinInheritors(ktClass, scope, false) } + + assertEquals(listOf("p.A", "q.B"), all) + assertEquals(listOf("p.A"), samePackageInheritorsOf(base, "Base")) + } + + private fun samePackageInheritorsOf( + file: KtFile, + className: String, + ): List = + inheritorsOf(file, className) { ktClass, scope -> + getSamePackageDirectKotlinInheritors(ktClass, scope, false) + } + + private fun inheritorsOf( + file: KtFile, + className: String, + search: KotlinDirectInheritorsProvider.(KtClass, GlobalSearchScope) -> Iterable, + ): List { + val ktClass = file.declarations.filterIsInstance().single { it.name == className } + return analyzeMaybeDanglingForTest(file) { + val scope = KotlinProjectStructureProvider.getModule(env.project, ktClass, useSiteModule = null).contentScope + KotlinDirectInheritorsProvider + .getInstance(env.project) + .search(ktClass, scope) + .map { it.fqName!!.asString() } + .sorted() + } + } +} diff --git a/lsp/kotlin/src/test/java/dev/mutwakil/androidide/lsp/kotlin/compiler/services/PrivateTopLevelResolutionTest.kt b/lsp/kotlin/src/test/java/dev/mutwakil/androidide/lsp/kotlin/compiler/services/PrivateTopLevelResolutionTest.kt new file mode 100644 index 0000000000..cd45c64070 --- /dev/null +++ b/lsp/kotlin/src/test/java/dev/mutwakil/androidide/lsp/kotlin/compiler/services/PrivateTopLevelResolutionTest.kt @@ -0,0 +1,44 @@ +package dev.mutwakil.androidide.lsp.kotlin.compiler.services + +import com.google.common.truth.Truth.assertThat +import dev.mutwakil.androidide.lsp.kotlin.compiler.read +import dev.mutwakil.androidide.lsp.kotlin.fixtures.KtLspTest +import org.jetbrains.kotlin.analysis.api.components.KaDiagnosticCheckerFilter +import org.jetbrains.kotlin.name.Name +import org.junit.Test + +class PrivateTopLevelResolutionTest : KtLspTest() { + private val file by lazy { + createSourceFile( + "p/Private.kt", + """ + package p + + private fun helper(): Int = 1 + + fun use(): Int = helper() + + private val secret = 2 + + fun read(): Int = secret + """.trimIndent(), + ) + } + + @Test + fun privateTopLevelDeclarationsResolveWithinTheirFile() { + val diagnostics = + analyzeMaybeDanglingForTest(file) { + file.collectDiagnostics(KaDiagnosticCheckerFilter.EXTENDED_AND_COMMON_CHECKERS).map { it.factoryName } + } + + assertThat(diagnostics).isEmpty() + } + + @Test + fun privateTopLevelFunctionsAreListed() { + val found = env.project.read { sequenceOf(file).topLevelFunctions(Name.identifier("helper")).toList() } + + assertThat(found).hasSize(1) + } +} diff --git a/lsp/kotlin/src/test/java/dev/mutwakil/androidide/lsp/kotlin/compiler/services/TopLevelDeclarationsEquivalenceTest.kt b/lsp/kotlin/src/test/java/dev/mutwakil/androidide/lsp/kotlin/compiler/services/TopLevelDeclarationsEquivalenceTest.kt new file mode 100644 index 0000000000..008405ea6a --- /dev/null +++ b/lsp/kotlin/src/test/java/dev/mutwakil/androidide/lsp/kotlin/compiler/services/TopLevelDeclarationsEquivalenceTest.kt @@ -0,0 +1,114 @@ +package dev.mutwakil.androidide.lsp.kotlin.compiler.services + +import com.google.common.truth.Truth.assertThat +import dev.mutwakil.androidide.lsp.kotlin.compiler.read +import dev.mutwakil.androidide.lsp.kotlin.fixtures.KtLspTest +import org.jetbrains.kotlin.com.intellij.psi.util.PsiTreeUtil +import org.jetbrains.kotlin.name.ClassId +import org.jetbrains.kotlin.name.Name +import org.jetbrains.kotlin.psi.KtCallableDeclaration +import org.jetbrains.kotlin.psi.KtClassLikeDeclaration +import org.jetbrains.kotlin.psi.KtClassOrObject +import org.jetbrains.kotlin.psi.KtFile +import org.jetbrains.kotlin.psi.KtNamedFunction +import org.jetbrains.kotlin.psi.KtProperty +import org.jetbrains.kotlin.psi.KtTypeAlias +import org.jetbrains.kotlin.psi.psiUtil.isTopLevelKtOrJavaMember +import org.junit.Test +import java.nio.file.Files +import java.nio.file.Paths + +class TopLevelDeclarationsEquivalenceTest : KtLspTest() { + @Test + fun topLevelLookupsMatchTheFullTreeWalksOnRealSources() { + val byPackage = parseMainSources().groupBy { it.packageFqName } + assertThat(byPackage.size).isGreaterThan(15) + + env.project.read { + for ((_, list) in byPackage) { + val files = list.asSequence() + assertThat(files.topLevelCallableNames().toSet()).isEqualTo(legacyCallableNames(files)) + assertThat(files.topLevelClassLikeNames().toSet()).isEqualTo(legacyClassLikeNames(files)) + for (id in legacyAllClassIds(files)) { + assertThat(files.classesWithId(id).toList()).containsExactlyElementsIn(legacyClasses(files, id)) + assertThat(files.typeAliasesWithId(id).toList()).containsExactlyElementsIn(legacyTypeAliases(files, id)) + } + for (name in legacyCallableNames(files)) { + assertThat(files.topLevelFunctions(name).toList()).containsExactlyElementsIn(legacyFunctions(files, name)) + assertThat(files.topLevelProperties(name).toList()).containsExactlyElementsIn(legacyProperties(files, name)) + } + } + } + } + + private fun parseMainSources(): List { + val root = + generateSequence(Paths.get("").toAbsolutePath()) { it.parent } + .first { Files.exists(it.resolve(".androidide_root")) } + val paths = + Files.walk(root.resolve("lsp/kotlin/src/main")).use { stream -> + stream.filter { it.toString().endsWith(".kt") }.toList() + } + return env.project.read { + paths.map { env.parser.createFile(it.fileName.toString(), it.toFile().readText()) } + } + } + + private fun legacyAllClassIds(files: Sequence): Set { + val classes = files.flatMap { PsiTreeUtil.collectElementsOfType(it, KtClassOrObject::class.java) }.mapNotNull { it.getClassId() } + val aliases = files.flatMap { PsiTreeUtil.collectElementsOfType(it, KtTypeAlias::class.java) }.mapNotNull { it.getClassId() } + return (classes + aliases).toSet() + } + + private fun legacyClasses( + files: Sequence, + classId: ClassId, + ): List = + files + .flatMap { PsiTreeUtil.collectElementsOfType(it, KtClassOrObject::class.java).asSequence() } + .filter { it.getClassId() == classId } + .toList() + + private fun legacyTypeAliases( + files: Sequence, + classId: ClassId, + ): List = + files + .flatMap { PsiTreeUtil.collectElementsOfType(it, KtTypeAlias::class.java).asSequence() } + .filter { it.getClassId() == classId } + .toList() + + private fun legacyFunctions( + files: Sequence, + name: Name, + ): List = + files + .flatMap { PsiTreeUtil.collectElementsOfType(it, KtNamedFunction::class.java).asSequence() } + .filter { it.isTopLevel } + .filter { it.nameAsName == name } + .toList() + + private fun legacyProperties( + files: Sequence, + name: Name, + ): List = + files + .flatMap { PsiTreeUtil.collectElementsOfType(it, KtProperty::class.java).asSequence() } + .filter { it.isTopLevel } + .filter { it.nameAsName == name } + .toList() + + private fun legacyClassLikeNames(files: Sequence): Set = + files + .flatMap { PsiTreeUtil.collectElementsOfType(it, KtClassLikeDeclaration::class.java).asSequence() } + .filter { it.isTopLevelKtOrJavaMember() } + .mapNotNull { it.nameAsName } + .toSet() + + private fun legacyCallableNames(files: Sequence): Set = + files + .flatMap { PsiTreeUtil.collectElementsOfType(it, KtCallableDeclaration::class.java).asSequence() } + .filter { it.isTopLevelKtOrJavaMember() } + .mapNotNull { it.nameAsName } + .toSet() +} diff --git a/lsp/kotlin/src/test/java/dev/mutwakil/androidide/lsp/kotlin/compiler/vfs/ListingJarFileSystemTest.kt b/lsp/kotlin/src/test/java/dev/mutwakil/androidide/lsp/kotlin/compiler/vfs/ListingJarFileSystemTest.kt new file mode 100644 index 0000000000..32e68c176d --- /dev/null +++ b/lsp/kotlin/src/test/java/dev/mutwakil/androidide/lsp/kotlin/compiler/vfs/ListingJarFileSystemTest.kt @@ -0,0 +1,373 @@ +package dev.mutwakil.androidide.lsp.kotlin.compiler.vfs + +import com.google.common.truth.Truth.assertThat +import dev.mutwakil.androidide.lsp.kotlin.fixtures.KtLspTest +import dev.mutwakil.androidide.zipfs2.listing.JarListing +import dev.mutwakil.androidide.zipfs2.listing.JarListingCache +import org.jetbrains.kotlin.com.intellij.openapi.vfs.VirtualFile +import org.jetbrains.kotlin.com.intellij.openapi.vfs.impl.jar.CoreJarFileSystem +import org.junit.Test +import java.io.ByteArrayOutputStream +import java.io.IOException +import java.nio.file.Files +import java.nio.file.Path +import java.nio.file.StandardCopyOption +import java.nio.file.attribute.FileTime +import java.util.zip.CRC32 +import java.util.zip.ZipEntry +import java.util.zip.ZipException +import java.util.zip.ZipFile +import java.util.zip.ZipOutputStream + +// Extends KtLspTest because CoreJarFileSystem reads contents through an application service. +class ListingJarFileSystemTest : KtLspTest() { + private val cache = JarListingCache(JarListing::read) + private val fileSystem = ListingJarFileSystem(cache) + + @Test + fun `the same entry is the same object while referenced`() { + val jar = writeJar("a.jar", "p/A.class" to "a", "p/q/B.class" to "b") + + val first = find(jar, "p/q/B.class") + val second = find(jar, "p/q/B.class") + val viaParent = find(jar, "p/q")!!.findChild("B.class") + val viaChildren = find(jar, "p/q")!!.children.single() + + assertThat(second).isSameInstanceAs(first) + assertThat(viaParent).isSameInstanceAs(first) + assertThat(viaChildren).isSameInstanceAs(first) + } + + @Test + fun `finding one entry creates only it and its parents`() { + val jar = writeJar("a.jar", "p/A.class" to "a", "p/q/B.class" to "b", "p/q/C.class" to "c", "r/D.class" to "d") + + val file = find(jar, "p/q/B.class") as ListingJarVirtualFile + + assertThat(file.handler.createdFileCount()).isEqualTo(4) + } + + @Test + fun `children, sizes and contents match ZipFile`() { + val jar = + writeJar( + "a.jar", + "META-INF/MANIFEST.MF" to "Manifest-Version: 1.0\n", + "p/A.class" to "a".repeat(100), + "p/q/B.class" to "bb", + "p/q/C.class" to "", + ) + + ZipFile(jar.toFile()).use { zip -> + for (entry in zip.entries()) { + val file = find(jar, entry.name)!! + assertThat(file.isDirectory).isFalse() + assertThat(file.length).isEqualTo(entry.size) + assertThat(file.contentsToByteArray()).isEqualTo(zip.getInputStream(entry).readBytes()) + } + } + assertThat(childNames(find(jar, "")!!)).containsExactly("META-INF", "p") + assertThat(childNames(find(jar, "p")!!)).containsExactly("A.class", "q") + assertThat(childNames(find(jar, "p/q")!!)).containsExactly("B.class", "C.class") + assertThat(find(jar, "p/q/B.class")!!.children).isEmpty() + } + + @Test + fun `urls and paths match CoreJarFileSystem's`() { + val implicitDirs = writeJar("implicit.jar", "p/A.class" to "a", "p/q/B.class" to "b") + val explicitDirs = writeJar("explicit.jar", "p/" to null, "p/A.class" to "a", "p/q/" to null, "p/q/B.class" to "b") + val core = CoreJarFileSystem() + + for (jar in listOf(implicitDirs, explicitDirs)) { + for (entry in listOf("", "p", "p/", "p/q", "p/A.class", "p/q/B.class", "p//q/B.class", "missing")) { + assertSameShape(find(jar, entry), core.findFileByPath("$jar!/$entry"), "$jar!/$entry") + } + } + } + + @Test + fun `a jar replaced in place invalidates old files and serves new content`() { + val jar = writeJar("a.jar", "p/A.class" to "old") + val old = find(jar, "p/A.class")!! + val oldRoot = find(jar, "")!! + + writeJar("a.jar", "p/A.class" to "new content", "p/B.class" to "b") + Files.setLastModifiedTime(jar, FileTime.fromMillis(Files.getLastModifiedTime(jar).toMillis() + 10_000)) + val replaced = find(jar, "p/A.class")!! + + assertThat(old.isValid).isFalse() + assertThat(oldRoot.isValid).isFalse() + assertThat(oldRoot.findChild("p")!!.findChild("A.class")).isSameInstanceAs(old) + assertThat(replaced).isNotSameInstanceAs(old) + assertThat(replaced.isValid).isTrue() + assertThat(replaced.contentsToByteArray().decodeToString()).isEqualTo("new content") + assertThat(find(jar, "p/B.class")).isNotNull() + } + + @Test + fun `clearing the cache invalidates every file and serves fresh ones`() { + val one = find(writeJar("one.jar", "p/A.class" to "a"), "p/A.class")!! + val two = writeJar("two.jar", "q/B.class" to "b") + val held = find(two, "q/B.class")!! + + cache.clear() + + assertThat(one.isValid).isFalse() + assertThat(held.isValid).isFalse() + assertThat(find(two, "q/B.class")!!.isValid).isTrue() + } + + @Test + fun `stored and deflated contents behind a stub prefix match ZipFile`() { + val jar = + lspTestRule.tempDir.root + .toPath() + .resolve("prefixed.jar") + val stored = setOf("p/Stored.class", "p/Empty.class") + val zip = + zipBytes( + "p/Stored.class" to "stored ".repeat(50), + "p/Deflated.class" to "deflated ".repeat(500), + "p/Empty.class" to "", + stored = stored, + ) + Files.write(jar, "#!/bin/sh stub\n".encodeToByteArray() + zip) + + ZipFile(jar.toFile()).use { zipFile -> + assertThat( + zipFile + .entries() + .toList() + .map { it.method } + .toSet(), + ).containsExactly(ZipEntry.STORED, ZipEntry.DEFLATED) + for (entry in zipFile.entries()) { + assertThat(find(jar, entry.name)!!.contentsToByteArray()).isEqualTo(zipFile.getInputStream(entry).readBytes()) + } + } + } + + @Test + fun `a held file keeps reading the old jar after it is replaced by a rename`() { + val jar = writeJar("a.jar", "p/A.class" to "old") + val held = find(jar, "p/A.class")!! + held.contentsToByteArray() + + renameOver(jar, "p/A.class" to "new and longer", "p/B.class" to "b") + + assertThat(held.contentsToByteArray().decodeToString()).isEqualTo("old") + } + + @Test + fun `corrupt deflate data fails the read with an IOException`() { + val jar = + lspTestRule.tempDir.root + .toPath() + .resolve("corrupt.jar") + val bytes = zipBytes("p/A.class" to "some deflated content") + // 0xFF opens a final block of reserved type 3, which no deflate stream may contain. + bytes[LOC_HEADER_SIZE + "p/A.class".length] = 0xFF.toByte() + Files.write(jar, bytes) + + val failure = runCatching { find(jar, "p/A.class")!!.contentsToByteArray() }.exceptionOrNull() + + assertThat(failure).isInstanceOf(IOException::class.java) + } + + @Test + fun `a compressed size past the end of the jar fails before allocating it`() { + val jar = writeCorrupt("p/A.class" to "a", cenOffset = CEN_COMPRESSED_SIZE, value = HUGE_SIZE) + + val failure = runCatching { find(jar, "p/A.class")!!.contentsToByteArray() }.exceptionOrNull() + + assertThat(failure).isInstanceOf(ZipException::class.java) + } + + @Test + fun `an uncompressed size deflate cannot reach fails before allocating it`() { + val jar = writeCorrupt("p/A.class" to "a", cenOffset = CEN_SIZE, value = HUGE_SIZE) + + val failure = runCatching { find(jar, "p/A.class")!!.contentsToByteArray() }.exceptionOrNull() + + assertThat(failure).isInstanceOf(ZipException::class.java) + } + + @Test + fun `a first read after a rename replaced the jar fails instead of using old offsets`() { + val jar = writeJar("a.jar", "p/A.class" to "old") + val held = find(jar, "p/A.class")!! + + renameOver(jar, "p/A.class" to "new and longer", "p/B.class" to "b") + + assertThat(runCatching { held.contentsToByteArray() }.exceptionOrNull()).isInstanceOf(IOException::class.java) + } + + @Test + fun `a lookup holding an older listing keeps the newer handler`() { + val jar = writeJar("a.jar", "p/A.class" to "old") + val stale = cache.snapshot(jar) + writeJar("a.jar", "p/A.class" to "new content") + Files.setLastModifiedTime(jar, FileTime.fromMillis(Files.getLastModifiedTime(jar).toMillis() + 10_000)) + val current = find(jar, "p/A.class") as ListingJarVirtualFile + + val kept = fileSystem.handlerFor(jar.toAbsolutePath().normalize().toString(), stale) + + assertThat(kept).isSameInstanceAs(current.handler) + assertThat(current.isValid).isTrue() + assertThat(find(jar, "p/A.class")).isSameInstanceAs(current) + } + + @Test + fun `a first read after a same-size rename with other names fails`() { + val jar = writeJar("a.jar", "p/A.class" to "same") + val held = find(jar, "p/A.class")!! + val size = Files.size(jar) + + renameOver(jar, "p/B.class" to "same") + + assertThat(Files.size(jar)).isEqualTo(size) + assertThat(runCatching { held.contentsToByteArray() }.exceptionOrNull()).isInstanceOf(IOException::class.java) + } + + @Test + fun `a lookup with an old snapshot after another consumer rebuilt the listing leaves no stale handler`() { + val jar = writeJar("a.jar", "p/A.class" to "old") + val key = jar.toAbsolutePath().normalize().toString() + val stale = cache.snapshot(jar) + find(jar, "p/A.class") + writeJar("a.jar", "p/A.class" to "new content") + Files.setLastModifiedTime(jar, FileTime.fromMillis(Files.getLastModifiedTime(jar).toMillis() + 10_000)) + val rebuilt = cache.snapshot(jar) + + val handler = fileSystem.handlerFor(key, stale)!! + + assertThat(handler.snapshot).isSameInstanceAs(rebuilt) + assertThat(fileSystem.handlerFor(key, rebuilt)).isSameInstanceAs(handler) + assertThat(handler.findFile("p/A.class")!!.contentsToByteArray().decodeToString()).isEqualTo("new content") + } + + @Test + fun `a deleted jar invalidates its files`() { + val jar = writeJar("a.jar", "p/A.class" to "a") + val file = find(jar, "p/A.class")!! + + Files.delete(jar) + + assertThat(find(jar, "p/A.class")).isNull() + assertThat(file.isValid).isFalse() + } + + @Test + fun `a missing jar finds nothing`() { + assertThat(fileSystem.findFileByPath("${lspTestRule.tempDir.root}/missing.jar!/p/A.class")).isNull() + } + + private fun find( + jar: Path, + entry: String, + ): VirtualFile? = fileSystem.findFileByPath("$jar!/$entry") + + private fun childNames(dir: VirtualFile): List = dir.children.map { it.name } + + private fun assertSameShape( + actual: VirtualFile?, + expected: VirtualFile?, + what: String, + ) { + if (expected == null) { + assertThat(actual).isNull() + return + } + checkNotNull(actual) { "missing $what" } + assertThat(actual.url).isEqualTo(expected.url) + assertThat(actual.path).isEqualTo(expected.path) + assertThat(actual.name).isEqualTo(expected.name) + assertThat(actual.isDirectory).isEqualTo(expected.isDirectory) + assertThat(actual.length).isEqualTo(expected.length) + assertThat(actual.timeStamp).isEqualTo(expected.timeStamp) + assertThat(actual.modificationStamp).isEqualTo(expected.modificationStamp) + assertThat(actual.isWritable).isEqualTo(expected.isWritable) + assertThat(actual.fileSystem.protocol).isEqualTo(expected.fileSystem.protocol) + assertThat(actual.fileSystem).isSameInstanceAs(fileSystem) + assertThat(actual.parent?.url).isEqualTo(expected.parent?.url) + assertThat(childNames(actual)).containsExactlyElementsIn(childNames(expected)) + if (!expected.isDirectory) { + assertThat(actual.contentsToByteArray()).isEqualTo(expected.contentsToByteArray()) + } + } + + private fun writeJar( + name: String, + vararg entries: Pair, + ): Path { + val jar = + lspTestRule.tempDir.root + .toPath() + .resolve(name) + Files.write(jar, zipBytes(*entries)) + return jar + } + + /** Writes a one-entry JAR whose central directory field at [cenOffset] is overwritten with [value]. */ + private fun writeCorrupt( + entry: Pair, + cenOffset: Int, + value: Long, + ): Path { + val bytes = zipBytes(entry) + val cen = (bytes.size - 4 downTo 0).first { u32(bytes, it) == CEN_SIGNATURE } + for (k in 0 until 4) { + bytes[cen + cenOffset + k] = (value ushr (8 * k)).toByte() + } + val jar = + lspTestRule.tempDir.root + .toPath() + .resolve("corrupt-size.jar") + Files.write(jar, bytes) + return jar + } + + private fun u32( + bytes: ByteArray, + at: Int, + ): Long = (0 until 4).fold(0L) { acc, k -> acc or ((bytes[at + k].toLong() and 0xFF) shl (8 * k)) } + + private fun renameOver( + jar: Path, + vararg entries: Pair, + ) { + val replacement = Files.write(jar.resolveSibling("replacement.tmp"), zipBytes(*entries)) + Files.move(replacement, jar, StandardCopyOption.ATOMIC_MOVE) + } + + // A null content writes a directory entry. + private fun zipBytes( + vararg entries: Pair, + stored: Set = emptySet(), + ): ByteArray { + val bytes = ByteArrayOutputStream() + ZipOutputStream(bytes).use { zip -> + entries.forEach { (name, content) -> + val data = content?.encodeToByteArray() ?: ByteArray(0) + val entry = ZipEntry(name) + if (name in stored) { + entry.method = ZipEntry.STORED + entry.size = data.size.toLong() + entry.crc = CRC32().apply { update(data) }.value + } + zip.putNextEntry(entry) + zip.write(data) + zip.closeEntry() + } + } + return bytes.toByteArray() + } +} + +private const val LOC_HEADER_SIZE = 30 +private const val CEN_SIGNATURE = 0x02014b50L +private const val CEN_COMPRESSED_SIZE = 20 +private const val CEN_SIZE = 24 + +// Below the 0xFFFFFFFF zip64 marker, and far beyond the 1 GB test heap. +private const val HUGE_SIZE = 0x7FFF_0000L diff --git a/lsp/kotlin/src/test/java/dev/mutwakil/androidide/lsp/kotlin/fixtures/GradleProjectFixtures.kt b/lsp/kotlin/src/test/java/dev/mutwakil/androidide/lsp/kotlin/fixtures/GradleProjectFixtures.kt new file mode 100644 index 0000000000..c82ac8e60c --- /dev/null +++ b/lsp/kotlin/src/test/java/dev/mutwakil/androidide/lsp/kotlin/fixtures/GradleProjectFixtures.kt @@ -0,0 +1,176 @@ +package dev.mutwakil.androidide.lsp.kotlin.fixtures + +import dev.mutwakil.androidide.project.AndroidModels +import dev.mutwakil.androidide.project.Common +import dev.mutwakil.androidide.project.GradleModels +import dev.mutwakil.androidide.project.JavaModels +import dev.mutwakil.androidide.projects.api.JavaModule +import dev.mutwakil.androidide.projects.models.ArtifactScope +import java.nio.file.Path +import kotlin.io.path.pathString + +/** + * Builds a minimal Gradle project model at [path], an Android library when [bootClassPath] or + * [projectDeps] is set, a Java project with [compileJars] on its compile classpath (in order) otherwise. + * + * [projectDeps] are Gradle paths of the projects the Android library compiles against. [unitTests], + * [androidTests] and [testFixtures], when set, give the Android library that source set with those + * jars on its own compile classpath. + */ +internal fun gradleProject( + path: String, + bootClassPath: Path? = null, + compileJars: List = emptyList(), + jvmTarget: String? = null, + projectDeps: List = emptyList(), + unitTests: TestSources? = null, + androidTests: TestSources? = null, + testFixtures: TestSources? = null, +): GradleModels.GradleProject { + val dir = "/tmp/collect-kt-modules${path.replace(':', '/')}" + return GradleModels.GradleProject + .newBuilder() + .setName(path.trimStart(':')) + .setPath(path) + .setProjectDirPath(dir) + .setBuildDirPath("$dir/build") + .setBuildScriptPath("$dir/build.gradle") + .apply { + val scoped = + listOfNotNull( + unitTests?.let { ArtifactScope.UNIT_TEST to it }, + androidTests?.let { ArtifactScope.ANDROID_TEST to it }, + testFixtures?.let { ArtifactScope.TestFixtures to it }, + ) + if (bootClassPath != null || projectDeps.isNotEmpty() || scoped.isNotEmpty()) { + val variantDeps = projectDependencies(projectDeps).toBuilder() + val sourceSet = AndroidModels.SourceSetContainer.newBuilder() + for ((scope, sources) in scoped) { + sourceSet.putSourceProviders(scope.key, sources.sourceProvider()) + variantDeps.putArtifacts(scope.key, sources.addJarsTo(variantDeps)) + } + setAndroidProject( + AndroidModels.AndroidProject + .newBuilder() + .setProjectType(AndroidModels.ProjectType.LibraryProject) + .apply { bootClassPath?.let { addBootClassPaths(it.pathString) } } + .apply { if (scoped.isNotEmpty()) setMainSourceSet(sourceSet) } + .setVariantDependencies(variantDeps), + ) + } + if (compileJars.isNotEmpty() || jvmTarget != null) { + setJavaProject( + JavaModels.JavaProject + .newBuilder() + .apply { + compileJars.forEach { jar -> + addDependency( + JavaModels.JavaDependency + .newBuilder() + .setJarFilePath(jar.pathString) + .setScope(JavaModule.SCOPE_COMPILE) + .setExternalLibrary(JavaModels.JavaExternalLibraryDependency.getDefaultInstance()), + ) + } + if (jvmTarget != null) { + setKotlinCompilerSettings(Common.KotlinCompilerSettings.newBuilder().setJvmTarget(jvmTarget)) + } + }, + ) + } + }.build() +} + +/** + * A test source set: its source [dirs], and the [jars] and [projects] only its tests compile + * against; [fixtureProjects] are projects whose test fixtures they compile against. + */ +internal data class TestSources( + val dirs: List, + val jars: List = emptyList(), + val projects: List = emptyList(), + val fixtureProjects: List = emptyList(), +) + +private fun TestSources.sourceProvider(): AndroidModels.SourceProvider = + AndroidModels.SourceProvider + .newBuilder() + .addAllJavaDirs(dirs.map { it.pathString }) + .build() + +/** Registers [TestSources.jars] as libraries of [variantDeps] and returns a graph with one root per jar. */ +private fun TestSources.addJarsTo(variantDeps: AndroidModels.VariantDependencies.Builder): AndroidModels.ArtifactDependencies { + val graph = AndroidModels.DependencyGraph.newBuilder() + for (jar in jars) { + val key = "jar:${jar.pathString}" + graph.addRoot(graph.nodeCount) + graph.addNode(AndroidModels.GraphNode.newBuilder().setKeyId(graph.keyCount)) + graph.addKey(key) + variantDeps.putLibraries( + key, + AndroidModels.Library + .newBuilder() + .setKey(key) + .setType(AndroidModels.LibraryType.ExternalJavaLibrary) + .setArtifactPath(jar.pathString) + .build(), + ) + } + for ((projectPath, fixtures) in projects.map { it to false } + fixtureProjects.map { it to true }) { + val key = if (fixtures) "project$projectPath:testFixtures" else "project$projectPath" + graph.addRoot(graph.nodeCount) + graph.addNode(AndroidModels.GraphNode.newBuilder().setKeyId(graph.keyCount)) + graph.addKey(key) + variantDeps.putLibraries( + key, + AndroidModels.Library + .newBuilder() + .setKey(key) + .setType(AndroidModels.LibraryType.Project) + .setProjectInfo( + AndroidModels.ProjectInfo + .newBuilder() + .setBuildId(":") + .setProjectPath(projectPath) + .setIsTestFixtures(fixtures), + ).build(), + ) + } + return AndroidModels.ArtifactDependencies + .newBuilder() + .setCompileGraph(graph) + .build() +} + +/** Encodes [projectPaths] as root `Project` libraries of the main artifact's compile graph, as the tooling layer does. */ +private fun projectDependencies(projectPaths: List): AndroidModels.VariantDependencies { + val graph = AndroidModels.DependencyGraph.newBuilder() + val variantDeps = AndroidModels.VariantDependencies.newBuilder().setName("debug") + for (projectPath in projectPaths) { + val key = "project$projectPath" + graph.addRoot(graph.nodeCount) + graph.addNode(AndroidModels.GraphNode.newBuilder().setKeyId(graph.keyCount)) + graph.addKey(key) + variantDeps.putLibraries( + key, + AndroidModels.Library + .newBuilder() + .setKey(key) + .setType(AndroidModels.LibraryType.Project) + .setProjectInfo( + AndroidModels.ProjectInfo + .newBuilder() + .setBuildId(":") + .setProjectPath(projectPath), + ).build(), + ) + } + return variantDeps + .putArtifacts( + ArtifactScope.Main.key, + AndroidModels.ArtifactDependencies + .newBuilder() + .setCompileGraph(graph) + .build(), + ).build() +} diff --git a/lsp/kotlin/src/test/java/dev/mutwakil/androidide/lsp/kotlin/fixtures/KtLspTest.kt b/lsp/kotlin/src/test/java/dev/mutwakil/androidide/lsp/kotlin/fixtures/KtLspTest.kt index 807c51f61e..f8e275a662 100644 --- a/lsp/kotlin/src/test/java/dev/mutwakil/androidide/lsp/kotlin/fixtures/KtLspTest.kt +++ b/lsp/kotlin/src/test/java/dev/mutwakil/androidide/lsp/kotlin/fixtures/KtLspTest.kt @@ -1,5 +1,6 @@ package dev.mutwakil.androidide.lsp.kotlin.fixtures +import dev.mutwakil.androidide.lsp.kotlin.compiler.KotlinModuleLayout import dev.mutwakil.androidide.lsp.kotlin.compiler.index.toMetadata import dev.mutwakil.androidide.lsp.kotlin.compiler.modules.AnalysisPriority import dev.mutwakil.androidide.lsp.kotlin.compiler.modules.ScheduledCancelChecker @@ -16,6 +17,7 @@ import org.jetbrains.kotlin.psi.KtFile import org.junit.Rule import org.junit.runner.RunWith import org.robolectric.RobolectricTestRunner +import java.nio.file.Path /** * Base class for plain JVM unit tests that need a real Kotlin Analysis API environment. @@ -36,9 +38,15 @@ abstract class KtLspTest { */ internal open val enableParserEventSystem: Boolean = false + /** + * The project layout to build the modules from, in place of [moduleSpecs]: write the sources under + * [baseDir], install a workspace and return its layout. Null keeps [moduleSpecs]. + */ + internal open fun layout(baseDir: Path): KotlinModuleLayout? = null + @get:Rule @PublishedApi - internal val lspTestRule = KtLspTestRule({ moduleSpecs }, { enableParserEventSystem }) + internal val lspTestRule = KtLspTestRule({ moduleSpecs }, { enableParserEventSystem }, ::layout) internal val env: KtLspTestEnvironment get() = lspTestRule.env diff --git a/lsp/kotlin/src/test/java/dev/mutwakil/androidide/lsp/kotlin/fixtures/KtLspTestEnvironment.kt b/lsp/kotlin/src/test/java/dev/mutwakil/androidide/lsp/kotlin/fixtures/KtLspTestEnvironment.kt index 4bc9b7400b..b24c2f5b32 100644 --- a/lsp/kotlin/src/test/java/dev/mutwakil/androidide/lsp/kotlin/fixtures/KtLspTestEnvironment.kt +++ b/lsp/kotlin/src/test/java/dev/mutwakil/androidide/lsp/kotlin/fixtures/KtLspTestEnvironment.kt @@ -3,13 +3,17 @@ package dev.mutwakil.androidide.lsp.kotlin.fixtures import dev.mutwakil.androidide.lsp.kotlin.compiler.AbstractCompilationEnvironment import dev.mutwakil.androidide.lsp.kotlin.compiler.CompilationKind import dev.mutwakil.androidide.lsp.kotlin.compiler.DEFAULT_LANGUAGE_VERSION +import dev.mutwakil.androidide.lsp.kotlin.compiler.KotlinModuleLayout import dev.mutwakil.androidide.lsp.kotlin.compiler.index.KtSymbolIndex +import dev.mutwakil.androidide.lsp.kotlin.compiler.index.toMetadata import dev.mutwakil.androidide.lsp.kotlin.compiler.modules.KtModule import dev.mutwakil.androidide.lsp.kotlin.compiler.modules.buildKtLibraryModule import dev.mutwakil.androidide.lsp.kotlin.compiler.read import dev.mutwakil.androidide.lsp.kotlin.compiler.registrar.AnalysisApiServiceProviders import dev.mutwakil.androidide.lsp.kotlin.compiler.registrar.LspAnalysisApiServiceRegistrar import dev.mutwakil.androidide.lsp.kotlin.compiler.services.AnalysisPermissionOptions +import dev.mutwakil.androidide.lsp.kotlin.compiler.toKtModules +import kotlinx.coroutines.runBlocking import org.appdevforall.codeonthego.indexing.InMemoryIndex import org.appdevforall.codeonthego.indexing.api.IndexQuery import org.appdevforall.codeonthego.indexing.jvm.JvmSymbol @@ -49,6 +53,9 @@ import org.jetbrains.kotlin.analysis.api.analyze as ktAnalyze * @param extraLibraryJars Additional JARs to add as library modules. * @param languageVersion Kotlin language version; defaults to [DEFAULT_LANGUAGE_VERSION]. * @param jdkRelease JDK release version; defaults to the host JVM's feature version. + * @param layout When set, the modules are built from it the way production builds them, in place of + * [moduleSpecs], and every Kotlin file under its source roots is indexed, as the background indexer + * would. Its source roots must exist already. */ @OptIn(K1Deprecation::class, KaImplementationDetail::class) internal class KtLspTestEnvironment( @@ -63,6 +70,7 @@ internal class KtLspTestEnvironment( // Tests that open a document and drive resolution/ranges through it (the live-document path) // need true to be representative; everything else keeps the historical false. enableParserEventSystem: Boolean = false, + private val layout: KotlinModuleLayout? = null, ) : AbstractCompilationEnvironment( name = "test", kind = CompilationKind.Default, @@ -99,6 +107,7 @@ internal class KtLspTestEnvironment( init { try { initialize(::buildModules, ::buildKtSymbolIndex) + layout?.let(::indexSourceRoots) } catch (failure: Throwable) { /* * A throwing constructor never hands the instance to KtLspTestRule, so its finally has @@ -111,6 +120,10 @@ internal class KtLspTestEnvironment( } } + // The fixture aliases one in-memory index as both source and library. + override val unimportedSymbolIndexes: List + get() = listOf(ktSymbolIndex.sourceIndex, ktSymbolIndex.libraryIndex).distinct() + override fun createServiceRegistrars(): List = listOf( LspAnalysisApiServiceRegistrar( @@ -134,6 +147,8 @@ internal class KtLspTestEnvironment( project: MockProject, applicationEnv: KotlinCoreApplicationEnvironment, ): List { + layout?.let { return it.toKtModules(project, applicationEnv) } + val jdkModule = buildKtLibraryModule(project, applicationEnv) { id = "jdk" @@ -208,6 +223,7 @@ internal class KtLspTestEnvironment( name = spec.name, roots = setOf(checkNotNull(rootByModule[name])), dependencies = libraryDeps + spec.dependsOn.map { checkNotNull(built[it]) }, + directFriendDependencies = spec.friends.map { checkNotNull(built[it]) { "Friend '$it' must be in dependsOn" } }, languageVersion = languageVersion, ) } @@ -292,6 +308,28 @@ internal class KtLspTestEnvironment( } } + /** The [KtFile] at [path], which must already exist on disk. */ + fun ktFile(path: Path): KtFile { + val vf = localFileSystem.refreshAndFindFileByPath(path.pathString) ?: error("VFS cannot find $path") + return project.read { PsiManager.getInstance(project).findFile(vf) as? KtFile } ?: error("Not a Kotlin file: $path") + } + + private fun indexSourceRoots(layout: KotlinModuleLayout) { + val files = + layout.modules + .flatMap { it.sourceRoots } + .flatMap { root -> + root + .toFile() + .walkTopDown() + .filter { it.isFile && it.extension == "kt" } + .toList() + } + runBlocking { + files.forEach { ktSymbolIndex.fileIndex.upsert(ktFile(it.toPath()).toMetadata(project, isIndexed = false)) } + } + } + /** * Runs [action] inside a [KaSession] for [file], acquiring the project read lock first. */ @@ -354,7 +392,7 @@ private fun findIntellijPluginRoot(): Path { } } -private fun findKotlinStdlibJar(): Path? = +internal fun findKotlinStdlibJar(): Path? = try { val location = KotlinVersion::class.java.protectionDomain diff --git a/lsp/kotlin/src/test/java/dev/mutwakil/androidide/lsp/kotlin/fixtures/KtLspTestRule.kt b/lsp/kotlin/src/test/java/dev/mutwakil/androidide/lsp/kotlin/fixtures/KtLspTestRule.kt index f50baaeec7..6425693383 100644 --- a/lsp/kotlin/src/test/java/dev/mutwakil/androidide/lsp/kotlin/fixtures/KtLspTestRule.kt +++ b/lsp/kotlin/src/test/java/dev/mutwakil/androidide/lsp/kotlin/fixtures/KtLspTestRule.kt @@ -1,9 +1,11 @@ package dev.mutwakil.androidide.lsp.kotlin.fixtures +import dev.mutwakil.androidide.lsp.kotlin.compiler.KotlinModuleLayout import org.junit.rules.TemporaryFolder import org.junit.rules.TestRule import org.junit.runner.Description import org.junit.runners.model.Statement +import java.nio.file.Path /** * @param moduleSpecs Supplied as a lambda, not a value: JUnit evaluates rules after the test class @@ -17,6 +19,7 @@ internal class KtLspTestRule( listOf(TestSourceModuleSpec("src")) }, private val enableParserEventSystem: () -> Boolean = { false }, + private val layout: (Path) -> KotlinModuleLayout? = { null }, ) : TestRule { val tempDir = TemporaryFolder() lateinit var env: KtLspTestEnvironment @@ -36,6 +39,7 @@ internal class KtLspTestRule( tempDir.root.toPath(), moduleSpecs(), enableParserEventSystem = enableParserEventSystem(), + layout = layout(tempDir.root.toPath()), ) env = environment diff --git a/lsp/kotlin/src/test/java/dev/mutwakil/androidide/lsp/kotlin/fixtures/TestKtSourceModule.kt b/lsp/kotlin/src/test/java/dev/mutwakil/androidide/lsp/kotlin/fixtures/TestKtSourceModule.kt index 9d4d4c9e50..da3c88e008 100644 --- a/lsp/kotlin/src/test/java/dev/mutwakil/androidide/lsp/kotlin/fixtures/TestKtSourceModule.kt +++ b/lsp/kotlin/src/test/java/dev/mutwakil/androidide/lsp/kotlin/fixtures/TestKtSourceModule.kt @@ -19,24 +19,25 @@ import java.nio.file.Path @OptIn(KaPlatformInterface::class, KaExperimentalApi::class) internal class TestKtSourceModule( - project: Project, - override val name: String, - roots: Set, - dependencies: List = emptyList(), - languageVersion: LanguageVersion = DEFAULT_LANGUAGE_VERSION, - jvmTarget: JvmTarget = DEFAULT_JVM_TARGET, -) : KaSourceModule, AbstractSourceModule(project, dependencies) { + project: Project, + override val name: String, + roots: Set, + dependencies: List = emptyList(), + override val directFriendDependencies: List = emptyList(), + languageVersion: LanguageVersion = DEFAULT_LANGUAGE_VERSION, + jvmTarget: JvmTarget = DEFAULT_JVM_TARGET, +) : AbstractSourceModule(project, dependencies), + KaSourceModule { + override val id: String = name + override val contentRoots: Set = roots + override val moduleDescription: String = "test:$name" - override val id: String = name - override val contentRoots: Set = roots - override val moduleDescription: String = "test:$name" + override val languageVersionSettings: LanguageVersionSettings = + LanguageVersionSettingsImpl( + languageVersion = languageVersion, + apiVersion = ApiVersion.createByLanguageVersion(languageVersion), + ) - override val languageVersionSettings: LanguageVersionSettings = - LanguageVersionSettingsImpl( - languageVersion = languageVersion, - apiVersion = ApiVersion.createByLanguageVersion(languageVersion), - ) - - override val targetPlatform: TargetPlatform = - JvmPlatforms.jvmPlatformByTargetVersion(jvmTarget) + override val targetPlatform: TargetPlatform = + JvmPlatforms.jvmPlatformByTargetVersion(jvmTarget) } diff --git a/lsp/kotlin/src/test/java/dev/mutwakil/androidide/lsp/kotlin/fixtures/TestSourceModuleSpec.kt b/lsp/kotlin/src/test/java/dev/mutwakil/androidide/lsp/kotlin/fixtures/TestSourceModuleSpec.kt index fe96817eea..3c1cd21b35 100644 --- a/lsp/kotlin/src/test/java/dev/mutwakil/androidide/lsp/kotlin/fixtures/TestSourceModuleSpec.kt +++ b/lsp/kotlin/src/test/java/dev/mutwakil/androidide/lsp/kotlin/fixtures/TestSourceModuleSpec.kt @@ -7,9 +7,12 @@ package dev.mutwakil.androidide.lsp.kotlin.fixtures * @param dirName Directory created for this module's source root, under the test's temp folder. * @param dependsOn Names of other source modules this one depends on. Empty means it sees only * the JDK, the stdlib and any extra jars. + * @param friends Names of modules whose `internal` declarations this one may use, as a test module + * uses its main module's. Each must also be in [dependsOn]. */ internal data class TestSourceModuleSpec( val name: String, val dirName: String = name, val dependsOn: List = emptyList(), + val friends: List = emptyList(), ) diff --git a/lsp/kotlin/src/test/java/dev/mutwakil/androidide/lsp/kotlin/fixtures/VariantProjectFixtures.kt b/lsp/kotlin/src/test/java/dev/mutwakil/androidide/lsp/kotlin/fixtures/VariantProjectFixtures.kt new file mode 100644 index 0000000000..2d7ae7f31e --- /dev/null +++ b/lsp/kotlin/src/test/java/dev/mutwakil/androidide/lsp/kotlin/fixtures/VariantProjectFixtures.kt @@ -0,0 +1,114 @@ +package dev.mutwakil.androidide.lsp.kotlin.fixtures + +import dev.mutwakil.androidide.lsp.kotlin.compiler.KotlinModuleLayout +import dev.mutwakil.androidide.lsp.kotlin.compiler.kotlinModuleLayout +import dev.mutwakil.androidide.project.AndroidModels +import dev.mutwakil.androidide.project.GradleModels +import dev.mutwakil.androidide.projects.ProjectManagerImpl +import dev.mutwakil.androidide.projects.models.ArtifactScope +import kotlinx.coroutines.runBlocking +import java.nio.file.Path +import kotlin.io.path.pathString + +/** + * Syncs, through [ProjectManagerImpl.setup] as a real sync does, an Android module at [dir] whose + * `src/main/kotlin` every variant in [variants] layers its own `src//kotlin` over, with + * [selected] configured and the Kotlin stdlib on the compile classpath, and returns the workspace's + * Kotlin layout. Write the sources first: the layout keeps only source dirs that exist. + */ +internal fun variantLayout( + dir: Path, + variants: List, + selected: String, +): KotlinModuleLayout { + val mainKotlin = dir.resolve("src/main/kotlin") + val variantKotlin = variants.associateWith { dir.resolve("src/$it/kotlin") } + val stdlib = checkNotNull(findKotlinStdlibJar()) { "Kotlin stdlib jar not found" } + + val module = + GradleModels.GradleProject + .newBuilder() + .setName("app") + .setPath(":app") + .setProjectDirPath(dir.pathString) + .setBuildDirPath(dir.resolve("build").pathString) + .setBuildScriptPath(dir.resolve("build.gradle").pathString) + .setAndroidProject( + AndroidModels.AndroidProject + .newBuilder() + .setProjectType(AndroidModels.ProjectType.LibraryProject) + .setMainSourceSet( + AndroidModels.SourceSetContainer + .newBuilder() + .putSourceProviders(ArtifactScope.Main.key, kotlinProvider(mainKotlin)), + ).addAllSourceSetDirPaths((listOf(mainKotlin) + variantKotlin.values).map { it.pathString }) + .addAllVariant(variantKotlin.map { (name, kotlinDir) -> variant(name, kotlinDir) }) + .setConfiguredVariantName(selected) + .setVariantDependencies(dependingOn(stdlib)), + ).build() + + val build = + GradleModels.GradleBuild + .newBuilder() + .setRootProject( + GradleModels.GradleProject + .newBuilder() + .setName("root") + .setPath(":"), + ).addSubProject(module) + .build() + val manager = ProjectManagerImpl.getInstance() + runBlocking { manager.setup(build) } + return checkNotNull(manager.workspace).kotlinModuleLayout() +} + +private fun kotlinProvider(dir: Path): AndroidModels.SourceProvider = + AndroidModels.SourceProvider + .newBuilder() + .addKotlinDirs(dir.pathString) + .build() + +private fun variant( + name: String, + kotlinDir: Path, +): AndroidModels.AndroidVariant = + AndroidModels.AndroidVariant + .newBuilder() + .setName(name) + .setMainArtifact(AndroidModels.AndroidArtifact.newBuilder().setName("main")) + .putArtifactSources( + ArtifactScope.Main.key, + AndroidModels.VariantArtifactSources + .newBuilder() + .addVariantSourceProviders(kotlinProvider(kotlinDir)) + .build(), + ).build() + +/** Main dependencies of one root library, [jar]. */ +private fun dependingOn(jar: Path): AndroidModels.VariantDependencies { + val key = "jar:${jar.pathString}" + val graph = + AndroidModels.DependencyGraph + .newBuilder() + .addKey(key) + .addNode(AndroidModels.GraphNode.newBuilder().setKeyId(0)) + .addRoot(0) + return AndroidModels.VariantDependencies + .newBuilder() + .setName("main") + .putArtifacts( + ArtifactScope.Main.key, + AndroidModels.ArtifactDependencies + .newBuilder() + .setCompileGraph(graph) + .build(), + ).putLibraries( + key, + AndroidModels.Library + .newBuilder() + .setKey(key) + .setType(AndroidModels.LibraryType.ExternalJavaLibrary) + .setArtifactPath(jar.pathString) + .build(), + ).build() +} diff --git a/lsp/kotlin/src/test/java/dev/mutwakil/androidide/lsp/kotlin/navigation/TestSourceScopesTest.kt b/lsp/kotlin/src/test/java/dev/mutwakil/androidide/lsp/kotlin/navigation/TestSourceScopesTest.kt new file mode 100644 index 0000000000..9987d2cdb0 --- /dev/null +++ b/lsp/kotlin/src/test/java/dev/mutwakil/androidide/lsp/kotlin/navigation/TestSourceScopesTest.kt @@ -0,0 +1,91 @@ +package dev.mutwakil.androidide.lsp.kotlin.navigation + +import com.google.common.truth.Truth.assertThat +import dev.mutwakil.androidide.lsp.kotlin.fixtures.KtLspTest +import dev.mutwakil.androidide.lsp.kotlin.fixtures.TestSourceModuleSpec +import dev.mutwakil.androidide.lsp.models.ReferenceParams +import dev.mutwakil.androidide.models.Position +import dev.mutwakil.androidide.progress.ICancelChecker +import kotlinx.coroutines.runBlocking +import org.jetbrains.kotlin.analysis.api.components.KaDiagnosticCheckerFilter +import org.jetbrains.kotlin.psi.KtFile +import org.junit.Test +import java.nio.file.Path + +/** + * Test sources are modules layered over main (ADFA-7115): each sees main, `internal` included, and + * find usages from main reaches them, while main and the other test scope see none of their code. + */ +class TestSourceScopesTest : KtLspTest() { + override val moduleSpecs = + listOf( + TestSourceModuleSpec("main"), + TestSourceModuleSpec("unitTest", dependsOn = listOf("main"), friends = listOf("main")), + TestSourceModuleSpec("androidTest", dependsOn = listOf("main"), friends = listOf("main")), + ) + + @Test + fun `find usages of a main declaration reaches both test scopes`() { + val main = "package p\n\nfun shared() {}\n" + val mainPath = path(createSourceFile("main", "p/Shared.kt", main)) + val unit = path(createSourceFile("unitTest", "p/UnitUse.kt", "package p\n\nfun u() { shared() }\n")) + val device = path(createSourceFile("androidTest", "p/DeviceUse.kt", "package p\n\nfun d() { shared() }\n")) + + val usages = usagesAt(mainPath, main.indexOf("shared")) + + assertThat(usages.map { it.first }).containsExactly(unit, device) + } + + @Test + fun `find usages of an internal main declaration reaches its test modules`() { + val main = "package p\n\ninternal fun helper() {}\n" + val mainPath = path(createSourceFile("main", "p/Helper.kt", main)) + val unit = path(createSourceFile("unitTest", "p/UnitHelperUse.kt", "package p\n\nfun u() { helper() }\n")) + + val usages = usagesAt(mainPath, main.indexOf("helper")) + + assertThat(usages.map { it.first }).containsExactly(unit) + } + + @Test + fun `a test file may use an internal main declaration`() { + createSourceFile("main", "p/Internal.kt", "package p\n\ninternal fun helper(): Int = 1\n") + val test = createSourceFile("unitTest", "p/UsesInternal.kt", "package p\n\nfun t(): Int = helper()\n") + + assertThat(diagnostics(test)).isEmpty() + } + + @Test + fun `a unit test cannot see android test code`() { + createSourceFile("androidTest", "p/DeviceOnly.kt", "package p\n\nclass DeviceOnly\n") + val unit = createSourceFile("unitTest", "p/UsesDevice.kt", "package p\n\nval d = DeviceOnly()\n") + + assertThat(diagnostics(unit)).contains("UNRESOLVED_REFERENCE") + } + + @Test + fun `main cannot see test code`() { + createSourceFile("unitTest", "p/UnitOnly.kt", "package p\n\nclass UnitOnly\n") + val main = createSourceFile("main", "p/UsesUnit.kt", "package p\n\nval u = UnitOnly()\n") + + assertThat(diagnostics(main)).contains("UNRESOLVED_REFERENCE") + } + + private fun path(file: KtFile): Path = Path.of(file.virtualFile.path) + + private fun diagnostics(file: KtFile): List = + analyzeMaybeDanglingForTest(file) { + file.collectDiagnostics(KaDiagnosticCheckerFilter.EXTENDED_AND_COMMON_CHECKERS).map { it.factoryName } + } + + /** Usages for a caret at [offset] in [file], as (path, startOffset) pairs. */ + private fun usagesAt( + file: Path, + offset: Int, + ): List> = + runBlocking { + context(env) { + findUsagesAt(ReferenceParams(file, Position(0, 0, offset), true, ICancelChecker.NOOP)) + }.locations.map { it.file to it.range.start.index } + } +} diff --git a/lsp/kotlin/src/test/java/dev/mutwakil/androidide/lsp/kotlin/utils/SymbolVisibilityCheckerTest.kt b/lsp/kotlin/src/test/java/dev/mutwakil/androidide/lsp/kotlin/utils/SymbolVisibilityCheckerTest.kt index 78b9fc65f9..fb24949ae5 100644 --- a/lsp/kotlin/src/test/java/dev/mutwakil/androidide/lsp/kotlin/utils/SymbolVisibilityCheckerTest.kt +++ b/lsp/kotlin/src/test/java/dev/mutwakil/androidide/lsp/kotlin/utils/SymbolVisibilityCheckerTest.kt @@ -2,6 +2,7 @@ package dev.mutwakil.androidide.lsp.kotlin.utils import com.google.common.truth.Truth.assertThat import dev.mutwakil.androidide.lsp.kotlin.compiler.services.ProjectStructureProvider +import io.mockk.every import io.mockk.mockk import org.appdevforall.codeonthego.indexing.jvm.JvmClassInfo import org.appdevforall.codeonthego.indexing.jvm.JvmSourceLanguage @@ -21,170 +22,185 @@ import org.junit.runners.JUnit4 */ @RunWith(JUnit4::class) class SymbolVisibilityCheckerTest { - - // Use relaxed mocks so that no stubs are required for unused methods - private val structureProvider = mockk(relaxed = true) - private val checker = SymbolVisibilityChecker(structureProvider) - - // Two distinct modules - private val moduleA: KaModule = mockk(relaxed = true) - private val moduleB: KaModule = mockk(relaxed = true) - - private fun symbol( - visibility: JvmVisibility, - pkg: String = "com.example", - sourceId: String = "jar-a", - ) = JvmSymbol( - key = "com/example/Foo", - sourceId = sourceId, - name = "com/example/Foo", - shortName = "Foo", - packageName = pkg, - kind = JvmSymbolKind.CLASS, - language = JvmSourceLanguage.KOTLIN, - visibility = visibility, - data = JvmClassInfo(), - ) - - @Test - fun `PUBLIC symbol is always visible regardless of module`() { - assertThat( - checker.isDeclarationVisible( - symbol(JvmVisibility.PUBLIC), - useSiteModule = moduleA, - declaringModule = moduleB, - useSitePackage = "other.pkg", - ) - ).isTrue() - } - - @Test - fun `PUBLIC symbol is visible even with null useSitePackage`() { - assertThat( - checker.isDeclarationVisible( - symbol(JvmVisibility.PUBLIC), - useSiteModule = moduleA, - declaringModule = moduleB, - useSitePackage = null, - ) - ).isTrue() - } - - @Test - fun `PRIVATE symbol is never visible`() { - assertThat( - checker.isDeclarationVisible( - symbol(JvmVisibility.PRIVATE), - useSiteModule = moduleA, - declaringModule = moduleB, - ) - ).isFalse() - } - - @Test - fun `PRIVATE symbol is not visible even from same module`() { - assertThat( - checker.isDeclarationVisible( - symbol(JvmVisibility.PRIVATE), - useSiteModule = moduleA, - declaringModule = moduleA, // same module - ) - ).isFalse() - } - - @Test - fun `INTERNAL symbol is visible from same module`() { - assertThat( - checker.isDeclarationVisible( - symbol(JvmVisibility.INTERNAL), - useSiteModule = moduleA, - declaringModule = moduleA, - ) - ).isTrue() - } - - @Test - fun `INTERNAL symbol is not visible from different module`() { - assertThat( - checker.isDeclarationVisible( - symbol(JvmVisibility.INTERNAL), - useSiteModule = moduleA, - declaringModule = moduleB, - ) - ).isFalse() - } - - @Test - fun `PACKAGE_PRIVATE symbol is visible within same package`() { - assertThat( - checker.isDeclarationVisible( - symbol(JvmVisibility.PACKAGE_PRIVATE, pkg = "com.example"), - useSiteModule = moduleA, - declaringModule = moduleB, - useSitePackage = "com.example", - ) - ).isTrue() - } - - @Test - fun `PACKAGE_PRIVATE symbol is not visible from different package`() { - assertThat( - checker.isDeclarationVisible( - symbol(JvmVisibility.PACKAGE_PRIVATE, pkg = "com.example"), - useSiteModule = moduleA, - declaringModule = moduleB, - useSitePackage = "org.other", - ) - ).isFalse() - } - - @Test - fun `PACKAGE_PRIVATE symbol is not visible when useSitePackage is null`() { - assertThat( - checker.isDeclarationVisible( - symbol(JvmVisibility.PACKAGE_PRIVATE, pkg = "com.example"), - useSiteModule = moduleA, - declaringModule = moduleB, - useSitePackage = null, - ) - ).isFalse() - } - - @Test - fun `PROTECTED symbol is visible within same package`() { - assertThat( - checker.isDeclarationVisible( - symbol(JvmVisibility.PROTECTED, pkg = "com.example"), - useSiteModule = moduleA, - declaringModule = moduleB, - useSitePackage = "com.example", - ) - ).isTrue() - } - - @Test - fun `PROTECTED symbol is visible as assumed descendant across packages`() { - // isDescendant is hardcoded to true in the current implementation - assertThat( - checker.isDeclarationVisible( - symbol(JvmVisibility.PROTECTED, pkg = "com.example"), - useSiteModule = moduleA, - declaringModule = moduleB, - useSitePackage = "different.pkg", - ) - ).isTrue() - } - - @Test - fun `PROTECTED symbol is visible with null useSitePackage due to descendant assumption`() { - // isSamePackage=false but isDescendant=true → visible - assertThat( - checker.isDeclarationVisible( - symbol(JvmVisibility.PROTECTED, pkg = "com.example"), - useSiteModule = moduleA, - declaringModule = moduleB, - useSitePackage = null, - ) - ).isTrue() - } + // Use relaxed mocks so that no stubs are required for unused methods + private val structureProvider = mockk(relaxed = true) + private val checker = SymbolVisibilityChecker(structureProvider) + + // Two distinct modules + private val moduleA: KaModule = mockk(relaxed = true) + private val moduleB: KaModule = mockk(relaxed = true) + + private fun symbol( + visibility: JvmVisibility, + pkg: String = "com.example", + sourceId: String = "jar-a", + ) = JvmSymbol( + key = "com/example/Foo", + sourceId = sourceId, + name = "com/example/Foo", + shortName = "Foo", + packageName = pkg, + kind = JvmSymbolKind.CLASS, + language = JvmSourceLanguage.KOTLIN, + visibility = visibility, + data = JvmClassInfo(), + ) + + @Test + fun `PUBLIC symbol is always visible regardless of module`() { + assertThat( + checker.isDeclarationVisible( + symbol(JvmVisibility.PUBLIC), + useSiteModule = moduleA, + declaringModule = moduleB, + useSitePackage = "other.pkg", + ), + ).isTrue() + } + + @Test + fun `PUBLIC symbol is visible even with null useSitePackage`() { + assertThat( + checker.isDeclarationVisible( + symbol(JvmVisibility.PUBLIC), + useSiteModule = moduleA, + declaringModule = moduleB, + useSitePackage = null, + ), + ).isTrue() + } + + @Test + fun `PRIVATE symbol is never visible`() { + assertThat( + checker.isDeclarationVisible( + symbol(JvmVisibility.PRIVATE), + useSiteModule = moduleA, + declaringModule = moduleB, + ), + ).isFalse() + } + + @Test + fun `PRIVATE symbol is not visible even from same module`() { + assertThat( + checker.isDeclarationVisible( + symbol(JvmVisibility.PRIVATE), + useSiteModule = moduleA, + declaringModule = moduleA, // same module + ), + ).isFalse() + } + + @Test + fun `INTERNAL symbol is visible from same module`() { + assertThat( + checker.isDeclarationVisible( + symbol(JvmVisibility.INTERNAL), + useSiteModule = moduleA, + declaringModule = moduleA, + ), + ).isTrue() + } + + @Test + fun `INTERNAL symbol is not visible from different module`() { + assertThat( + checker.isDeclarationVisible( + symbol(JvmVisibility.INTERNAL), + useSiteModule = moduleA, + declaringModule = moduleB, + ), + ).isFalse() + } + + @Test + fun `INTERNAL symbol is visible from a friend module`() { + // A test module is its main module's friend (ADFA-7115). + val testModule: KaModule = + mockk(relaxed = true) { + every { directFriendDependencies } returns listOf(moduleA) + } + assertThat( + checker.isDeclarationVisible( + symbol(JvmVisibility.INTERNAL), + useSiteModule = testModule, + declaringModule = moduleA, + ), + ).isTrue() + } + + @Test + fun `PACKAGE_PRIVATE symbol is visible within same package`() { + assertThat( + checker.isDeclarationVisible( + symbol(JvmVisibility.PACKAGE_PRIVATE, pkg = "com.example"), + useSiteModule = moduleA, + declaringModule = moduleB, + useSitePackage = "com.example", + ), + ).isTrue() + } + + @Test + fun `PACKAGE_PRIVATE symbol is not visible from different package`() { + assertThat( + checker.isDeclarationVisible( + symbol(JvmVisibility.PACKAGE_PRIVATE, pkg = "com.example"), + useSiteModule = moduleA, + declaringModule = moduleB, + useSitePackage = "org.other", + ), + ).isFalse() + } + + @Test + fun `PACKAGE_PRIVATE symbol is not visible when useSitePackage is null`() { + assertThat( + checker.isDeclarationVisible( + symbol(JvmVisibility.PACKAGE_PRIVATE, pkg = "com.example"), + useSiteModule = moduleA, + declaringModule = moduleB, + useSitePackage = null, + ), + ).isFalse() + } + + @Test + fun `PROTECTED symbol is visible within same package`() { + assertThat( + checker.isDeclarationVisible( + symbol(JvmVisibility.PROTECTED, pkg = "com.example"), + useSiteModule = moduleA, + declaringModule = moduleB, + useSitePackage = "com.example", + ), + ).isTrue() + } + + @Test + fun `PROTECTED symbol is visible as assumed descendant across packages`() { + // isDescendant is hardcoded to true in the current implementation + assertThat( + checker.isDeclarationVisible( + symbol(JvmVisibility.PROTECTED, pkg = "com.example"), + useSiteModule = moduleA, + declaringModule = moduleB, + useSitePackage = "different.pkg", + ), + ).isTrue() + } + + @Test + fun `PROTECTED symbol is visible with null useSitePackage due to descendant assumption`() { + // isSamePackage=false but isDescendant=true → visible + assertThat( + checker.isDeclarationVisible( + symbol(JvmVisibility.PROTECTED, pkg = "com.example"), + useSiteModule = moduleA, + declaringModule = moduleB, + useSitePackage = null, + ), + ).isTrue() + } } diff --git a/subprojects/kotlin-analysis-api/build.gradle.kts b/subprojects/kotlin-analysis-api/build.gradle.kts index 29a4487af8..9e06e9356e 100644 --- a/subprojects/kotlin-analysis-api/build.gradle.kts +++ b/subprojects/kotlin-analysis-api/build.gradle.kts @@ -24,7 +24,7 @@ kotlin { val ktAndroidRepo = "https://github.com/appdevforall/kotlin-android" val ktAndroidVersion = "2.3.255" -val ktAndroidTag = "v${ktAndroidVersion}-dc58d97" +val ktAndroidTag = "v$ktAndroidVersion-b006e8c" val ktAndroidJarName = "analysis-api-standalone-embeddable-for-ide-${ktAndroidVersion}-SNAPSHOT.jar" externalAssets { @@ -33,7 +33,7 @@ externalAssets { source = AssetSource.External( url = uri("$ktAndroidRepo/releases/download/$ktAndroidTag/$ktAndroidJarName"), - sha256Checksum = "42e59dfc31d1fbd67b48898e10220bde00190c00694c5848b6f6d890d2e4b332", + sha256Checksum = "0793c08f666157aa091055a498f9c231a42ced31ad5a019c9875cf814e719bbb", ) } } \ No newline at end of file diff --git a/subprojects/project-models/src/main/java/dev/mutwakil/androidide/projects/models/ArtifactScope.kt b/subprojects/project-models/src/main/java/dev/mutwakil/androidide/projects/models/ArtifactScope.kt new file mode 100644 index 0000000000..87db44c962 --- /dev/null +++ b/subprojects/project-models/src/main/java/dev/mutwakil/androidide/projects/models/ArtifactScope.kt @@ -0,0 +1,119 @@ +package dev.mutwakil.androidide.projects.models + +/** + * A component of a module's build that compiles its own sources against its own dependencies: main + * code, test fixtures, or one kind of host (JVM) or device test. + * + * Each scope has exactly one value, so it can key maps and caches. [key] is how the scope is stored + * in the project model, by the tooling server that writes it and the IDE that reads it; [fromKey] + * reads it back. Host and device test keys carry a prefix so one AGP test type name can never name + * two scopes. + */ +sealed class ArtifactScope { + /** The key this scope is stored under in the project model. */ + abstract val key: String + + /** The suffix of this scope's Kotlin analysis module path; empty for [Main]. */ + abstract val moduleSuffix: String + + /** + * Whether this scope's sources may reference [other]'s. Main sees only itself, test fixtures see + * main, and a test sees main and test fixtures; test scopes never see each other. + */ + fun sees(other: ArtifactScope): Boolean = + when (this) { + Main -> other == Main + TestFixtures -> other == Main || other == TestFixtures + is HostTest, is DeviceTest -> other == Main || other == TestFixtures || other == this + } + + /** Main sources: `src/main` and the selected variant's layers over it. */ + data object Main : ArtifactScope() { + override val key = "main" + override val moduleSuffix = "" + } + + /** Test fixtures: `src/testFixtures`, visible to the module's tests. */ + data object TestFixtures : ArtifactScope() { + override val key = "testFixtures" + override val moduleSuffix = "testFixtures" + } + + /** Tests that run on the host JVM, named by the key AGP's model gives them (e.g. `_unit_test_`). */ + data class HostTest( + val type: String, + ) : ArtifactScope() { + override val key = "$HOST_PREFIX$type" + override val moduleSuffix = camelCase(type) + } + + /** Tests that run on a device, named by the key AGP's model gives them (e.g. `_android_test_`). */ + data class DeviceTest( + val type: String, + ) : ArtifactScope() { + override val key = "$DEVICE_PREFIX$type" + override val moduleSuffix = camelCase(type) + } + + companion object { + private const val HOST_PREFIX = "host:" + private const val DEVICE_PREFIX = "device:" + + // The type names are AGP's ComponentTypeImpl artifact names, the keys of its model's test maps. + + /** Unit tests, `src/test`. */ + @JvmField + val UNIT_TEST = HostTest("_unit_test_") + + /** Screenshot tests, `src/screenshotTest`. */ + @JvmField + val SCREENSHOT_TEST = HostTest("_screenshot_test_") + + /** Instrumented tests, `src/androidTest`. */ + @JvmField + val ANDROID_TEST = DeviceTest("_android_test_") + + /** + * Main, test fixtures, unit tests, android tests, then other host and device tests by key: the + * order a file shared by several scopes is attributed in. + */ + @JvmField + val ORDER: Comparator = + compareBy { scope -> + when (scope) { + Main -> 0 + TestFixtures -> 1 + UNIT_TEST -> 2 + ANDROID_TEST -> 3 + is HostTest -> 4 + is DeviceTest -> 5 + } + }.thenBy { it.key } + + /** `_unit_test_` -> `unitTest`, so Kotlin module paths stay readable. */ + private fun camelCase(type: String): String = + type + .split('_') + .filter { it.isNotEmpty() } + .mapIndexed { index, part -> + if (index == + 0 + ) { + part.replaceFirstChar(Char::lowercaseChar) + } else { + part.replaceFirstChar(Char::uppercaseChar) + } + }.joinToString("") + + /** The scope stored under [key], or null when [key] names no scope. */ + @JvmStatic + fun fromKey(key: String): ArtifactScope? = + when { + key == Main.key -> Main + key == TestFixtures.key -> TestFixtures + key.startsWith(HOST_PREFIX) -> HostTest(key.removePrefix(HOST_PREFIX)) + key.startsWith(DEVICE_PREFIX) -> DeviceTest(key.removePrefix(DEVICE_PREFIX)) + else -> null + } + } +} \ No newline at end of file diff --git a/subprojects/project-models/src/main/proto/android.proto b/subprojects/project-models/src/main/proto/android.proto index f791872c28..6834d4aa07 100644 --- a/subprojects/project-models/src/main/proto/android.proto +++ b/subprojects/project-models/src/main/proto/android.proto @@ -152,6 +152,10 @@ message ProjectInfo { // The project path. string projectPath = 2; + + // Whether the dependency is on the project's test fixtures (testFixtures(project(":lib"))) + // rather than on the project itself. + bool isTestFixtures = 3; } // An Android library. @@ -184,14 +188,15 @@ message VariantDependencies { // The name of the variant. It is made up of the build type and flavors (if applicable) string name = 1; - // The dependencies for the variant's main artifact. - ArtifactDependencies mainArtifact = 2; - // The list of external libraries used by all the variants in the module. // // The key for the map entries is the keys found via [com.android.builder.model.v2.ide.GraphItem.key] // and [Library.key] map libraries = 3; + + // The dependencies of each of the variant's components (main, test fixtures, each host and + // device test type), keyed by ArtifactScope.key. A component the variant lacks has no entry. + map artifacts = 2; } // A custom source directory. @@ -220,8 +225,9 @@ message SourceProvider { // Android source set container. message SourceSetContainer { - // The default source provider. - SourceProvider sourceProvider = 1; + // The source provider of each component (src/main, src/test, src/androidTest, ...), keyed by + // ArtifactScope.key. A component the module lacks has no entry. + map sourceProviders = 1; } // View binding options for Android projects. @@ -275,6 +281,17 @@ message AndroidArtifact { int32 targetSdkVersionOverride = 13; } +// The sources one component of a variant adds over that component's default source set. +message VariantArtifactSources { + + // The source providers AGP layers over the component's default source set for this variant: its + // build type, each product flavor, the multi-flavor provider and the variant's own provider. + repeated SourceProvider variantSourceProviders = 1; + + // The component's generated source folders (kapt, KSP, BuildConfig and the like). + repeated string generatedSourceFolderPaths = 2; +} + // An Android project variant. message AndroidVariant { @@ -283,6 +300,9 @@ message AndroidVariant { // The 'main' artifact of the variant. AndroidArtifact mainArtifact = 2; + + // The sources each of the variant's components adds, keyed by ArtifactScope.key. + map artifactSources = 3; } // The Android project model. @@ -321,4 +341,8 @@ message AndroidProject { // The compiler settings for Kotlin sources. optional KotlinCompilerSettings kotlinCompilerSettings = 11; + // The Java and Kotlin dirs of every source set AGP knows for this module: every component of the + // default config, every build type and flavor, and every variant's own and multi-flavor layers. + // A file in one of these that the selected variant does not compile gets no analysis. + repeated string sourceSetDirPaths = 12; } \ No newline at end of file diff --git a/subprojects/projects/src/main/java/dev/mutwakil/androidide/projects/ProjectManagerImpl.kt b/subprojects/projects/src/main/java/dev/mutwakil/androidide/projects/ProjectManagerImpl.kt index 9828ecd2a9..5638817b66 100644 --- a/subprojects/projects/src/main/java/dev/mutwakil/androidide/projects/ProjectManagerImpl.kt +++ b/subprojects/projects/src/main/java/dev/mutwakil/androidide/projects/ProjectManagerImpl.kt @@ -38,6 +38,7 @@ import dev.mutwakil.androidide.projects.api.JavaModule import dev.mutwakil.androidide.projects.api.ModuleProject import dev.mutwakil.androidide.projects.api.Workspace import dev.mutwakil.androidide.projects.builder.BuildService +import dev.mutwakil.androidide.projects.models.ArtifactScope import dev.mutwakil.androidide.projects.models.resDirs import dev.mutwakil.androidide.tasks.executeAsync import dev.mutwakil.androidide.tooling.api.IAndroidProject @@ -94,6 +95,9 @@ class ProjectManagerImpl : synchronized(indexingServiceManagerLock) { _indexingServiceManager ?: IndexingServiceManager().also { _indexingServiceManager = it } } + /** The indexing service manager of the current project session, or null if none exists; never creates one. */ + val currentIndexingServiceManager: IndexingServiceManager? + get() = synchronized(indexingServiceManagerLock) { _indexingServiceManager } override var gradleBuild: GradleModels.GradleBuild? = null override var workspace: Workspace? = null @@ -245,12 +249,15 @@ class ProjectManagerImpl : this.workspace = null - // Closed outside the lock: close() blocks until every service has shut down, and a worker - // thread reading the manager meanwhile must not wait on that. - val indexingServiceManager = - synchronized(indexingServiceManagerLock) { - _indexingServiceManager.also { _indexingServiceManager = null } - } + /* + * Closed inside the lock, so the getter cannot create the next manager before this close is + * recorded as pending, which the next manager waits for. Safe to hold: close() only ends the + * session lifetime and launches the actual close in the background. + */ + synchronized(indexingServiceManagerLock) { + _indexingServiceManager?.close() + _indexingServiceManager = null + } (this.androidBuildVariants as? MutableMap?)?.clear() } @@ -385,7 +392,7 @@ class ProjectManagerImpl : } val isResource = - module.mainSourceSet?.sourceProvider?.resDirs?.any { + module.defaultSources(ArtifactScope.Main)?.resDirs?.any{ this.pathString.contains(it.path) } ?: false @@ -401,11 +408,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) + } } } } @@ -419,16 +426,18 @@ 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) @@ -438,22 +447,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/dev/mutwakil/androidide/projects/api/AndroidModule.kt b/subprojects/projects/src/main/java/dev/mutwakil/androidide/projects/api/AndroidModule.kt index 72c98b5a75..eddb50d429 100644 --- a/subprojects/projects/src/main/java/dev/mutwakil/androidide/projects/api/AndroidModule.kt +++ b/subprojects/projects/src/main/java/dev/mutwakil/androidide/projects/api/AndroidModule.kt @@ -25,13 +25,13 @@ import dev.mutwakil.androidide.builder.model.UNKNOWN_PACKAGE import dev.mutwakil.androidide.project.AndroidModels import dev.mutwakil.androidide.project.GradleModels import dev.mutwakil.androidide.projects.IProjectManager +import dev.mutwakil.androidide.projects.models.ArtifactScope import dev.mutwakil.androidide.projects.models.artifact import dev.mutwakil.androidide.projects.models.bootClassPaths import dev.mutwakil.androidide.projects.models.buildDir import dev.mutwakil.androidide.projects.models.classJars import dev.mutwakil.androidide.projects.models.classesJar import dev.mutwakil.androidide.projects.models.compileJarFiles -import dev.mutwakil.androidide.projects.models.generatedSourceFolders import dev.mutwakil.androidide.projects.models.javaDirs import dev.mutwakil.androidide.projects.models.kotlinDirs import dev.mutwakil.androidide.projects.models.resDirs @@ -85,6 +85,16 @@ open class AndroidModule( fun getVariant(name: String): AndroidModels.AndroidVariant? = variantList.firstOrNull { it.name == name } + /** The default source provider of [scope] (`src/main`, `src/test`, ...), if the module has one. */ + internal fun defaultSources(scope: ArtifactScope): AndroidModels.SourceProvider? = mainSourceSet?.sourceProvidersMap?.get(scope.key) + + /** What the selected variant's [scope] component adds over its default source set. */ + private fun variantSources(scope: ArtifactScope): AndroidModels.VariantArtifactSources? = + getSelectedVariant()?.artifactSourcesMap?.get(scope.key) + + /** The dependencies of the selected variant's [scope] component, if the variant has it. */ + private fun dependenciesOf(scope: ArtifactScope): AndroidModels.ArtifactDependencies? = variantDependencies.artifactsMap[scope.key] + fun getResourceDirectories(): Set { if (mainSourceSet == null) { log.error("No main source set found in application module: {}", name) @@ -92,7 +102,13 @@ open class AndroidModule( } val dirs = mutableSetOf() - dirs.addAll(mainSourceSet?.sourceProvider?.resDirs ?: emptyList()) + dirs.addAll(defaultSources(ArtifactScope.Main)?.resDirs ?: emptyList()) + + // src//res, src//res and the variant's own res dir are resources of the + // selected variant as much as src/main/res is; a save there must regenerate R too. + variantSources(ArtifactScope.Main)?.variantSourceProvidersList?.forEach { provider -> + dirs.addAll(provider.resDirs) + } val dependencies = getCompileModuleProjects().filterIsInstance() @@ -103,28 +119,36 @@ open class AndroidModule( return dirs } - override fun getSourceDirectories(): Set { + // The components the selected variant has: one AGP does not report for it is no scope, even if + // the module has its source set (src/androidTest while a non-tested build type is selected). + override fun getKnownSourceSetDirectories(): Set = sourceSetDirPathsList.mapTo(LinkedHashSet(), ::File) + + override fun getArtifactScopes(): List = + (listOf(ArtifactScope.Main) + variantDependencies.artifactsMap.keys.mapNotNull(ArtifactScope::fromKey)) + .distinct() + .sortedWith(ArtifactScope.ORDER) + + override fun getSourceDirectories(scope: ArtifactScope): Set { if (mainSourceSet == null) { log.warn( "No main source set is available for project {}. Cannot get source directories.", name, ) - return mutableSetOf() + return emptySet() } + if (scope != ArtifactScope.Main && dependenciesOf(scope) == null) { + return emptySet() + } + val provider = defaultSources(scope) ?: return emptySet() + val variant = variantSources(scope) - // src/main/java - val sources = mainSourceSet.sourceProvider.javaDirs.toMutableSet() - - // src/main/kotlin - sources.addAll(mainSourceSet.sourceProvider.kotlinDirs) + // src/, src/, src/ and their test counterparts are compiled + // with the default source set whenever this variant is selected. + val layers = variant?.variantSourceProvidersList.orEmpty().flatMap { it.javaDirs + it.kotlinDirs } - // build/generated/** - // AIDL, ViewHolder, Renderscript, BuildConfig i.e every generated source sources - val selectedVariant = getSelectedVariant() - if (selectedVariant != null) { - sources.addAll(selectedVariant.mainArtifact.generatedSourceFolders) - } - return sources + // build/generated/**: AIDL, BuildConfig, kapt, KSP and every other generated source + val generated = variant?.generatedSourceFolderPathsList.orEmpty().map(::File) + return (provider.javaDirs + provider.kotlinDirs + layers + generated).toSet() } override fun getCompileSourceDirectories(): Set { @@ -134,6 +158,72 @@ open class AndroidModule( return dirs } + override fun getTestFixturesModuleProjects(scope: ArtifactScope): List { + if (scope == ArtifactScope.Main) { + return emptyList() + } + return directProjectDependencies(scope) + .filter { (library, _) -> library.projectInfo.isTestFixtures } + .map { (_, module) -> module } + .distinctBy { it.path } + } + + override fun getCompileModuleProjects(scope: ArtifactScope): List { + if (scope == ArtifactScope.Main) { + return getCompileModuleProjects() + } + // Seeded with this module so a test fixture that depends back on it (`:testutils` -> + // `:app`) is not re-expanded. Not on the recursion path: that back-edge is legal, not a cycle. + val visited = hashSetOf(path) + val recursionPath = ArrayDeque() + val result = mutableListOf() + for ((_, module) in directProjectDependencies(scope)) { + result.add(module) + result.addAll(module.getCompileModuleProjects(visited, recursionPath)) + } + return result.filter { it.path != path }.distinctBy { it.path } + } + + /** The project libraries at the root of [scope]'s compile graph, with their modules, excluding this one. */ + private fun directProjectDependencies(scope: ArtifactScope): List> { + val graph = dependenciesOf(scope)?.compileGraph ?: return emptyList() + val root = IProjectManager.getInstance().workspace ?: return emptyList() + return graph.rootList + .mapNotNull { nodeId -> graph.nodeList.getOrNull(nodeId)?.let { graph.keyList.getOrNull(it.keyId) } } + .mapNotNull { key -> variantDependencies.librariesMap[key] } + .filter { it.type == AndroidModels.LibraryType.Project } + .mapNotNull { library -> + (root.findByPath(library.projectInfo.projectPath) as? ModuleProject) + ?.takeIf { it.path != path } + ?.let { library to it } + } + } + + override fun getCompileClasspaths( + scope: ArtifactScope, + excludeSourceGeneratedClassPath: Boolean, + ): Set { + if (scope == ArtifactScope.Main) { + return getCompileClasspaths(excludeSourceGeneratedClassPath) + } + val artifact = dependenciesOf(scope) ?: return emptySet() + val project = IProjectManager.getInstance().workspace ?: return emptySet() + + val result = getCompileClasspaths(excludeSourceGeneratedClassPath).toMutableSet() + val graph = artifact.compileGraph + collectLibraries( + root = project, + graph = graph, + nodeIds = graph.rootList, + result = result, + excludeSourceGeneratedClassPath = excludeSourceGeneratedClassPath, + visited = HashSet(), + // A test graph that reaches back to this module must not re-expand it. + moduleVisited = hashSetOf(path), + ) + return result + } + override fun getModuleClasspaths(): Set = mutableSetOf().apply { add(getGeneratedJar()) @@ -166,7 +256,7 @@ open class AndroidModule( } else { result.addAll(getModuleClasspaths()) } - val graph = variantDependencies.mainArtifact.compileGraph + val graph = dependenciesOf(ArtifactScope.Main)?.compileGraph ?: AndroidModels.DependencyGraph.getDefaultInstance() collectLibraries( root = project, graph = graph, @@ -389,7 +479,7 @@ open class AndroidModule( try { val result = mutableListOf() - val graph = variantDependencies.mainArtifact.compileGraph + val graph = dependenciesOf(ArtifactScope.Main)?.compileGraph ?: AndroidModels.DependencyGraph.getDefaultInstance() val libraryMap = variantDependencies.librariesMap for (nodeId in graph.rootList) { val node = graph.nodeList.getOrNull(nodeId) @@ -493,7 +583,7 @@ open class AndroidModule( fun getResourceTable(): ResourceTable? { val namespace = this.namespace ?: return null - val resDirs = mainSourceSet?.sourceProvider?.resDirs ?: return null + val resDirs = defaultSources(ArtifactScope.Main)?.resDirs ?: return null return ResourceTableRegistry.getInstance().forPackage(namespace, *resDirs.toTypedArray()) } @@ -505,7 +595,7 @@ open class AndroidModule( CompletableFuture.runAsync { val tableRegistry = ResourceTableRegistry.getInstance() - val resDirs = mainSourceSet?.sourceProvider?.resDirs ?: return@runAsync + val resDirs = defaultSources(ArtifactScope.Main)?.resDirs ?: return@runAsync tableRegistry.removeTable(this.namespace) tableRegistry.forPackage(this.namespace, *resDirs.toTypedArray()) } diff --git a/subprojects/projects/src/main/java/dev/mutwakil/androidide/projects/api/JavaModule.kt b/subprojects/projects/src/main/java/dev/mutwakil/androidide/projects/api/JavaModule.kt index 539131af05..27115328dd 100644 --- a/subprojects/projects/src/main/java/dev/mutwakil/androidide/projects/api/JavaModule.kt +++ b/subprojects/projects/src/main/java/dev/mutwakil/androidide/projects/api/JavaModule.kt @@ -21,6 +21,7 @@ import com.google.protobuf.MessageLite import dev.mutwakil.androidide.project.GradleModels import dev.mutwakil.androidide.project.JavaModels import dev.mutwakil.androidide.projects.IProjectManager +import dev.mutwakil.androidide.projects.models.ArtifactScope import dev.mutwakil.androidide.projects.models.buildDir import dev.mutwakil.androidide.projects.models.directory import dev.mutwakil.androidide.projects.models.jarFile @@ -32,21 +33,22 @@ import java.io.File * @author Akash Yadav */ class JavaModule( - delegate: GradleModels.GradleProject, + delegate: GradleModels.GradleProject, ) : ModuleProject(delegate), - JavaModels.JavaProjectOrBuilder by delegate.javaProject { - companion object { - const val SCOPE_COMPILE = "COMPILE" - const val SCOPE_RUNTIME = "RUNTIME" - } - - init { - check(delegate.hasJavaProject()) { - "Project '${delegate.path}' is not a Java project" - } - } - - /** + JavaModels.JavaProjectOrBuilder by delegate.javaProject { + companion object { + const val SCOPE_COMPILE = "COMPILE" + const val SCOPE_RUNTIME = "RUNTIME" + const val SCOPE_TEST = "TEST" + } + + init { + check(delegate.hasJavaProject()) { + "Project '${delegate.path}' is not a Java project" + } + } + + /** * Returns this module's built JAR under `build/libs`, or a non-existent sentinel file when it * has not been built. * @@ -58,112 +60,157 @@ class JavaModule( val named = File(libs, "${delegate.name}.jar") if (named.exists()) { return named - } - - return libs - .listFiles() - ?.firstOrNull { delegate.name?.let(it.name::startsWith) ?: false } - ?: File("module-jar-does-not-exist.jar") - } - - override fun isInitialized(): Boolean = super.isInitialized() - - override fun getDefaultInstanceForType(): MessageLite? = super.getDefaultInstanceForType() - - override fun getClassPaths(): Set = getModuleClasspaths() - - override fun getSourceDirectories(): Set { - val sources = mutableSetOf() - contentRootList.forEach { contentRoot -> - sources.addAll( - contentRoot.sourceDirectoryList.map { sourceDirectory -> - sourceDirectory.directory - }, - ) - } - return sources - } - - override fun getCompileSourceDirectories(): Set { - val dirs = getSourceDirectories().toMutableSet() - getCompileModuleProjects().forEach { dirs.addAll(it.getSourceDirectories()) } - return dirs - } - - override fun getModuleClasspaths(): Set = mutableSetOf(getClassesJar()) - - override fun getCompileClasspaths( - excludeSourceGeneratedClassPath: Boolean, - visited: MutableSet - ): Set { - if (!visited.add(path)) { - return emptySet() - } - val classpaths = - if (excludeSourceGeneratedClassPath) mutableSetOf() else getModuleClasspaths().toMutableSet() - getCompileModuleProjects().forEach { - classpaths.addAll( - it.getCompileClasspaths( - excludeSourceGeneratedClassPath, - visited - ) - ) - } - classpaths.addAll(getDependencyClassPaths()) - return classpaths - } - - override fun getIntermediateClasspaths(): Set { - val result = mutableSetOf() - val buildDirectory = delegate.buildDir - - val kotlinClasses = File(buildDirectory, "tmp/kotlin-classes/main") - if (kotlinClasses.exists()) { - result.add(kotlinClasses) - } - - val javaClasses = File(buildDirectory, "classes/java/main") - if (javaClasses.exists()) { - result.add(javaClasses) - } - - return result - } - - override fun getRuntimeDexFiles(): Set = emptySet() - - override fun getCompileModuleProjects( - visited: MutableSet, - recursionPath: ArrayDeque - ): List { - val root = IProjectManager.getInstance().workspace ?: return emptyList() - if (recursionPath.contains(path)) { - reportDependencyCycle(recursionPath, path) - return emptyList() - } - if (!visited.add(path)) { - return emptyList() - } - return this.dependencyList - .filter { it.hasModule() && it.scope == SCOPE_COMPILE } - .mapNotNull { root.findByPath(it.module.projectPath) } - .filterIsInstance() - } - - override fun hasExternalDependency( - group: String, - name: String, - ): Boolean = - this.dependencyList.any { dependency -> - dependency.hasExternalLibrary() && - dependency.externalLibrary.libraryInfo?.let { artifact -> - artifact.group == group && artifact.name == name - } ?: false - } - - fun getDependencyClassPaths(): Set = - this.dependencyList - .mapNotNull { dependency -> - dependency.jarFile.takeIf { it.exists() } - }.toHashSet() -} + } + + return libs + .listFiles() + ?.firstOrNull { delegate.name?.let(it.name::startsWith) ?: false } + ?: File("module-jar-does-not-exist.jar") + } + + override fun isInitialized(): Boolean = super.isInitialized() + + override fun getDefaultInstanceForType(): MessageLite? = super.getDefaultInstanceForType() + + override fun getClassPaths(): Set = getModuleClasspaths() + + override fun getArtifactScopes(): List = listOf(ArtifactScope.Main, ArtifactScope.UNIT_TEST) + + override fun getSourceDirectories(scope: ArtifactScope): Set = + when (scope) { + ArtifactScope.Main -> mainSourceDirectories() + ArtifactScope.UNIT_TEST -> contentRootList.flatMap { root -> root.testDirectoryList.map { it.directory } }.toSet() + else -> emptySet() + } + + private fun mainSourceDirectories(): Set { + val sources = mutableSetOf() + contentRootList.forEach { contentRoot -> + sources.addAll( + contentRoot.sourceDirectoryList.map { sourceDirectory -> + sourceDirectory.directory + }, + ) + } + return sources + } + + override fun getCompileSourceDirectories(): Set { + val dirs = getSourceDirectories().toMutableSet() + getCompileModuleProjects().forEach { dirs.addAll(it.getSourceDirectories()) } + return dirs + } + + // getDependencyClassPaths does not filter by scope, so test dependencies are already on the + // compile classpath. + override fun getCompileClasspaths( + scope: ArtifactScope, + excludeSourceGeneratedClassPath: Boolean, + ): Set = + when (scope) { + ArtifactScope.Main, ArtifactScope.UNIT_TEST -> getCompileClasspaths(excludeSourceGeneratedClassPath) + else -> emptySet() + } + + // Unit tests see main's module dependencies plus the TEST-scoped ones (testImplementation). + override fun getCompileModuleProjects(scope: ArtifactScope): List { + if (scope == ArtifactScope.Main) { + return getCompileModuleProjects() + } + if (scope != ArtifactScope.UNIT_TEST) { + return emptyList() + } + val root = IProjectManager.getInstance().workspace ?: return emptyList() + val testOnly = + dependencyList + .filter { it.hasModule() && it.scope == SCOPE_TEST } + .mapNotNull { root.findByPath(it.module.projectPath) as? ModuleProject } + .filter { it.path != path } + return (getCompileModuleProjects() + testOnly).distinctBy { it.path } + } + + override fun getModuleClasspaths(): Set = mutableSetOf(getClassesJar()) + + override fun getCompileClasspaths( + excludeSourceGeneratedClassPath: Boolean, + visited: MutableSet, + ): Set { + // Guard against cyclic project-dependency graphs: contribute each module's classpaths once. + if (!visited.add(path)) { + return emptySet() + } + + val classpaths = + if (excludeSourceGeneratedClassPath) mutableSetOf() else getModuleClasspaths().toMutableSet() + + getCompileModuleProjects().forEach { + classpaths.addAll( + it.getCompileClasspaths(excludeSourceGeneratedClassPath, visited), + ) + } + + classpaths.addAll(getDependencyClassPaths()) + return classpaths + } + + override fun getIntermediateClasspaths(): Set { + val result = mutableSetOf() + val buildDirectory = delegate.buildDir + + val kotlinClasses = File(buildDirectory, "tmp/kotlin-classes/main") + if (kotlinClasses.exists()) { + result.add(kotlinClasses) + } + + val javaClasses = File(buildDirectory, "classes/java/main") + if (javaClasses.exists()) { + result.add(javaClasses) + } + + return result + } + + override fun getRuntimeDexFiles(): Set = emptySet() + + override fun getCompileModuleProjects( + visited: MutableSet, + recursionPath: ArrayDeque, + ): List { + val root = IProjectManager.getInstance().workspace ?: return emptyList() + + // True cycle guard (defensive: this override is non-recursive — it returns only direct + // compile-scope module dependencies — so it cannot itself extend the recursion path, but the + // check keeps behavior consistent with AndroidModule if that ever changes). + if (recursionPath.contains(path)) { + reportDependencyCycle(recursionPath, path) + return emptyList() + } + + // Already fully expanded elsewhere (a diamond / shared dependency, not a cycle): dedup. + if (!visited.add(path)) { + return emptyList() + } + + return this.dependencyList + .filter { it.hasModule() && it.scope == SCOPE_COMPILE } + .mapNotNull { root.findByPath(it.module.projectPath) } + .filterIsInstance() + } + + override fun hasExternalDependency( + group: String, + name: String, + ): Boolean = + this.dependencyList.any { dependency -> + dependency.hasExternalLibrary() && + dependency.externalLibrary.libraryInfo?.let { artifact -> + artifact.group == group && artifact.name == name + } ?: false + } + + fun getDependencyClassPaths(): Set = + this.dependencyList + .mapNotNull { dependency -> + dependency.jarFile.takeIf { it.exists() } + }.toHashSet() +} \ No newline at end of file diff --git a/subprojects/projects/src/main/java/dev/mutwakil/androidide/projects/api/ModuleProject.kt b/subprojects/projects/src/main/java/dev/mutwakil/androidide/projects/api/ModuleProject.kt index ffb8a22ae7..b3ed1776cb 100644 --- a/subprojects/projects/src/main/java/dev/mutwakil/androidide/projects/api/ModuleProject.kt +++ b/subprojects/projects/src/main/java/dev/mutwakil/androidide/projects/api/ModuleProject.kt @@ -23,6 +23,7 @@ import dev.mutwakil.androidide.javac.services.fs.CacheFSInfoSingleton import dev.mutwakil.androidide.lookup.Lookup import dev.mutwakil.androidide.project.Common import dev.mutwakil.androidide.project.GradleModels +import dev.mutwakil.androidide.projects.models.ArtifactScope import dev.mutwakil.androidide.projects.models.DEFAULT_COMPILER_SETTINGS import dev.mutwakil.androidide.projects.models.bootClassPaths import dev.mutwakil.androidide.projects.util.BootClasspathProvider @@ -33,6 +34,7 @@ import dev.mutwakil.androidide.utils.StopWatch import org.slf4j.LoggerFactory import java.io.File import java.nio.file.Path +import java.util.concurrent.ConcurrentHashMap import kotlin.io.path.pathString /** @@ -69,15 +71,89 @@ 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 = ConcurrentHashMap() + + /** The Java classes [scope] compiles against. */ + fun javaSourceClasses(scope: ArtifactScope): SourceClassTrie = + if (scope == ArtifactScope.Main) { + compileJavaSourceClasses + } else { + testJavaSourceClasses.computeIfAbsent(scope) { SourceClassTrie() } + } + + /** The scopes of this module other than [ArtifactScope.Main]. */ + private fun nonMainScopes(): List = getArtifactScopes().filter { it != ArtifactScope.Main } + /** - * Get the source directories of this module (non-transitive i.e for this module only). + * The scope whose own source directories hold [file], in [getArtifactScopes] order. Null when + * [file] is instead in a source set this module has that the selected variant does not compile + * (`src/release` while `debug` is selected): it gets no analysis. Any other file is main's. + */ + fun artifactScopeOf(file: Path): ArtifactScope? { + getArtifactScopes() + .firstOrNull { scope -> getSourceDirectories(scope).any { file.startsWith(it.toPath()) } } + ?.let { return it } + return if (getKnownSourceSetDirectories().any { file.startsWith(it.toPath()) }) null else ArtifactScope.Main + } + + /** The source set dirs this module has for any variant; empty when the build model lists none. */ + protected open fun getKnownSourceSetDirectories(): Set = emptySet() + + fun artifactScopeOf(file: File): ArtifactScope? = artifactScopeOf(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 other scope's, any other source in the trie of each scope that + * sees a scope holding its dir (a test fixture goes in the fixtures' and every test scope's). + * Empty when the file is in no source directory. + */ + fun javaSourceClassesFor(file: File): List> { + findSourceRoot(file)?.let { root -> + return listOf(compileJavaSourceClasses to root) + + nonMainScopes() + .filter { getSourceDirectories(it).isNotEmpty() } + .map { javaSourceClasses(it) to root } + } + val path = file.toPath() + // Every matching scope, not the first: a dir such as src/sharedTest can be in both. + val scopes = nonMainScopes() + return scopes.mapNotNull { scope -> + scopes + .filter(scope::sees) + .flatMap(::getSourceDirectories) + .firstOrNull { path.startsWith(it.toPath()) } + ?.let { javaSourceClasses(scope) to it.toPath() } + } + } + + /** 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 + + /** + * The scopes of this module's selected variant: [ArtifactScope.Main] first, then the others + * the module has. + */ + abstract fun getArtifactScopes(): List + + /** + * Get the main source directories of this module (non-transitive i.e for this module only). * * @return The source directories. */ - abstract fun getSourceDirectories(): Set + fun getSourceDirectories(): Set = getSourceDirectories(ArtifactScope.Main) + + /** + * Get the source directories of this module's [scope] (non-transitive). Non-main scopes are + * kept out of main's, so neither main code nor dependent modules see test code. + * + * @return The source directories, or an empty set if the module has no such scope. + */ + abstract fun getSourceDirectories(scope: ArtifactScope): Set /** * Get the source directories with compile scope. This must include source directories of @@ -87,6 +163,47 @@ abstract class ModuleProject( */ abstract fun getCompileSourceDirectories(): Set + /** + * Get the classpaths that [scope] sources compile against. For a non-main scope: everything in + * [getCompileClasspaths] plus that scope's own dependencies. + * + * @param excludeSourceGeneratedClassPath See [getCompileClasspaths]. + * @return The compile classpaths, or an empty set if the module has no such scope. + */ + abstract fun getCompileClasspaths( + scope: ArtifactScope, + excludeSourceGeneratedClassPath: Boolean = false, + ): Set + + /** + * Get the module projects [scope] compiles against, transitively. For a non-main scope: main's, + * plus those only that scope depends on, such as `testImplementation(project(":lib"))`. Never + * this module. + */ + abstract fun getCompileModuleProjects(scope: ArtifactScope): List + + /** + * The source directories [scope] compiles against. For main, [getCompileSourceDirectories]; for + * any other scope: main's, this module's sources of every scope [scope] sees (itself and test + * fixtures), and the sources of the modules only that scope depends on. + */ + fun getCompileSourceDirectories(scope: ArtifactScope): Set = + if (scope == ArtifactScope.Main) { + getCompileSourceDirectories() + } else { + getCompileSourceDirectories() + + nonMainScopes().filter(scope::sees).flatMap(::getSourceDirectories) + + getCompileModuleProjects(scope).flatMap { it.getSourceDirectories() } + + getTestFixturesModuleProjects(scope).flatMap { it.getSourceDirectories(ArtifactScope.TestFixtures) } + } + + /** + * The other modules whose test fixtures [scope] compiles against, such as `:lib` for + * `testImplementation(testFixtures(project(":lib")))`. Their main sources come through + * [getCompileModuleProjects]. + */ + open fun getTestFixturesModuleProjects(scope: ArtifactScope): List = emptyList() + /** * Get the classpaths for this module project. The returned list always included the * `classes.jar`. @@ -210,7 +327,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) @@ -237,34 +358,51 @@ 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 nonMainScopes()) { + if (getSourceDirectories(scope).isEmpty()) { + continue + } + val trie = javaSourceClasses(scope) + val testSources = javaSourcesIn(getCompileSourceDirectories(scope) - getCompileSourceDirectories()) + (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. */ + @JvmOverloads + fun packageNameOrEmpty( + file: Path?, + scope: ArtifactScope = ArtifactScope.Main, + ): String { if (file == null) { return "" } - val sourceNode = searchSourceFileRelatively(file) + val sourceNode = searchSourceFileRelatively(file, scope) if (sourceNode != null) { return sourceNode.packageName } @@ -272,8 +410,12 @@ abstract class ModuleProject( return "" } - private fun searchSourceFileRelatively(file: Path?): SourceNode? { - for (source in getCompileSourceDirectories().map(File::toPath)) { + private fun searchSourceFileRelatively( + file: Path?, + scope: ArtifactScope, + ): SourceNode? { + val roots = getCompileSourceDirectories(scope) + 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 @@ -283,7 +425,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 } @@ -315,8 +457,12 @@ abstract class ModuleProject( return "" } - fun listClassesFromSourceDirs(packageName: String): List = - compileJavaSourceClasses + @JvmOverloads + fun listClassesFromSourceDirs( + packageName: String, + scope: ArtifactScope = ArtifactScope.Main, + ): List = + javaSourceClasses(scope) .findInPackage(packageName) .filterIsInstance() diff --git a/subprojects/projects/src/main/java/dev/mutwakil/androidide/projects/api/Workspace.kt b/subprojects/projects/src/main/java/dev/mutwakil/androidide/projects/api/Workspace.kt index 56a90e367f..61aed24eb5 100644 --- a/subprojects/projects/src/main/java/dev/mutwakil/androidide/projects/api/Workspace.kt +++ b/subprojects/projects/src/main/java/dev/mutwakil/androidide/projects/api/Workspace.kt @@ -84,6 +84,15 @@ data class Workspace( fun findModuleForFile(file: Path): ModuleProject? = findModuleForFile(file.toFile()) + /** + * Whether [file] is in a module but outside every source directory of that module's selected + * variant, so language servers must not analyze it. False for a file in no module. + */ + fun isOutsideSelectedVariant(file: Path): Boolean { + val module = findModuleForFile(file) ?: return false + return module.artifactScopeOf(file) == null + } + @JvmOverloads fun findModuleForFile( file: File, @@ -115,4 +124,4 @@ data class Workspace( return moduleWithLongestPath } -} +} \ No newline at end of file diff --git a/subprojects/projects/src/main/java/dev/mutwakil/androidide/projects/classpath/JarFsClasspathReader.kt b/subprojects/projects/src/main/java/dev/mutwakil/androidide/projects/classpath/JarFsClasspathReader.kt index f54670cbf1..de7618b9a0 100644 --- a/subprojects/projects/src/main/java/dev/mutwakil/androidide/projects/classpath/JarFsClasspathReader.kt +++ b/subprojects/projects/src/main/java/dev/mutwakil/androidide/projects/classpath/JarFsClasspathReader.kt @@ -23,9 +23,9 @@ import dev.mutwakil.androidide.javac.services.fs.CachingJarFileSystemProvider import org.slf4j.LoggerFactory import java.io.File import java.io.IOException +import java.nio.file.FileSystemNotFoundException import java.nio.file.FileVisitResult import java.nio.file.FileVisitResult.CONTINUE -import java.nio.file.FileVisitResult.SKIP_SUBTREE import java.nio.file.Files import java.nio.file.Path import java.nio.file.SimpleFileVisitor @@ -35,93 +35,94 @@ import kotlin.io.path.pathString /** @author Akash Yadav */ class JarFsClasspathReader : IClasspathReader { - companion object { - private val log = LoggerFactory.getLogger(JarFsClasspathReader::class.java) - } + companion object { + private val log = LoggerFactory.getLogger(JarFsClasspathReader::class.java) + } - private val _unreadableJars = mutableListOf() + private val _unreadableJars = mutableListOf() - /** - * JARs skipped during the most recent [listClasses] call because they were corrupt or could not - * be read (e.g. a truncated download / incomplete offline provisioning). Not reported to the - * user: the JAR indexing pass in `:lsp:jvm-symbol-index` is what surfaces an unreadable JAR now, - * from its own scan of the same JARs. Reset at the start of every [listClasses] call. - */ - val unreadableJars: List - get() = _unreadableJars.toList() + /** + * JARs skipped during the most recent [listClasses] call because they were corrupt or could not + * be read (e.g. a truncated download / incomplete offline provisioning). Not reported to the + * user: the JAR indexing pass in `:lsp:jvm-symbol-index` is what surfaces an unreadable JAR now, + * from its own scan of the same JARs. Reset at the start of every [listClasses] call. + */ + val unreadableJars: List + get() = _unreadableJars.toList() - /** - * Lists the classes contained in the given JAR files. Any JAR that is corrupt or cannot be read is - * skipped (rather than aborting the whole scan) and recorded in [unreadableJars]. [unreadableJars] - * is reset at the start of each call. - */ - override fun listClasses(files: Collection): ImmutableSet { - _unreadableJars.clear() - val builder = ImmutableSet.builder() - for (path in files.map(File::toPath)) { - if (!Files.exists(path)) { - continue - } + /** + * Lists the classes contained in the given JAR files. Any JAR that is corrupt or cannot be read is + * skipped (rather than aborting the whole scan) and recorded in [unreadableJars]. [unreadableJars] + * is reset at the start of each call. + */ + override fun listClasses(files: Collection): ImmutableSet { + _unreadableJars.clear() + val builder = ImmutableSet.builder() + for (path in files.map(File::toPath)) { + if (!Files.exists(path)) { + continue + } - try { - val fs = CachingJarFileSystemProvider.newFileSystem(path) as CachedJarFileSystem - for (rootDirectory in fs.rootDirectories) { - Files.walkFileTree( - rootDirectory, - emptySet(), - Int.MAX_VALUE, - object : SimpleFileVisitor() { - override fun preVisitDirectory( - dir: Path?, - attrs: BasicFileAttributes?, - ): FileVisitResult = - if (fs.storeJARPackageDir(dir)) { - CONTINUE - } else { - SKIP_SUBTREE - } + try { + val fs = CachingJarFileSystemProvider.newFileSystem(path) as CachedJarFileSystem + for (packageDirectory in fs.packageIndex().values) { + addClassesIn(packageDirectory, builder) + } + } catch (e: ZipException) { + // A corrupt or truncated JAR must not abort indexing of the remaining classpath entries. + log.warn("Skipping corrupt/unreadable JAR while indexing classpath: {}", path, e) + _unreadableJars.add(path.toFile()) + } catch (e: IOException) { + log.warn("Skipping JAR that could not be read while indexing classpath: {}", path, e) + _unreadableJars.add(path.toFile()) + } catch (e: FileSystemNotFoundException) { + // The provider reports a JAR that is gone by the time it opens it this way, not as an IOException. + log.warn("Skipping JAR that disappeared while indexing classpath: {}", path, e) + _unreadableJars.add(path.toFile()) + } + } + return builder.build() + } - override fun visitFile( - file: Path, - attrs: BasicFileAttributes, - ): FileVisitResult { - var name = file.pathString - if (name.endsWith("/package-info.class") || !name.endsWith(".class")) { - return CONTINUE - } + private fun addClassesIn( + packageDirectory: Path, + builder: ImmutableSet.Builder, + ) { + Files.walkFileTree( + packageDirectory, + emptySet(), + 1, + object : SimpleFileVisitor() { + override fun visitFile( + file: Path, + attrs: BasicFileAttributes, + ): FileVisitResult { + var name = file.pathString + if (!attrs.isRegularFile || name.endsWith("/package-info.class") || !name.endsWith(".class")) { + return CONTINUE + } - name = name.substringBeforeLast(".class") + name = name.substringBeforeLast(".class") - if (name.isBlank()) { - return CONTINUE - } + if (name.isBlank()) { + return CONTINUE + } - if (name.startsWith('/')) { - name = name.substring(1) - } + if (name.startsWith('/')) { + name = name.substring(1) + } - if (name.contains('/')) { - name = name.replace('/', '.') - } + if (name.contains('/')) { + name = name.replace('/', '.') + } - ClassInfo.create(name)?.also { - builder.add(it) - } + ClassInfo.create(name)?.also { + builder.add(it) + } - return super.visitFile(file, attrs) - } - }, - ) - } - } catch (e: ZipException) { - // A corrupt or truncated JAR must not abort indexing of the remaining classpath entries. - log.warn("Skipping corrupt/unreadable JAR while indexing classpath: {}", path, e) - _unreadableJars.add(path.toFile()) - } catch (e: IOException) { - log.warn("Skipping JAR that could not be read while indexing classpath: {}", path, e) - _unreadableJars.add(path.toFile()) - } - } - return builder.build() - } + return CONTINUE + } + }, + ) + } } \ No newline at end of file diff --git a/tooling/api/src/main/java/dev/mutwakil/androidide/tooling/api/sync/ProjectSyncHelper.kt b/tooling/api/src/main/java/dev/mutwakil/androidide/tooling/api/sync/ProjectSyncHelper.kt index 67090d9cce..24f7740732 100644 --- a/tooling/api/src/main/java/dev/mutwakil/androidide/tooling/api/sync/ProjectSyncHelper.kt +++ b/tooling/api/src/main/java/dev/mutwakil/androidide/tooling/api/sync/ProjectSyncHelper.kt @@ -51,7 +51,7 @@ object ProjectSyncHelper { * differs from this one discards the sync files and forces a full sync. The models are * produced and consumed only by the IDE and hold no user data, so discarding them is safe. */ - const val SYNC_META_VERSION = "2" + const val SYNC_META_VERSION = "3" private val logger = LoggerFactory.getLogger(ProjectSyncHelper::class.java) diff --git a/tooling/api/src/main/java/dev/mutwakil/androidide/tooling/api/util/ToolingApiLauncher.kt b/tooling/api/src/main/java/dev/mutwakil/androidide/tooling/api/util/ToolingApiLauncher.kt index a3985f3d51..ef90a9cc84 100644 --- a/tooling/api/src/main/java/dev/mutwakil/androidide/tooling/api/util/ToolingApiLauncher.kt +++ b/tooling/api/src/main/java/dev/mutwakil/androidide/tooling/api/util/ToolingApiLauncher.kt @@ -80,6 +80,7 @@ import dev.mutwakil.androidide.tooling.events.work.WorkItemOperationResult import dev.mutwakil.androidide.tooling.events.work.WorkItemProgressEvent import dev.mutwakil.androidide.tooling.events.work.WorkItemStartEvent import org.eclipse.lsp4j.jsonrpc.Launcher +import org.eclipse.lsp4j.jsonrpc.MessageConsumer import java.io.File import java.io.InputStream import java.io.OutputStream @@ -227,7 +228,8 @@ object ToolingApiLauncher { `in`: InputStream?, out: OutputStream?, executorService: ExecutorService = Executors.newCachedThreadPool(), - ): Launcher = newIoLauncher(arrayOf(client), arrayOf(IToolingApiServer::class.java), `in`, out, executorService) + wrapMessages: (MessageConsumer) -> MessageConsumer = { it }, + ): Launcher = newIoLauncher(arrayOf(client), arrayOf(IToolingApiServer::class.java), `in`, out, executorService, wrapMessages) fun newIoLauncher( locals: Array, @@ -235,12 +237,14 @@ object ToolingApiLauncher { `in`: InputStream?, out: OutputStream?, executorService: ExecutorService = Executors.newCachedThreadPool(), + wrapMessages: (MessageConsumer) -> MessageConsumer = { it }, ): Launcher = Launcher .Builder() .setInput(`in`) .setOutput(out) .setExecutorService(executorService) + .wrapMessages { consumer -> wrapMessages(consumer) } .setLocalServices(listOf(*locals)) .setRemoteInterfaces(listOf(*remotes)) .configureGson { configureGson(it) } diff --git a/tooling/events/src/main/java/dev/mutwakil/androidide/tooling/events/task/TaskOperationDescriptor.kt b/tooling/events/src/main/java/dev/mutwakil/androidide/tooling/events/task/TaskOperationDescriptor.kt index 68264587b6..1c47c0c50f 100644 --- a/tooling/events/src/main/java/dev/mutwakil/androidide/tooling/events/task/TaskOperationDescriptor.kt +++ b/tooling/events/src/main/java/dev/mutwakil/androidide/tooling/events/task/TaskOperationDescriptor.kt @@ -20,33 +20,41 @@ package dev.mutwakil.androidide.tooling.events.task import dev.mutwakil.androidide.tooling.events.OperationDescriptor import dev.mutwakil.androidide.tooling.model.PluginIdentifier -/** @author Akash Yadav */ +/** + * A Gradle task operation, as the IDE receives it in progress events. + * + * [dependencies] holds the direct dependencies' task paths (an operation name for one that is not a + * task), not their descriptors: those nest the whole task graph, and a single event serialized that + * way reached 23.7 MB. + * + * @author Akash Yadav + */ class TaskOperationDescriptor( - val dependencies: Set, - val originPlugin: PluginIdentifier, - val taskPath: String, - override val name: String, - override val displayName: String + val dependencies: Set, + val originPlugin: PluginIdentifier, + val taskPath: String, + override val name: String, + override val displayName: String, ) : OperationDescriptor() { - override fun equals(other: Any?): Boolean { - if (this === other) return true - if (other !is TaskOperationDescriptor) return false + override fun equals(other: Any?): Boolean { + if (this === other) return true + if (other !is TaskOperationDescriptor) return false - if (dependencies != other.dependencies) return false - if (originPlugin != other.originPlugin) return false - if (taskPath != other.taskPath) return false - if (name != other.name) return false - if (displayName != other.displayName) return false + if (dependencies != other.dependencies) return false + if (originPlugin != other.originPlugin) return false + if (taskPath != other.taskPath) return false + if (name != other.name) return false + if (displayName != other.displayName) return false - return true - } + return true + } - override fun hashCode(): Int { - var result = dependencies.hashCode() - result = 31 * result + originPlugin.hashCode() - result = 31 * result + taskPath.hashCode() - result = 31 * result + name.hashCode() - result = 31 * result + displayName.hashCode() - return result - } -} + override fun hashCode(): Int { + var result = dependencies.hashCode() + result = 31 * result + originPlugin.hashCode() + result = 31 * result + taskPath.hashCode() + result = 31 * result + name.hashCode() + result = 31 * result + displayName.hashCode() + return result + } +} \ No newline at end of file diff --git a/tooling/events/src/main/java/dev/mutwakil/androidide/tooling/events/transform/TransformOperationDescriptor.kt b/tooling/events/src/main/java/dev/mutwakil/androidide/tooling/events/transform/TransformOperationDescriptor.kt index cdfe79ff27..ae73af7bda 100644 --- a/tooling/events/src/main/java/dev/mutwakil/androidide/tooling/events/transform/TransformOperationDescriptor.kt +++ b/tooling/events/src/main/java/dev/mutwakil/androidide/tooling/events/transform/TransformOperationDescriptor.kt @@ -19,37 +19,48 @@ package dev.mutwakil.androidide.tooling.events.transform import dev.mutwakil.androidide.tooling.events.OperationDescriptor -/** @author Akash Yadav */ +/** + * A Gradle artifact transform operation, as the IDE receives it in progress events. + * + * [dependencies] holds the direct dependencies' task paths (an operation name for one that is not a + * task), for the same reason as [TaskOperationDescriptor.dependencies]. + * + * @author Akash Yadav + */ class TransformOperationDescriptor( - val dependencies: Set, - val subject: SubjectDescriptor, - val transformer: TransformerDescriptor, - override val name: String, - override val displayName: String + val dependencies: Set, + val subject: SubjectDescriptor, + val transformer: TransformerDescriptor, + override val name: String, + override val displayName: String, ) : OperationDescriptor() { - class SubjectDescriptor(val displayName: String) - - class TransformerDescriptor(val displayName: String) - - override fun equals(other: Any?): Boolean { - if (this === other) return true - if (other !is TransformOperationDescriptor) return false - - if (dependencies != other.dependencies) return false - if (subject != other.subject) return false - if (transformer != other.transformer) return false - if (name != other.name) return false - if (displayName != other.displayName) return false - - return true - } - - override fun hashCode(): Int { - var result = dependencies.hashCode() - result = 31 * result + subject.hashCode() - result = 31 * result + transformer.hashCode() - result = 31 * result + name.hashCode() - result = 31 * result + displayName.hashCode() - return result - } -} + class SubjectDescriptor( + val displayName: String, + ) + + class TransformerDescriptor( + val displayName: String, + ) + + override fun equals(other: Any?): Boolean { + if (this === other) return true + if (other !is TransformOperationDescriptor) return false + + if (dependencies != other.dependencies) return false + if (subject != other.subject) return false + if (transformer != other.transformer) return false + if (name != other.name) return false + if (displayName != other.displayName) return false + + return true + } + + override fun hashCode(): Int { + var result = dependencies.hashCode() + result = 31 * result + subject.hashCode() + result = 31 * result + transformer.hashCode() + result = 31 * result + name.hashCode() + result = 31 * result + displayName.hashCode() + return result + } +} \ No newline at end of file diff --git a/tooling/impl/src/main/java/dev/mutwakil/androidide/tooling/impl/progress/EventTransformer.kt b/tooling/impl/src/main/java/dev/mutwakil/androidide/tooling/impl/progress/EventTransformer.kt index d66357441e..83e65f75b3 100644 --- a/tooling/impl/src/main/java/dev/mutwakil/androidide/tooling/impl/progress/EventTransformer.kt +++ b/tooling/impl/src/main/java/dev/mutwakil/androidide/tooling/impl/progress/EventTransformer.kt @@ -69,403 +69,394 @@ import org.gradle.tooling.model.ProjectIdentifier /** @author Akash Yadav */ class EventTransformer { - companion object { - - // ------------------------ COMMON ------------------------- - private fun operationDescriptor( - descriptor: OperationDescriptor? - ): dev.mutwakil.androidide.tooling.events.OperationDescriptor? = - when (descriptor) { - null -> null - is ProjectConfigurationOperationDescriptor -> projectConfigurationDescriptor(descriptor) - is FileDownloadOperationDescriptor -> fileDownloadDescriptor(descriptor) - is TaskOperationDescriptor -> taskDescriptor(descriptor) - is TransformOperationDescriptor -> transformDescriptor(descriptor) - is WorkItemOperationDescriptor -> workDescriptor(descriptor) - else -> - DefaultOperationDescriptor(name = descriptor.name, displayName = descriptor.displayName) - } - - // ----------------- PROJECT CONFIGURATION -------------------- - @JvmStatic - fun projectConfigurationStart( - event: ProjectConfigurationStartEvent - ): dev.mutwakil.androidide.tooling.events.configuration.ProjectConfigurationProgressEvent = - dev.mutwakil.androidide.tooling.events.configuration.ProjectConfigurationStartEvent( - displayName = event.displayName, - eventTime = event.eventTime, - descriptor = projectConfigurationDescriptor(event.descriptor) - ) - - @JvmStatic - fun projectConfigurationProgress( - event: ProjectConfigurationProgressEvent - ): dev.mutwakil.androidide.tooling.events.configuration.ProjectConfigurationProgressEvent = - dev.mutwakil.androidide.tooling.events.configuration.ProjectConfigurationProgressEvent( - displayName = event.displayName, - eventTime = event.eventTime, - descriptor = projectConfigurationDescriptor(event.descriptor) - ) - - @JvmStatic - fun projectConfigurationFinish( - event: ProjectConfigurationFinishEvent - ): dev.mutwakil.androidide.tooling.events.configuration.ProjectConfigurationProgressEvent = - dev.mutwakil.androidide.tooling.events.configuration.ProjectConfigurationFinishEvent( - displayName = event.displayName, - eventTime = event.eventTime, - descriptor = projectConfigurationDescriptor(event.descriptor), - result = projectConfigurationResult(event.result) - ) - - private fun projectConfigurationResult( - result: ProjectConfigurationOperationResult - ): dev.mutwakil.androidide.tooling.events.configuration.ProjectConfigurationOperationResult = - dev.mutwakil.androidide.tooling.events.configuration.ProjectConfigurationOperationResult( - pluginApplicationResults = - result.pluginApplicationResults.map { - PluginApplicationResult( - plugin = PluginIdentifier(it.plugin?.displayName ?: "Unknown plugin"), - it.totalConfigurationTime.toMillis() - ) - }, - startTime = result.startTime, - endTime = result.endTime, - success = result is ProjectConfigurationSuccessResult - ) - - private fun projectConfigurationDescriptor( - descriptor: ProjectConfigurationOperationDescriptor - ): dev.mutwakil.androidide.tooling.events.configuration.ProjectConfigurationOperationDescriptor = - dev.mutwakil.androidide.tooling.events.configuration.ProjectConfigurationOperationDescriptor( - project = projectIdentifier(descriptor.project), - name = descriptor.name, - displayName = descriptor.displayName - ) - - private fun projectIdentifier( - project: ProjectIdentifier - ): dev.mutwakil.androidide.tooling.model.ProjectIdentifier = - dev.mutwakil.androidide.tooling.model.ProjectIdentifier( - projectPath = project.projectPath, - buildIdentifier = - dev.mutwakil.androidide.tooling.model.BuildIdentifier(project.buildIdentifier.rootDir) - ) - - // ---------------------- FILE DOWNLOAD --------------------------------- - @JvmStatic - fun fileDownloadStart( - event: org.gradle.tooling.events.download.FileDownloadStartEvent - ): FileDownloadStartEvent = - FileDownloadStartEvent( - eventTime = event.eventTime, - displayName = event.displayName, - descriptor = fileDownloadDescriptor(event.descriptor) - ) - - @JvmStatic - fun fileDownloadProgress( - event: org.gradle.tooling.events.download.FileDownloadProgressEvent - ): FileDownloadProgressEvent = - FileDownloadProgressEvent( - eventTime = event.eventTime, - displayName = event.displayName, - descriptor = fileDownloadDescriptor(event.descriptor) - ) - - @JvmStatic - fun fileDownloadFinish( - event: org.gradle.tooling.events.download.FileDownloadFinishEvent - ): FileDownloadFinishEvent = - FileDownloadFinishEvent( - eventTime = event.eventTime, - displayName = event.displayName, - descriptor = fileDownloadDescriptor(event.descriptor), - result = fileDownloadResult(event.result) - ) - - private fun fileDownloadResult( - result: FileDownloadResult - ): dev.mutwakil.androidide.tooling.events.download.FileDownloadResult = - dev.mutwakil.androidide.tooling.events.download.FileDownloadResult( - bytesDownloaded = result.bytesDownloaded, - startTime = result.startTime, - endTime = result.endTime - ) - - private fun fileDownloadDescriptor( - descriptor: FileDownloadOperationDescriptor - ): dev.mutwakil.androidide.tooling.events.download.FileDownloadOperationDescriptor = - dev.mutwakil.androidide.tooling.events.download.FileDownloadOperationDescriptor( - descriptor.uri, - descriptor.name, - descriptor.displayName - ) - - // -------------------- TASK ------------------------------- - @JvmStatic - fun taskStart(event: org.gradle.tooling.events.task.TaskStartEvent): TaskStartEvent = - TaskStartEvent( - eventTime = event.eventTime, - displayName = event.displayName, - descriptor = taskDescriptor(event.descriptor) - ) - - @JvmStatic - fun taskProgress(event: org.gradle.tooling.events.task.TaskProgressEvent): TaskProgressEvent = - TaskProgressEvent( - eventTime = event.eventTime, - displayName = event.displayName, - descriptor = taskDescriptor(event.descriptor) - ) - - @JvmStatic - fun taskFinish(event: org.gradle.tooling.events.task.TaskFinishEvent): TaskFinishEvent = - TaskFinishEvent( - eventTime = event.eventTime, - displayName = event.displayName, - descriptor = taskDescriptor(event.descriptor), - result = taskResult(event.result) - ) - - private fun taskResult( - result: TaskOperationResult - ): dev.mutwakil.androidide.tooling.events.task.TaskOperationResult { - - // The order of conditions must not change here. - - if (result is TaskSuccessResult) { - return dev.mutwakil.androidide.tooling.events.task.TaskSuccessResult( - result.isUpToDate, - result.isFromCache, - result.startTime, - result.endTime, - result.isIncremental, - result.executionReasons - ) - } - - if (result is TaskFailureResult) { - return dev.mutwakil.androidide.tooling.events.task.TaskFailureResult( - result.startTime, - result.endTime - ) - } - - if (result is TaskExecutionResult) { - return dev.mutwakil.androidide.tooling.events.task.TaskExecutionResult( - result.startTime, - result.endTime, - result.isIncremental, - result.executionReasons - ) - } - - if (result is TaskSkippedResult) { - return dev.mutwakil.androidide.tooling.events.task.TaskSkippedResult( - result.skipMessage, - result.startTime, - result.endTime - ) - } - - return dev.mutwakil.androidide.tooling.events.task.TaskOperationResult( - startTime = result.startTime, - endTime = result.endTime - ) - } - - private fun taskDescriptor( - descriptor: TaskOperationDescriptor - ): dev.mutwakil.androidide.tooling.events.task.TaskOperationDescriptor = - dev.mutwakil.androidide.tooling.events.task.TaskOperationDescriptor( - dependencies = - descriptor.dependencies.filterNotNull().mapNotNull { operationDescriptor(it) }.toSet(), - originPlugin = PluginIdentifier(descriptor.originPlugin?.displayName ?: "Unknown plugin"), - taskPath = descriptor.taskPath, - name = descriptor.name, - displayName = descriptor.displayName - ) - - // ----------------------- TEST ------------------------- - @JvmStatic - fun testStart(event: org.gradle.tooling.events.test.TestStartEvent): TestStartEvent = - TestStartEvent( - eventTime = event.eventTime, - displayName = event.displayName, - operationDescriptor = testDescriptor(event.descriptor) - ) - - @JvmStatic - fun testProgress(event: org.gradle.tooling.events.test.TestProgressEvent): TestProgressEvent = - TestProgressEvent( - eventTime = event.eventTime, - displayName = event.displayName, - descriptor = testDescriptor(event.descriptor) - ) - - @JvmStatic - fun testFinish(event: org.gradle.tooling.events.test.TestFinishEvent): TestFinishEvent = - TestFinishEvent( - eventTime = event.eventTime, - displayName = event.displayName, - operationDescriptor = testDescriptor(event.descriptor), - result = testResult(event.result) - ) - - private fun testResult( - result: org.gradle.tooling.events.test.TestOperationResult - ): TestOperationResult = - TestOperationResult( - startTime = result.startTime, - endTime = result.endTime, - success = result is TestSuccessResult - ) - - private fun testDescriptor( - descriptor: TestOperationDescriptor - ): dev.mutwakil.androidide.tooling.events.test.TestOperationDescriptor = - dev.mutwakil.androidide.tooling.events.test.TestOperationDescriptor( - name = descriptor.name, - displayName = descriptor.displayName - ) - - // ----------------------- TRANSFORM ------------------------- - @JvmStatic - fun transformStart( - event: org.gradle.tooling.events.transform.TransformStartEvent - ): TransformStartEvent = - TransformStartEvent( - eventTime = event.eventTime, - displayName = event.displayName, - descriptor = transformDescriptor(event.descriptor) - ) - - @JvmStatic - fun transformProgress( - event: org.gradle.tooling.events.transform.TransformProgressEvent - ): TransformStartEvent = - TransformStartEvent( - eventTime = event.eventTime, - displayName = event.displayName, - descriptor = transformDescriptor(event.descriptor) - ) - - @JvmStatic - fun transformFinish( - event: org.gradle.tooling.events.transform.TransformFinishEvent - ): TransformFinishEvent = - TransformFinishEvent( - eventTime = event.eventTime, - displayName = event.displayName, - operationDescriptor = transformDescriptor(event.descriptor), - result = transformResult(event.result) - ) - - private fun transformResult( - result: org.gradle.tooling.events.transform.TransformOperationResult - ): TransformOperationResult = - TransformOperationResult( - success = result is TransformSuccessResult, - startTime = result.startTime, - endTime = result.endTime - ) - - private fun transformDescriptor( - descriptor: TransformOperationDescriptor - ): dev.mutwakil.androidide.tooling.events.transform.TransformOperationDescriptor = - dev.mutwakil.androidide.tooling.events.transform.TransformOperationDescriptor( - name = descriptor.name, - displayName = descriptor.displayName, - subject = SubjectDescriptor(descriptor.subject.displayName), - transformer = - dev.mutwakil.androidide.tooling.events.transform.TransformOperationDescriptor - .TransformerDescriptor(descriptor.transformer.displayName), - dependencies = descriptor.dependencies.mapNotNull { operationDescriptor(it) }.toSet() - ) - - // ----------------------- WORK ITEM ------------------------- - @JvmStatic - fun workStart(event: org.gradle.tooling.events.work.WorkItemStartEvent): WorkItemStartEvent = - WorkItemStartEvent( - eventTime = event.eventTime, - displayName = event.displayName, - descriptor = workDescriptor(event.descriptor) - ) - - @JvmStatic - fun workProgress( - event: org.gradle.tooling.events.work.WorkItemProgressEvent - ): WorkItemProgressEvent = - WorkItemProgressEvent( - eventTime = event.eventTime, - displayName = event.displayName, - descriptor = workDescriptor(event.descriptor) - ) - - @JvmStatic - fun workFinish(event: org.gradle.tooling.events.work.WorkItemFinishEvent): WorkItemFinishEvent = - WorkItemFinishEvent( - eventTime = event.eventTime, - displayName = event.displayName, - operationDescriptor = workDescriptor(event.descriptor), - result = workResult(event.result) - ) - - private fun workResult( - result: org.gradle.tooling.events.work.WorkItemOperationResult - ): WorkItemOperationResult = - WorkItemOperationResult( - success = result is WorkItemSuccessResult, - startTime = result.startTime, - endTime = result.endTime - ) - - private fun workDescriptor( - descriptor: WorkItemOperationDescriptor - ): dev.mutwakil.androidide.tooling.events.work.WorkItemOperationDescriptor = - dev.mutwakil.androidide.tooling.events.work.WorkItemOperationDescriptor( - name = descriptor.name, - displayName = descriptor.displayName, - className = descriptor.className - ) - - // ---------------------------- STATUS --------------------------------- - fun statusEvent(event: org.gradle.tooling.events.StatusEvent): StatusEvent = - StatusEvent( - total = event.total, - progress = event.progress, - unit = event.unit, - displayName = event.displayName, - eventTime = event.eventTime, - descriptor = operationDescriptor(event.descriptor)!! - ) - - // ----------------------- DEFAULT ---------------------------------- - fun progress(event: ProgressEvent): dev.mutwakil.androidide.tooling.events.ProgressEvent = - DefaultProgressEvent( - eventTime = event.eventTime, - displayName = event.displayName, - descriptor = operationDescriptor(event.descriptor)!! - ) - - fun start( - event: org.gradle.tooling.events.StartEvent - ): dev.mutwakil.androidide.tooling.events.ProgressEvent = - DefaultStartEvent( - eventTime = event.eventTime, - displayName = event.displayName, - descriptor = operationDescriptor(event.descriptor)!! - ) - - fun finish( - event: org.gradle.tooling.events.FinishEvent - ): dev.mutwakil.androidide.tooling.events.ProgressEvent = - DefaultFinishEvent( - eventTime = event.eventTime, - displayName = event.displayName, - descriptor = operationDescriptor(event.descriptor)!!, - result = DefaultOperationResult(event.result.startTime, event.result.endTime) - ) - } -} + companion object { + // ------------------------ COMMON ------------------------- + private fun operationDescriptor(descriptor: OperationDescriptor?): dev.mutwakil.androidide.tooling.events.OperationDescriptor? = + when (descriptor) { + null -> { + null + } + + is ProjectConfigurationOperationDescriptor -> { + projectConfigurationDescriptor(descriptor) + } + + is FileDownloadOperationDescriptor -> { + fileDownloadDescriptor(descriptor) + } + + is TaskOperationDescriptor -> { + taskDescriptor(descriptor) + } + + is TransformOperationDescriptor -> { + transformDescriptor(descriptor) + } + + is WorkItemOperationDescriptor -> { + workDescriptor(descriptor) + } + + else -> { + DefaultOperationDescriptor(name = descriptor.name, displayName = descriptor.displayName) + } + } + + /* + * Direct dependencies as task paths only. Converting them to descriptors recursed through the + * whole task graph, and JSON copies a shared subtree once per path to it: a single task event + * for the CoGo app reached 23.7 MB and ran the IDE's message reader out of heap. + */ + private fun dependencyPaths(dependencies: Set): Set = + dependencies.filterNotNull().mapTo(LinkedHashSet()) { dependency -> + (dependency as? TaskOperationDescriptor)?.taskPath ?: dependency.name + } + + // ----------------- PROJECT CONFIGURATION -------------------- + @JvmStatic + fun projectConfigurationStart( + event: ProjectConfigurationStartEvent, + ): dev.mutwakil.androidide.tooling.events.configuration.ProjectConfigurationProgressEvent = + dev.mutwakil.androidide.tooling.events.configuration.ProjectConfigurationStartEvent( + displayName = event.displayName, + eventTime = event.eventTime, + descriptor = projectConfigurationDescriptor(event.descriptor), + ) + + @JvmStatic + fun projectConfigurationProgress( + event: ProjectConfigurationProgressEvent, + ): dev.mutwakil.androidide.tooling.events.configuration.ProjectConfigurationProgressEvent = + dev.mutwakil.androidide.tooling.events.configuration.ProjectConfigurationProgressEvent( + displayName = event.displayName, + eventTime = event.eventTime, + descriptor = projectConfigurationDescriptor(event.descriptor), + ) + + @JvmStatic + fun projectConfigurationFinish( + event: ProjectConfigurationFinishEvent, + ): dev.mutwakil.androidide.tooling.events.configuration.ProjectConfigurationProgressEvent = + dev.mutwakil.androidide.tooling.events.configuration.ProjectConfigurationFinishEvent( + displayName = event.displayName, + eventTime = event.eventTime, + descriptor = projectConfigurationDescriptor(event.descriptor), + result = projectConfigurationResult(event.result), + ) + + private fun projectConfigurationResult( + result: ProjectConfigurationOperationResult, + ): dev.mutwakil.androidide.tooling.events.configuration.ProjectConfigurationOperationResult = + dev.mutwakil.androidide.tooling.events.configuration.ProjectConfigurationOperationResult( + pluginApplicationResults = + result.pluginApplicationResults.map { + PluginApplicationResult( + plugin = PluginIdentifier(it.plugin?.displayName ?: "Unknown plugin"), + it.totalConfigurationTime.toMillis(), + ) + }, + startTime = result.startTime, + endTime = result.endTime, + success = result is ProjectConfigurationSuccessResult, + ) + + private fun projectConfigurationDescriptor( + descriptor: ProjectConfigurationOperationDescriptor, + ): dev.mutwakil.androidide.tooling.events.configuration.ProjectConfigurationOperationDescriptor = + dev.mutwakil.androidide.tooling.events.configuration.ProjectConfigurationOperationDescriptor( + project = projectIdentifier(descriptor.project), + name = descriptor.name, + displayName = descriptor.displayName, + ) + + private fun projectIdentifier(project: ProjectIdentifier): dev.mutwakil.androidide.tooling.model.ProjectIdentifier = + dev.mutwakil.androidide.tooling.model.ProjectIdentifier( + projectPath = project.projectPath, + buildIdentifier = + dev.mutwakil.androidide.tooling.model + .BuildIdentifier(project.buildIdentifier.rootDir), + ) + + // ---------------------- FILE DOWNLOAD --------------------------------- + @JvmStatic + fun fileDownloadStart(event: org.gradle.tooling.events.download.FileDownloadStartEvent): FileDownloadStartEvent = + FileDownloadStartEvent( + eventTime = event.eventTime, + displayName = event.displayName, + descriptor = fileDownloadDescriptor(event.descriptor), + ) + + @JvmStatic + fun fileDownloadProgress(event: org.gradle.tooling.events.download.FileDownloadProgressEvent): FileDownloadProgressEvent = + FileDownloadProgressEvent( + eventTime = event.eventTime, + displayName = event.displayName, + descriptor = fileDownloadDescriptor(event.descriptor), + ) + + @JvmStatic + fun fileDownloadFinish(event: org.gradle.tooling.events.download.FileDownloadFinishEvent): FileDownloadFinishEvent = + FileDownloadFinishEvent( + eventTime = event.eventTime, + displayName = event.displayName, + descriptor = fileDownloadDescriptor(event.descriptor), + result = fileDownloadResult(event.result), + ) + + private fun fileDownloadResult(result: FileDownloadResult): dev.mutwakil.androidide.tooling.events.download.FileDownloadResult = + dev.mutwakil.androidide.tooling.events.download.FileDownloadResult( + bytesDownloaded = result.bytesDownloaded, + startTime = result.startTime, + endTime = result.endTime, + ) + + private fun fileDownloadDescriptor( + descriptor: FileDownloadOperationDescriptor, + ): dev.mutwakil.androidide.tooling.events.download.FileDownloadOperationDescriptor = + dev.mutwakil.androidide.tooling.events.download.FileDownloadOperationDescriptor( + descriptor.uri, + descriptor.name, + descriptor.displayName, + ) + + // -------------------- TASK ------------------------------- + @JvmStatic + fun taskStart(event: org.gradle.tooling.events.task.TaskStartEvent): TaskStartEvent = + TaskStartEvent( + eventTime = event.eventTime, + displayName = event.displayName, + descriptor = taskDescriptor(event.descriptor), + ) + + @JvmStatic + fun taskProgress(event: org.gradle.tooling.events.task.TaskProgressEvent): TaskProgressEvent = + TaskProgressEvent( + eventTime = event.eventTime, + displayName = event.displayName, + descriptor = taskDescriptor(event.descriptor), + ) + + @JvmStatic + fun taskFinish(event: org.gradle.tooling.events.task.TaskFinishEvent): TaskFinishEvent = + TaskFinishEvent( + eventTime = event.eventTime, + displayName = event.displayName, + descriptor = taskDescriptor(event.descriptor), + result = taskResult(event.result), + ) + + private fun taskResult(result: TaskOperationResult): dev.mutwakil.androidide.tooling.events.task.TaskOperationResult { + // The order of conditions must not change here. + + if (result is TaskSuccessResult) { + return dev.mutwakil.androidide.tooling.events.task.TaskSuccessResult( + result.isUpToDate, + result.isFromCache, + result.startTime, + result.endTime, + result.isIncremental, + result.executionReasons, + ) + } + + if (result is TaskFailureResult) { + return dev.mutwakil.androidide.tooling.events.task.TaskFailureResult( + result.startTime, + result.endTime, + ) + } + + if (result is TaskExecutionResult) { + return dev.mutwakil.androidide.tooling.events.task.TaskExecutionResult( + result.startTime, + result.endTime, + result.isIncremental, + result.executionReasons, + ) + } + + if (result is TaskSkippedResult) { + return dev.mutwakil.androidide.tooling.events.task.TaskSkippedResult( + result.skipMessage, + result.startTime, + result.endTime, + ) + } + + return dev.mutwakil.androidide.tooling.events.task.TaskOperationResult( + startTime = result.startTime, + endTime = result.endTime, + ) + } + + private fun taskDescriptor(descriptor: TaskOperationDescriptor): dev.mutwakil.androidide.tooling.events.task.TaskOperationDescriptor = + dev.mutwakil.androidide.tooling.events.task.TaskOperationDescriptor( + dependencies = dependencyPaths(descriptor.dependencies), + originPlugin = PluginIdentifier(descriptor.originPlugin?.displayName ?: "Unknown plugin"), + taskPath = descriptor.taskPath, + name = descriptor.name, + displayName = descriptor.displayName, + ) + + // ----------------------- TEST ------------------------- + @JvmStatic + fun testStart(event: org.gradle.tooling.events.test.TestStartEvent): TestStartEvent = + TestStartEvent( + eventTime = event.eventTime, + displayName = event.displayName, + operationDescriptor = testDescriptor(event.descriptor), + ) + + @JvmStatic + fun testProgress(event: org.gradle.tooling.events.test.TestProgressEvent): TestProgressEvent = + TestProgressEvent( + eventTime = event.eventTime, + displayName = event.displayName, + descriptor = testDescriptor(event.descriptor), + ) + + @JvmStatic + fun testFinish(event: org.gradle.tooling.events.test.TestFinishEvent): TestFinishEvent = + TestFinishEvent( + eventTime = event.eventTime, + displayName = event.displayName, + operationDescriptor = testDescriptor(event.descriptor), + result = testResult(event.result), + ) + + private fun testResult(result: org.gradle.tooling.events.test.TestOperationResult): TestOperationResult = + TestOperationResult( + startTime = result.startTime, + endTime = result.endTime, + success = result is TestSuccessResult, + ) + + private fun testDescriptor(descriptor: TestOperationDescriptor): dev.mutwakil.androidide.tooling.events.test.TestOperationDescriptor = + dev.mutwakil.androidide.tooling.events.test.TestOperationDescriptor( + name = descriptor.name, + displayName = descriptor.displayName, + ) + + // ----------------------- TRANSFORM ------------------------- + @JvmStatic + fun transformStart(event: org.gradle.tooling.events.transform.TransformStartEvent): TransformStartEvent = + TransformStartEvent( + eventTime = event.eventTime, + displayName = event.displayName, + descriptor = transformDescriptor(event.descriptor), + ) + + @JvmStatic + fun transformProgress(event: org.gradle.tooling.events.transform.TransformProgressEvent): TransformStartEvent = + TransformStartEvent( + eventTime = event.eventTime, + displayName = event.displayName, + descriptor = transformDescriptor(event.descriptor), + ) + + @JvmStatic + fun transformFinish(event: org.gradle.tooling.events.transform.TransformFinishEvent): TransformFinishEvent = + TransformFinishEvent( + eventTime = event.eventTime, + displayName = event.displayName, + operationDescriptor = transformDescriptor(event.descriptor), + result = transformResult(event.result), + ) + + private fun transformResult(result: org.gradle.tooling.events.transform.TransformOperationResult): TransformOperationResult = + TransformOperationResult( + success = result is TransformSuccessResult, + startTime = result.startTime, + endTime = result.endTime, + ) + + private fun transformDescriptor( + descriptor: TransformOperationDescriptor, + ): dev.mutwakil.androidide.tooling.events.transform.TransformOperationDescriptor = + dev.mutwakil.androidide.tooling.events.transform.TransformOperationDescriptor( + name = descriptor.name, + displayName = descriptor.displayName, + subject = SubjectDescriptor(descriptor.subject.displayName), + transformer = + dev.mutwakil.androidide.tooling.events.transform.TransformOperationDescriptor + .TransformerDescriptor(descriptor.transformer.displayName), + dependencies = dependencyPaths(descriptor.dependencies), + ) + + // ----------------------- WORK ITEM ------------------------- + @JvmStatic + fun workStart(event: org.gradle.tooling.events.work.WorkItemStartEvent): WorkItemStartEvent = + WorkItemStartEvent( + eventTime = event.eventTime, + displayName = event.displayName, + descriptor = workDescriptor(event.descriptor), + ) + + @JvmStatic + fun workProgress(event: org.gradle.tooling.events.work.WorkItemProgressEvent): WorkItemProgressEvent = + WorkItemProgressEvent( + eventTime = event.eventTime, + displayName = event.displayName, + descriptor = workDescriptor(event.descriptor), + ) + + @JvmStatic + fun workFinish(event: org.gradle.tooling.events.work.WorkItemFinishEvent): WorkItemFinishEvent = + WorkItemFinishEvent( + eventTime = event.eventTime, + displayName = event.displayName, + operationDescriptor = workDescriptor(event.descriptor), + result = workResult(event.result), + ) + + private fun workResult(result: org.gradle.tooling.events.work.WorkItemOperationResult): WorkItemOperationResult = + WorkItemOperationResult( + success = result is WorkItemSuccessResult, + startTime = result.startTime, + endTime = result.endTime, + ) + + private fun workDescriptor( + descriptor: WorkItemOperationDescriptor, + ): dev.mutwakil.androidide.tooling.events.work.WorkItemOperationDescriptor = + dev.mutwakil.androidide.tooling.events.work.WorkItemOperationDescriptor( + name = descriptor.name, + displayName = descriptor.displayName, + className = descriptor.className, + ) + + // ---------------------------- STATUS --------------------------------- + fun statusEvent(event: org.gradle.tooling.events.StatusEvent): StatusEvent = + StatusEvent( + total = event.total, + progress = event.progress, + unit = event.unit, + displayName = event.displayName, + eventTime = event.eventTime, + descriptor = operationDescriptor(event.descriptor)!!, + ) + + // ----------------------- DEFAULT ---------------------------------- + fun progress(event: ProgressEvent): dev.mutwakil.androidide.tooling.events.ProgressEvent = + DefaultProgressEvent( + eventTime = event.eventTime, + displayName = event.displayName, + descriptor = operationDescriptor(event.descriptor)!!, + ) + + fun start(event: org.gradle.tooling.events.StartEvent): dev.mutwakil.androidide.tooling.events.ProgressEvent = + DefaultStartEvent( + eventTime = event.eventTime, + displayName = event.displayName, + descriptor = operationDescriptor(event.descriptor)!!, + ) + + fun finish(event: org.gradle.tooling.events.FinishEvent): dev.mutwakil.androidide.tooling.events.ProgressEvent = + DefaultFinishEvent( + eventTime = event.eventTime, + displayName = event.displayName, + descriptor = operationDescriptor(event.descriptor)!!, + result = DefaultOperationResult(event.result.startTime, event.result.endTime), + ) + } +} \ No newline at end of file diff --git a/tooling/impl/src/main/java/dev/mutwakil/androidide/tooling/impl/serial/AndroidProjectExts.kt b/tooling/impl/src/main/java/dev/mutwakil/androidide/tooling/impl/serial/AndroidProjectExts.kt index bf96a4f99f..e66ccecd1e 100644 --- a/tooling/impl/src/main/java/dev/mutwakil/androidide/tooling/impl/serial/AndroidProjectExts.kt +++ b/tooling/impl/src/main/java/dev/mutwakil/androidide/tooling/impl/serial/AndroidProjectExts.kt @@ -61,6 +61,7 @@ fun createAndroidProjectProtoModel( ProjectType.FUSED_LIBRARY -> AndroidModels.ProjectType.FusedLibrary }, mainSourceSet = basicAndroidProject.mainSourceSet?.asProtoModel(), + sourceSetDirPathsList = basicAndroidProject.allSourceSetDirs(), javaCompilerSettings = androidProject.javaCompileOptions?.asProtoModel(), kotlinCompilerSettings = null, // TODO: Read kotlin compiler settings viewBindingOptions = androidProject.viewBindingOptions?.asProtoModel(), @@ -82,8 +83,8 @@ fun createAndroidProjectProtoModel( fun VariantDependencies.asProtoModel() = VariantDependencies( name = this.name, - mainArtifact = this.mainArtifact.asProtoModel(), librariesMap = this.libraries.mapValues { entry -> entry.value.asProtoModel() }, + artifactsMap = scopedArtifacts().mapValues { entry -> entry.value.asProtoModel() }, ) fun Library.asProtoModel() = @@ -114,6 +115,7 @@ fun ProjectInfo.asProtoModel() = ProjectInfo( buildId = this.buildId, projectPath = projectPath, + isTestFixtures = isTestFixtures, ) fun LibraryInfo.asProtoModel() = @@ -206,7 +208,10 @@ fun UnresolvedDependency.asProtoModel() = cause = this.cause, ) -fun SourceSetContainer.asProtoModel() = SourceSetContainer(sourceProvider = this.sourceProvider?.asProtoModel()) +fun SourceSetContainer.asProtoModel() = + SourceSetContainer( + sourceProvidersMap = scopedSourceProviders().mapValues { entry -> entry.value.asProtoModel() }, + ) fun SourceProvider.asProtoModel() = SourceProvider( @@ -242,6 +247,7 @@ fun Variant.asProtoModel( androidDsl = androidDsl, versions = versions, ), + artifactSourcesMap = basicAndroidProject.variantArtifactSources(this), ) fun AndroidArtifact.asProtoModel( diff --git a/tooling/impl/src/main/java/dev/mutwakil/androidide/tooling/impl/serial/ScopedComponents.kt b/tooling/impl/src/main/java/dev/mutwakil/androidide/tooling/impl/serial/ScopedComponents.kt new file mode 100644 index 0000000000..a839f48ca7 --- /dev/null +++ b/tooling/impl/src/main/java/dev/mutwakil/androidide/tooling/impl/serial/ScopedComponents.kt @@ -0,0 +1,145 @@ +package dev.mutwakil.androidide.tooling.impl.serial + +import com.android.builder.model.v2.ide.AbstractArtifact +import com.android.builder.model.v2.ide.ArtifactDependencies +import com.android.builder.model.v2.ide.BasicArtifact +import com.android.builder.model.v2.ide.BasicVariant +import com.android.builder.model.v2.ide.SourceProvider +import com.android.builder.model.v2.ide.SourceSetContainer +import com.android.builder.model.v2.ide.Variant +import com.android.builder.model.v2.models.BasicAndroidProject +import com.android.builder.model.v2.models.VariantDependencies +import dev.mutwakil.androidide.project.AndroidModels +import dev.mutwakil.androidide.project.VariantArtifactSources +import dev.mutwakil.androidide.projects.models.ArtifactScope +import org.gradle.tooling.model.UnsupportedMethodException + +// The map keys AGP's model gives the components the single-artifact getters return. +private val UNIT_TEST_TYPE = ArtifactScope.UNIT_TEST.type +private val ANDROID_TEST_TYPE = ArtifactScope.ANDROID_TEST.type + +/** One source set's or variant's components as AGP's model reports them, before they are keyed by scope. */ +private class ComponentsByType( + val main: T?, + val testFixtures: T?, + val hostTests: Map, + val deviceTests: Map, +) { + fun keyedByScope(): Map = + buildMap { + main?.let { put(ArtifactScope.Main.key, it) } + testFixtures?.let { put(ArtifactScope.TestFixtures.key, it) } + hostTests.forEach { (type, component) -> put(ArtifactScope.HostTest(type).key, component) } + deviceTests.forEach { (type, component) -> put(ArtifactScope.DeviceTest(type).key, component) } + } +} + +/** + * AGP's per-type test map, or null on AGP 7.3 to 8.3, which predate it: the Tooling API proxies a + * missing model method by throwing [UnsupportedMethodException]. + */ +private inline fun testMap(get: () -> Map): Map? = + try { + get() + } catch (e: UnsupportedMethodException) { + null + } + +/** The single pre-map test component, as a one-entry map under [type]. */ +private fun legacyTests( + type: String, + component: T?, +): Map = component?.let { mapOf(type to it) }.orEmpty() + +/** This container's source providers by scope key. */ +fun SourceSetContainer.scopedSourceProviders(): Map = + ComponentsByType( + main = sourceProvider, + testFixtures = testFixturesSourceProvider, + hostTests = + testMap { hostTestSourceProviders } + ?: legacyTests(UNIT_TEST_TYPE, @Suppress("DEPRECATION") unitTestSourceProvider), + deviceTests = + testMap { deviceTestSourceProviders } + ?: legacyTests(ANDROID_TEST_TYPE, @Suppress("DEPRECATION") androidTestSourceProvider), + ).keyedByScope() + +/** The dependencies of each of the variant's components by scope key. */ +fun VariantDependencies.scopedArtifacts(): Map = + ComponentsByType( + main = mainArtifact, + testFixtures = testFixturesArtifact, + hostTests = testMap { hostTestArtifacts } ?: legacyTests(UNIT_TEST_TYPE, @Suppress("DEPRECATION") unitTestArtifact), + deviceTests = + testMap { deviceTestArtifacts } + ?: legacyTests(ANDROID_TEST_TYPE, @Suppress("DEPRECATION") androidTestArtifact), + ).keyedByScope() + +private fun Variant.scopedArtifacts(): Map = + ComponentsByType( + main = mainArtifact, + testFixtures = testFixturesArtifact, + hostTests = testMap { hostTestArtifacts } ?: legacyTests(UNIT_TEST_TYPE, @Suppress("DEPRECATION") unitTestArtifact), + deviceTests = + testMap { deviceTestArtifacts } + ?: legacyTests(ANDROID_TEST_TYPE, @Suppress("DEPRECATION") androidTestArtifact), + ).keyedByScope() + +private fun BasicVariant.scopedArtifacts(): Map = + ComponentsByType( + main = mainArtifact, + testFixtures = testFixturesArtifact, + hostTests = testMap { hostTestArtifacts } ?: legacyTests(UNIT_TEST_TYPE, @Suppress("DEPRECATION") unitTestArtifact), + deviceTests = + testMap { deviceTestArtifacts } + ?: legacyTests(ANDROID_TEST_TYPE, @Suppress("DEPRECATION") androidTestArtifact), + ).keyedByScope() + +/** + * Per scope key, the source providers AGP layers over that scope's default source set for the + * variant named [variantName], in the order AGP applies them: the build type, each product flavor, + * the multi-flavor provider and the variant's own provider. Empty when the basic model does not + * list the variant. + */ +private fun BasicAndroidProject.variantLayers(variantName: String): Map> { + val variant = variants.firstOrNull { it.name == variantName } ?: return emptyMap() + val buildType = buildTypeSourceSets.firstOrNull { it.sourceProvider?.name == variant.buildType } + val flavors = variant.productFlavors.mapNotNull { flavor -> productFlavorSourceSets.firstOrNull { it.sourceProvider?.name == flavor } } + val containerLayers = (listOfNotNull(buildType) + flavors).map { it.scopedSourceProviders() } + val artifacts = variant.scopedArtifacts() + + return (containerLayers.flatMap { it.keys } + artifacts.keys).distinct().associateWith { key -> + containerLayers.mapNotNull { it[key] } + + listOfNotNull(artifacts[key]?.multiFlavorSourceProvider, artifacts[key]?.variantSourceProvider) + } +} + +/** + * The Java and Kotlin dirs of every source set this module has, whichever variant is selected: each + * component of the default config, of every build type and flavor, and every variant's own and + * multi-flavor layers. + */ +fun BasicAndroidProject.allSourceSetDirs(): List { + val containers = listOfNotNull(mainSourceSet) + buildTypeSourceSets + productFlavorSourceSets + val providers = + containers.flatMap { it.scopedSourceProviders().values } + + variants.flatMap { variant -> + variant.scopedArtifacts().values.flatMap { listOfNotNull(it.multiFlavorSourceProvider, it.variantSourceProvider) } + } + return providers + .flatMap { it.javaDirectories + it.kotlinDirectories } + .map { it.absolutePath } + .distinct() +} + +/** Per scope key, the sources each of [variant]'s components adds over its default source set. */ +fun BasicAndroidProject.variantArtifactSources(variant: Variant): Map { + val generated = variant.scopedArtifacts().mapValues { (_, artifact) -> artifact.generatedSourceFolders.map { it.absolutePath } } + val layers = variantLayers(variant.name) + return (generated.keys + layers.keys).associateWith { key -> + VariantArtifactSources( + variantSourceProvidersList = layers[key].orEmpty().map { it.asProtoModel() }, + generatedSourceFolderPathsList = generated[key].orEmpty(), + ) + } +} \ No newline at end of file diff --git a/utilities/shared/src/main/java/dev/mutwakil/androidide/memprof/Memprof.kt b/utilities/shared/src/main/java/dev/mutwakil/androidide/memprof/Memprof.kt index e3ef65328c..9bcaea73f2 100644 --- a/utilities/shared/src/main/java/dev/mutwakil/androidide/memprof/Memprof.kt +++ b/utilities/shared/src/main/java/dev/mutwakil/androidide/memprof/Memprof.kt @@ -54,6 +54,17 @@ object Memprof { marker: String, ): MemprofSpan = sink?.beginPhase(title, marker) ?: MemprofSpan.None + /** + * Starts a section whose start and end happen in different callbacks. + * + * The caller owns the returned span as with [beginPhase]; use [section] whenever the work fits one + * block. + */ + fun beginSection( + name: String, + detail: String? = null, + ): MemprofSpan = sink?.beginSection(name, detail) ?: MemprofSpan.None + /** Records that the instant named [marker] was reached. */ fun mark(marker: String) { sink?.mark(marker) @@ -83,4 +94,4 @@ object Memprof { span.abandon() } } -} +} \ No newline at end of file diff --git a/utilities/shared/src/main/java/dev/mutwakil/androidide/memprof/MemprofLines.kt b/utilities/shared/src/main/java/dev/mutwakil/androidide/memprof/MemprofLines.kt index 163acc488d..88c3f0f274 100644 --- a/utilities/shared/src/main/java/dev/mutwakil/androidide/memprof/MemprofLines.kt +++ b/utilities/shared/src/main/java/dev/mutwakil/androidide/memprof/MemprofLines.kt @@ -51,14 +51,15 @@ object MemprofLines { nowMs: Long, durationMs: Long, allocBytes: Long, - ): String = "MEMPROF|phase_end|$nowMs|marker=$marker|durationMs=$durationMs|allocBytes=$allocBytes" + ): String = "MEMPROF|phase_end|$nowMs|marker=$marker|durationMs=$durationMs|procAllocBytes=$allocBytes" /** * The line one finished section instance emits, read by `alloc_budget.py`'s per-file report. * - * The field order and names (`allocBytes`, `durationMs`, `path`) after the timestamp are fixed + * The field order and names (`procAllocBytes`, `durationMs`, `path`) after the timestamp are fixed * by that script's `MEMPROF\|file\|(\d+)\|(.*)` regex and its k=v parsing; changing them breaks - * the harness silently rather than with an error, since unknown keys are ignored. + * the harness silently rather than with an error, since unknown keys are ignored. The [details] the + * section put follow the fixed fields, where the script's k=v parsing picks them up. */ fun fileLine( nowMs: Long, @@ -67,7 +68,10 @@ object MemprofLines { path: String?, name: String, completed: Boolean, - ): String = "MEMPROF|file|$nowMs|allocBytes=$allocBytes|durationMs=$durationMs|path=$path|name=$name|completed=$completed" + details: Map, + ): String = + "MEMPROF|file|$nowMs|procAllocBytes=$allocBytes|durationMs=$durationMs|path=$path|name=$name|completed=$completed" + + detailsSuffix(details) private fun detailsSuffix(details: Map): String = details.entries.joinToString("") { (key, value) -> "|$key=$value" } -} +} \ No newline at end of file diff --git a/utilities/shared/src/main/java/dev/mutwakil/androidide/memprof/MemprofReport.kt b/utilities/shared/src/main/java/dev/mutwakil/androidide/memprof/MemprofReport.kt index 1c85e547c6..56a361ae1d 100644 --- a/utilities/shared/src/main/java/dev/mutwakil/androidide/memprof/MemprofReport.kt +++ b/utilities/shared/src/main/java/dev/mutwakil/androidide/memprof/MemprofReport.kt @@ -131,7 +131,7 @@ class MemprofReport( } val header = - listOf("Phase", "Start", "Time", "Allocated", "Alloc - freed", "Peak heap", "Blocking GCs", "") + listOf("Phase", "Start", "Time", "Proc alloc", "Proc alloc - freed", "Peak heap", "Blocking GCs", "") appendTable(listOf(header) + phases.map { it.row(nowMs, counters) }) } @@ -142,7 +142,7 @@ class MemprofReport( appendLine() appendLine("Repeated work") - val header = listOf("Work", "Count", "Total time", "Allocated", "Largest single instance") + val header = listOf("Work", "Count", "Total time", "Proc alloc", "Largest single instance") appendTable(listOf(header) + repeatedWork.values.map { it.row() }) } @@ -245,4 +245,4 @@ class MemprofReport( fun seconds(ms: Long): String = "%.1f s".format(Locale.US, ms / 1000.0) } -} +} \ No newline at end of file diff --git a/utilities/shared/src/main/java/dev/mutwakil/androidide/utils/DocumentUtils.java b/utilities/shared/src/main/java/dev/mutwakil/androidide/utils/DocumentUtils.java index c56f976d0a..fa41299ff7 100644 --- a/utilities/shared/src/main/java/dev/mutwakil/androidide/utils/DocumentUtils.java +++ b/utilities/shared/src/main/java/dev/mutwakil/androidide/utils/DocumentUtils.java @@ -27,36 +27,44 @@ */ public class DocumentUtils { - public static boolean isJavaFile(Path file) { - final var name = PathsKt.getName(file); - final var extension = PathsKt.getExtension(file); - - return extension.equals("java") - && Files.exists(file) - && !Files.isDirectory(file) - && !name.equals("module-info.java") - && !name.equals("package-info.java"); - } - - public static boolean isKotlinFile(Path file) { - if (file == null) { - return false; - } - final var extension = PathsKt.getExtension(file); - return (extension.equals("kt") || extension.equals("kts")) - && Files.exists(file) - && !Files.isDirectory(file); - } - - public static boolean isXmlFile(Path file) { - return PathsKt.getExtension(file).equals("xml") && Files.exists(file) && !Files.isDirectory(file); - } - - public static boolean isSameFile(Path first, Path second) { - try { - return Files.isSameFile(first, second); - } catch (IOException e) { - return false; - } - } -} + /** + * Whether {@code file} has a Kotlin source extension ({@code .kt} or {@code .kts}), without touching the filesystem. + * + *

+ * Unlike {@link #isKotlinFile(Path)}, this holds for a path that no longer exists. + */ + public static boolean hasKotlinExtension(Path file) { + if (file == null) { + return false; + } + final var extension = PathsKt.getExtension(file); + return extension.equals("kt") || extension.equals("kts"); + } + + public static boolean isJavaFile(Path file) { + final var name = PathsKt.getName(file); + final var extension = PathsKt.getExtension(file); + + return extension.equals("java") + && Files.exists(file) + && !Files.isDirectory(file) + && !name.equals("module-info.java") + && !name.equals("package-info.java"); + } + + public static boolean isKotlinFile(Path file) { + return hasKotlinExtension(file) && Files.exists(file) && !Files.isDirectory(file); + } + + public static boolean isSameFile(Path first, Path second) { + try { + return Files.isSameFile(first, second); + } catch (IOException e) { + return false; + } + } + + public static boolean isXmlFile(Path file) { + return PathsKt.getExtension(file).equals("xml") && Files.exists(file) && !Files.isDirectory(file); + } +} \ No newline at end of file