Class WorkspaceIndex
FileBloomEntry per XML/grammar
file, enabling ultra-fast cross-file reference lookup with zero repeated file I/O.
Purpose: Answers "which files reference grammar X?" and "how many?" entirely from memory, powering:
- UC19 — "Find References" on
types.xsd: lists every XML file that references it, with exactLocations. - UC14–UC18 — Rename grammar file: finds all impacted files and computes
a
WorkspaceEditto update their references. - Code lens — "N references" badge on
schema.xsd: counts references instantly without reading any file.
One-read-per-file principle: Each file is read exactly once, at indexing
time (triggered by startup scan or didChangeWatchedFiles). Reading is
done via a streaming IndexScanner
— only the reader's internal buffer (~8 KB) is allocated, never the full file content,
so even multi-megabyte XSD files are indexed without OOM risk.
An optional per-extension character limit can be configured via
xml.workspaceIndex.headLimits to cap scan time on very large files.
The result is stored in a FileBloomEntry
containing two complementary structures:
- A
BloomFilterwith all token names — O(1) probabilistic lookup, used as a fast pre-filter to find rename/reference candidates. - A confirmed
GrammarReferencelist — exact line/column positions of every grammar reference in the head, used for zero-I/O code lens counts and for building LSP Locations/TextEdits without re-reading files.
indexFile(java.nio.file.Path) atomically replaces its entry, so the cache is always
up-to-date without any explicit invalidation step.
Memory:
- BloomFilter: ~12 KB per 10,000 files (1.2 bytes per file)
- GrammarReference list: ~100–200 bytes per file (1–3 refs × ~80 bytes each)
- Total overhead for 10,000 files: approximately 1–2 MB
- Peak per-file transient allocation: ~8 KB (reader buffer) regardless of file size.
Thread safety: Uses ConcurrentHashMap
for the entry map and a monotonic sequence number per path to handle concurrent
re-indexing of the same file without locks.
- See Also:
-
Nested Class Summary
Nested ClassesModifier and TypeClassDescriptionstatic interfaceListener notified as files are indexed during ascanDirectory(java.nio.file.Path)call. -
Constructor Summary
Constructors -
Method Summary
Modifier and TypeMethodDescriptionvoidclear()Drops all Bloom filter entries, effectively disabling reference lookup.intcountFilesWithRefValue(String value, boolean excludeGrammars) Counts indexed files (excluding grammar files when requested) that contain at least oneGrammarReferencewhoseGrammarReference.value()equalsvalue.intcountReferencesTo(Path targetPath, boolean excludeGrammars) Counts grammar references that resolve totargetPath, using only cached data — zero file I/O.findReferencingFiles(String name) Returns URIs of all indexed files whose Bloom filter may containname.findReferencingFiles(String name, boolean includePartiallyIndexed) Returns URIs of indexed files whose Bloom filter may containname.getReferencesTo(Path targetPath) Returns, for each indexed file that has confirmed references totargetPath, the list of matchingGrammarReferenceobjects.getReferencesWithValue(String value, boolean excludeGrammars) Returns, for each indexed file whose cached refs contain at least one entry withGrammarReference.value()equal tovalue, the list of matching references.Returns a future that completes when the initial workspace scan finishes.booleanBuilds or refreshes the Bloom filter entry for a single file using a single streaming pass — no file content is ever fully loaded into memory.booleanReturnstruewhen the initial workspace scan has completed and all indexed files are available for reference lookup.voidMarks the initial workspace scan as completed.voidremoveFile(Path path) Removes a file's Bloom entry from the index.voidscanDirectory(Path root) Recursively indexes all XML-family files underroot.voidscanDirectory(Path root, WorkspaceIndex.IndexProgressListener listener) Recursively indexes all XML-family files underroot, reporting progress.voidscanDirectory(Path root, WorkspaceIndex.IndexProgressListener listener, Set<String> excludedDirs) Recursively indexes all XML-family files underroot, reporting progress and skipping the specified directories.voidscanDirectory(Path root, WorkspaceIndex.IndexProgressListener listener, Set<String> excludedDirs, BooleanSupplier isCanceled) voidsetContributors(List<IGrammarReferenceContributor> contributors) voidsetFileScannerContributors(List<IIndexFileScannerContributor> fileScannerContributors) voidsetHeadLimits(Map<String, String> raw) Sets the per-file read limits used during indexing from a raw glob-pattern map.intsize()Returns the number of files currently indexed.
-
Constructor Details
-
WorkspaceIndex
public WorkspaceIndex()
-
-
Method Details
-
setContributors
-
setFileScannerContributors
-
getContributors
-
getFileScannerContributors
-
setHeadLimits
Sets the per-file read limits used during indexing from a raw glob-pattern map.Keys are glob patterns (e.g.
"**/*.xsd","**/vendor/**"). The longest matching pattern wins. Values are size strings parsed byXMLWorkspaceIndexSettings.parseSizeLimit(java.lang.String).Files larger than their matched limit are marked as partially indexed and always returned as candidates, avoiding false negatives while bounding the transient heap allocation per file.
Use case: Called from
WorkspaceIndexPluginwhenever thexml.workspaceIndex.headLimitssetting changes.- Parameters:
raw- glob-pattern→size-string map;nullclears all limits.
-
indexFile
Builds or refreshes the Bloom filter entry for a single file using a single streaming pass — no file content is ever fully loaded into memory.Use case: The file watcher fires a
CreatedorChangedevent fororder.xml. The plugin callsindexFile(path)so that subsequentfindReferencingFiles(String)calls include this file if it referencesschema.xsd.An optional per-extension character limit can be configured via
xml.workspaceIndex.headLimits. Files that exceed the limit are added topartiallyIndexedand always returned as candidates, avoiding false negatives while bounding scan time. When no limits are configured (the default), the full file is scanned without memory concerns — peak heap per file is the reader's internal buffer (~8 KB), not the full file content.- Parameters:
path- the file to index.- Returns:
trueif the file contains at least one grammar reference (the index was meaningfully updated);falseif the file has no grammar references and no code lens refresh is necessary.- Throws:
IOException- if the file cannot be read.
-
removeFile
Removes a file's Bloom entry from the index.Use case: The user deletes
order.xmlfrom the workspace. The file watcher fires aDeletedevent; the plugin callsremoveFile(path)so the file is no longer returned byfindReferencingFiles(java.lang.String). The deletion is always processed even when the index is otherwise disabled (to prevent stale entries).- Parameters:
path- the file to remove.
-
scanDirectory
Recursively indexes all XML-family files underroot.Use case: Called once at startup to populate the index for the entire workspace root (e.g.
/home/user/my-project).- Parameters:
root- the directory to scan.- Throws:
IOException- if the directory cannot be walked.
-
scanDirectory
public void scanDirectory(Path root, WorkspaceIndex.IndexProgressListener listener) throws IOException Recursively indexes all XML-family files underroot, reporting progress.Use case: Called by
WorkspaceIndexPluginduring the async workspace scan triggered byinitialized. Thelistenerdrives the LSP progress notification (e.g. "Indexed 42 / 200 files — 21%").- Parameters:
root- the directory to scan.listener- optional progress listener;nullfor no progress.- Throws:
IOException- if the directory cannot be walked.
-
scanDirectory
public void scanDirectory(Path root, WorkspaceIndex.IndexProgressListener listener, Set<String> excludedDirs) throws IOException Recursively indexes all XML-family files underroot, reporting progress and skipping the specified directories.Single-pass approach: collects all XML file paths in one directory traversal, then indexes them. This avoids the two-pass overhead of an earlier count-then-index approach while still allowing accurate progress percentages.
Directory exclusions: any directory whose simple name exactly matches an entry in
excludedDirsis skipped entirely (along with all descendants). Typical exclusions:.git,node_modules,target.- Parameters:
root- the directory to scan.listener- optional progress listener;nullfor no progress.excludedDirs- directory names to skip;nullmeans skip nothing.- Throws:
IOException- if the directory cannot be walked.
-
scanDirectory
public void scanDirectory(Path root, WorkspaceIndex.IndexProgressListener listener, Set<String> excludedDirs, BooleanSupplier isCanceled) throws IOException - Throws:
IOException
-
findReferencingFiles
Returns URIs of all indexed files whose Bloom filter may containname.Use case: Before renaming
schema.xsd, the rename support callsfindReferencingFiles("schema.xsd")to get the candidate set (e.g.[order.xml, invoice.xml]). Each candidate is then opened and scanned withGrammarReferenceLocatorfor exact position confirmation.Partially indexed files (those that hit a configured head limit) are always included as candidates regardless of their Bloom filter result, to avoid false negatives. Use
findReferencingFiles(String, boolean)withfalsewhen this conservative behaviour is not needed (e.g. for catalog identifier lookups where references always appear in the first 64 KB).- Parameters:
name- a grammar filename, symbol name, or any string to look up.- Returns:
- list of file URIs that may reference
name(may include false positives).
-
findReferencingFiles
Returns URIs of indexed files whose Bloom filter may containname.- Parameters:
name- a grammar filename, catalog identifier, or any string to look up.includePartiallyIndexed- whentrue, files larger than 64 KB are always included regardless of their Bloom filter result (conservative correctness for rename). Whenfalse, only Bloom filter hits are returned — safe for queries where the target always appears in the first 64 KB (e.g. namespace URI declarations, catalog systemId/publicId references).- Returns:
- list of file URIs that may reference
name(may include false positives).
-
countReferencesTo
Counts grammar references that resolve totargetPath, using only cached data — zero file I/O.Use case: The user opens
types.xsd. The code lens provider calls this method to show "3 references" without reading any file.order.xmlcontributes 1 (itsxml-modelhref), andinvoice.xmlcontributes 2 (bothxml-modelandxsi:noNamespaceSchemaLocationpoint totypes.xsd).Each
GrammarReferencein each indexed file is resolved relative to that file's directory. Only those whose resolved path equalstargetPathare counted. A single file may contribute more than one count if it references the grammar multiple times.- Parameters:
targetPath- absolute path of the grammar file.excludeGrammars- whentrue, grammar files (XSD, DTD…) are excluded from the count — useful for catalog lenses that count only XML instance documents.- Returns:
- total number of matching reference occurrences across all indexed files.
-
getReferencesWithValue
public Map<String,List<GrammarReference>> getReferencesWithValue(String value, boolean excludeGrammars) Returns, for each indexed file whose cached refs contain at least one entry withGrammarReference.value()equal tovalue, the list of matching references. Zero file I/O.Use case: The user clicks the "2 references" lens on the catalog entry
<uri name="http://example.com/ns" uri="schema.xsd"/>incatalog.xml. The catalog reference participant callsgetReferencesWithValue("http://example.com/ns", true)to retrieve only the XML instance files that contain that exact namespace URI. Locations are built directly from cached line/column positions — no files are read.Unlike
getReferencesTo(Path), which resolves ref values as file paths, this method matches by exact string equality — suitable for namespace URIs, systemIds, and publicIds that are not paths.- Parameters:
value- the identifier to match againstGrammarReference.value().excludeGrammars- whentrue, grammar files (XSD, DTD…) are excluded.- Returns:
- map of fileUri → matching refs; empty if none found.
-
getReferencesTo
Returns, for each indexed file that has confirmed references totargetPath, the list of matchingGrammarReferenceobjects. Zero file I/O — all data comes from the in-memory index.Use case: The user invokes "Find All References" on
schema.xsd.WorkspaceIndexReferenceParticipantcallsgetReferencesTo(schemaXsdPath)to get a map such as:"file:///project/order.xml" → [XML_MODEL_HREF line=0,col=17-27 "schema.xsd"] "file:///project/invoice.xml" → [NO_NS_SCHEMA_LOCATION line=2,col=43-53 "schema.xsd"]
No files are opened — eachGrammarReferencein the map already carries pre-computed line/column positions from indexing time.Each
GrammarReference.value()is resolved relative to the containing file's directory and compared totargetPath. Values that cannot be parsed as a path (e.g. absolute URIs) are silently skipped.- Parameters:
targetPath- absolute path of the grammar file.- Returns:
- map of fileUri → matching refs; empty if none found.
-
countFilesWithRefValue
Counts indexed files (excluding grammar files when requested) that contain at least oneGrammarReferencewhoseGrammarReference.value()equalsvalue. Zero file I/O.Use case: A catalog entry
<system systemId="http://example.org/dtd" uri="book.dtd"/>hassystemIdas the catalog identifier. The catalog code lens callscountFilesWithRefValue("http://example.org/dtd", true)to show "2 references" — the number of XML instance files that contain a reference with that exact value (e.g. aDOCTYPEdeclaration using that system ID).Each file is counted at most once, even if it contains multiple refs with the same value.
- Parameters:
value- the identifier to match againstGrammarReference.value().excludeGrammars- whentrue, grammar files (XSD, DTD…) are excluded.- Returns:
- number of matching files.
-
size
public int size()Returns the number of files currently indexed.Use case: Logged after a workspace scan completes — "WorkspaceIndex: indexed 342 files in 1 230 ms".
-
isScanCompleted
public boolean isScanCompleted()Returnstruewhen the initial workspace scan has completed and all indexed files are available for reference lookup.Use case: The catalog diagnostics participant waits for the scan to complete before reporting unused entries, to avoid false positives when the index is still being populated.
-
markScanCompleted
public void markScanCompleted()Marks the initial workspace scan as completed.Called by
WorkspaceIndexPluginonce the async scan finishes. After this point,isScanCompleted()returnstrueand diagnostics participants may report unused catalog entries. -
getScanCompletedFuture
Returns a future that completes when the initial workspace scan finishes. Participants that depend on the index (e.g. reference search) can chain on this future so they naturally wait without blocking a thread. -
clear
public void clear()Drops all Bloom filter entries, effectively disabling reference lookup.Use case: The user sets
xml.workspaceIndex.enabled = falsein their VS Code settings.WorkspaceIndexPlugin.doSave(org.eclipse.lemminx.services.extensions.save.ISaveContext)callsclear()so no stale candidates are returned until the index is re-enabled and re-scanned.
-