Class WorkspaceIndex

java.lang.Object
org.eclipse.lemminx.extensions.index.WorkspaceIndex

public class WorkspaceIndex extends Object
Workspace-level index that maintains one 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 exact Locations.
  • UC14–UC18 — Rename grammar file: finds all impacted files and computes a WorkspaceEdit to 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:

  1. A BloomFilter with all token names — O(1) probabilistic lookup, used as a fast pre-filter to find rename/reference candidates.
  2. A confirmed GrammarReference list — 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.
After indexing, files are never re-read for code lens computation. When a file changes, 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:
  • Constructor Details

    • WorkspaceIndex

      public WorkspaceIndex()
  • Method Details

    • setContributors

      public void setContributors(List<IGrammarReferenceContributor> contributors)
    • setFileScannerContributors

      public void setFileScannerContributors(List<IIndexFileScannerContributor> fileScannerContributors)
    • getContributors

      public List<IGrammarReferenceContributor> getContributors()
    • getFileScannerContributors

      public List<IIndexFileScannerContributor> getFileScannerContributors()
    • setHeadLimits

      public void setHeadLimits(Map<String,String> raw)
      Sets the per-file read limits used during indexing from a raw glob-pattern map.

      Keys are glob patterns (e.g. "**&#47;*.xsd", "**&#47;vendor&#47;**"). The longest matching pattern wins. Values are size strings parsed by XMLWorkspaceIndexSettings.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 WorkspaceIndexPlugin whenever the xml.workspaceIndex.headLimits setting changes.

      Parameters:
      raw - glob-pattern→size-string map; null clears all limits.
    • indexFile

      public boolean indexFile(Path path) throws IOException
      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 Created or Changed event for order.xml. The plugin calls indexFile(path) so that subsequent findReferencingFiles(String) calls include this file if it references schema.xsd.

      An optional per-extension character limit can be configured via xml.workspaceIndex.headLimits. Files that exceed the limit are added to partiallyIndexed and 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:
      true if the file contains at least one grammar reference (the index was meaningfully updated); false if the file has no grammar references and no code lens refresh is necessary.
      Throws:
      IOException - if the file cannot be read.
    • removeFile

      public void removeFile(Path path)
      Removes a file's Bloom entry from the index.

      Use case: The user deletes order.xml from the workspace. The file watcher fires a Deleted event; the plugin calls removeFile(path) so the file is no longer returned by findReferencingFiles(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

      public void scanDirectory(Path root) throws IOException
      Recursively indexes all XML-family files under root.

      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 under root, reporting progress.

      Use case: Called by WorkspaceIndexPlugin during the async workspace scan triggered by initialized. The listener drives the LSP progress notification (e.g. "Indexed 42 / 200 files — 21%").

      Parameters:
      root - the directory to scan.
      listener - optional progress listener; null for 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 under root, 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 excludedDirs is skipped entirely (along with all descendants). Typical exclusions: .git, node_modules, target.

      Parameters:
      root - the directory to scan.
      listener - optional progress listener; null for no progress.
      excludedDirs - directory names to skip; null means 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

      public List<String> findReferencingFiles(String name)
      Returns URIs of all indexed files whose Bloom filter may contain name.

      Use case: Before renaming schema.xsd, the rename support calls findReferencingFiles("schema.xsd") to get the candidate set (e.g. [order.xml, invoice.xml]). Each candidate is then opened and scanned with GrammarReferenceLocator for 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) with false when 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

      public List<String> findReferencingFiles(String name, boolean includePartiallyIndexed)
      Returns URIs of indexed files whose Bloom filter may contain name.
      Parameters:
      name - a grammar filename, catalog identifier, or any string to look up.
      includePartiallyIndexed - when true, files larger than 64 KB are always included regardless of their Bloom filter result (conservative correctness for rename). When false, 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

      public int countReferencesTo(Path targetPath, boolean excludeGrammars)
      Counts grammar references that resolve to targetPath, 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.xml contributes 1 (its xml-model href), and invoice.xml contributes 2 (both xml-model and xsi:noNamespaceSchemaLocation point to types.xsd).

      Each GrammarReference in each indexed file is resolved relative to that file's directory. Only those whose resolved path equals targetPath are 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 - when true, 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 with GrammarReference.value() equal to value, 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"/> in catalog.xml. The catalog reference participant calls getReferencesWithValue("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 against GrammarReference.value().
      excludeGrammars - when true, grammar files (XSD, DTD…) are excluded.
      Returns:
      map of fileUri → matching refs; empty if none found.
    • getReferencesTo

      public Map<String,List<GrammarReference>> getReferencesTo(Path targetPath)
      Returns, for each indexed file that has confirmed references to targetPath, the list of matching GrammarReference objects. Zero file I/O — all data comes from the in-memory index.

      Use case: The user invokes "Find All References" on schema.xsd. WorkspaceIndexReferenceParticipant calls getReferencesTo(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 — each GrammarReference in 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 to targetPath. 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

      public int countFilesWithRefValue(String value, boolean excludeGrammars)
      Counts indexed files (excluding grammar files when requested) that contain at least one GrammarReference whose GrammarReference.value() equals value. Zero file I/O.

      Use case: A catalog entry <system systemId="http://example.org/dtd" uri="book.dtd"/> has systemId as the catalog identifier. The catalog code lens calls countFilesWithRefValue("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. a DOCTYPE declaration 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 against GrammarReference.value().
      excludeGrammars - when true, 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()
      Returns true when 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 WorkspaceIndexPlugin once the async scan finishes. After this point, isScanCompleted() returns true and diagnostics participants may report unused catalog entries.

    • getScanCompletedFuture

      public CompletableFuture<Void> 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 = false in their VS Code settings. WorkspaceIndexPlugin.doSave(org.eclipse.lemminx.services.extensions.save.ISaveContext) calls clear() so no stale candidates are returned until the index is re-enabled and re-scanned.