PHPantom — Indexing¶
This document covers how PHPantom discovers, parses, and caches class definitions across the workspace. The goal is to remain fast and lightweight by default while offering progressively richer modes for users who want exhaustive workspace intelligence.
Items are ordered by impact (descending), then complexity (ascending) within the same impact tier.
| Label | Scale |
|---|---|
| Impact | Critical, High, Medium-High, Medium, Low-Medium, Low |
| Complexity | Low (mechanical/boilerplate, no design decisions), Medium (self-contained, follows an existing pattern), Medium-High (spans modules, some new design), High (shared/core subsystem, correctness or performance tradeoffs), Very High (cross-cutting architecture, wide blast radius) |
Current state¶
PHPantom has three byte-level scanners (no AST) for early-stage file discovery:
- composer-classmap — parses Composer's
autoload_classmap.phpinto an in-memoryHashMap<String, PathBuf>. - PSR-4 scanner (
find_classes) — walks PSR-4 directories fromcomposer.jsonand extracts class FQNs with namespace compliance filtering. - full-scan (
find_symbols) — walks files and extracts classes, standalone functions,define()constants, and top-levelconstdeclarations in a single pass.
These scanners serve three scenarios at startup:
| Scenario | Class discovery | Function & constant discovery |
|---|---|---|
| Composer project (classmap complete) | composer-classmap | autoload_files.php byte-level scan + lazy parse |
| Composer project (classmap missing/incomplete) | PSR-4 scanner + vendor packages | autoload_files.php byte-level scan + lazy parse |
No composer.json |
full-scan on all workspace files | full-scan on all workspace files |
Monorepo (no root composer.json, subprojects found) |
Per-subproject: composer-classmap or PSR-4 + vendor packages. Loose files: full-scan with skip set | Per-subproject: autoload_files.php byte-level scan + lazy parse. Loose files: full-scan |
The "no composer.json" path is fully lightweight: find_symbols
populates classmap, autoload_function_index, and
autoload_constant_index in one pass, and lazy update_ast on first
access provides complete FunctionInfo/DefineInfo. All directory
walkers (full-scan, PSR-4 scanner, vendor package scanner, and
go-to-implementation file collector) use the ignore crate for
gitignore-aware traversal instead of hardcoded directory name
filtering. Hidden directories are skipped automatically, and so are the
laravel-ide-helper files. Paths listed under [indexing] include are
scanned on top of that walk, bypassing all three, for first-party PHP
in a dotted directory and for generated files that are gitignored as
build artefacts. An included path inside the workspace is project code;
one outside it is registered like a vendor directory, so it resolves
but is never analysed or edited.
The monorepo path activates when there is no root composer.json but
discover_subproject_roots finds subdirectories with their own
composer.json files. Each subproject is processed through the full
Composer pipeline (PSR-4, classmap, vendor packages, autoload files)
and results are merged into the shared backend state. Loose PHP files
outside subproject trees are picked up by the full-scan walker with a
skip set that prevents double-scanning subproject directories. See
the ARCHITECTURE.md Composer Integration section for full details.
Find References parses files in parallel via std::thread::scope.
Go-to-Implementation walks classmap files sequentially.
Strategy modes¶
Four indexing strategies, selectable via .phpantom.toml:
[indexing]
# "full" (default) - background-parse all project files for rich intelligence
# "composer" - merged classmap + self-scan
# "self" - always self-scan, ignore composer classmap
# "none" - no proactive scanning
strategy = "full"
"full" (default)¶
Background-parse every user PHP file in the workspace after discovery. Uses Composer data to guide file discovery when available, falls back to scanning all PHP files in the workspace when it is not. Populates the uri_classes_index, symbol_maps, the cross-file reference index, and all derived indices. Enables workspace symbols, fast find-references without on-demand scanning, and rich hover on completion items. Vendor files are not background-parsed; they are still resolved lazily on demand. Memory usage grows proportionally to project size. This is the zero-config experience.
"composer"¶
Merged classmap + self-scan. Load Composer's classmap (if it exists) as a skip set, then self-scan all PSR-4 and vendor directories for anything the classmap missed. Whatever the classmap already covers is a free performance win; whatever it's missing, we find ourselves. No completeness heuristic needed.
"self"¶
Always build the classmap ourselves: scan every PHP file under the
workspace root, ignoring autoload_classmap.php and the PSR-4
mappings. Vendor packages are still scanned via installed.json.
For users who prefer PHPantom's own scanner or who are actively
editing composer.json dependencies.
"none"¶
No proactive file scanning. Still uses Composer's classmap if present,
still resolves classes on demand when the user triggers completion or
hover, still has embedded stubs. The only difference from "composer"
is that it never self-scans to fill gaps.
X2. Parallel file processing¶
Goal: Speed up workspace-wide operations (find references, go-to-implementation, self-scan, diagnostics) by processing files in parallel with priority awareness.
All prerequisites (RwLock, Arc<String>, Arc<SymbolMap>) are
complete.
Current state (partial)¶
ensure_workspace_indexed (src/indexing/preload.rs, used by find
references) parses files in parallel via
parse_files_parallel_with_progress ((uri, Option<content>) pairs)
and parse_paths_parallel_with_progress ((uri, PathBuf) pairs, read
from disk). Both run on the shared pull-index pool in src/parallel.rs
(map_indexed): workers claim the next file as they finish the last,
the pool is capped at available_parallelism(), and never spawns more
workers than there are files.
Transient entry eviction after GTI and find references has been
removed. Parsed files stay cached in uri_classes_index, symbol_maps,
use_map, and namespace_map so that subsequent operations benefit
from the work already done. This trades a small amount of memory for
faster repeat queries and simpler code.
Self-scan classmap building (scan_psr4_directories,
scan_directories, scan_vendor_packages,
scan_workspace_fallback_full) now uses a two-phase approach:
directory walks collect file paths first (single-threaded), then files
are read and scanned in parallel batches via std::thread::scope.
Three parallel helpers in classmap_scanner/discovery.rs cover the
three scan modes: scan_files_parallel_classes (plain classmap),
scan_files_parallel_psr4 (PSR-4 with FQN filtering), and
scan_files_parallel_full (classes + functions + constants). Small
batches (≤ 4 files) skip threading overhead.
The byte-level PHP scanner (find_classes, find_symbols) uses
memchr SIMD acceleration to skip line comments, block comments,
single-quoted strings, double-quoted strings, and heredocs/nowdocs
instead of scanning byte-by-byte. This reduces per-file scanning time
for files with large docblocks or string literals.
read_for_scan (classmap_scanner/mod.rs) now reads file bytes
adaptively: files at or above 256 KiB are memory-mapped so the OS page
cache is shared without a heap copy, and smaller files (the vast
majority of source files) are read directly into a heap buffer, since
mapping a small file costs more in page-fault and lock overhead than
copying it. This closed the gap identified in earlier profiling, where
mapping every file regardless of size held a process-wide lock that
serialized concurrent readers.
Remaining work¶
The following are deferred to a later sprint:
- Priority-aware scheduling. Interactive requests (completion, hover, go-to-definition) should preempt batch work. Currently all threads run at equal priority.
- Parallel classmap scanning in
find_implementors. Once the workspace index is ready (the default"full"strategy after startup),find_implementorsanswers entirely from thegti_indexreverse-inheritance index and never reaches the sequential classmap scan below. Phase 3 (reading and parsing classmap files one at a time) only still runs for"composer"/"self"/"none"strategies, for a request that arrives before the background index finishes, or for a target that lives under/vendor/(where the index-ready fast path would filter out the package's own implementations). The candidate files are then parsed one at a time (parse_and_cache_filein a loop insrc/definition/implementation.rs). Parallelizing it requires care because it interleaves reads and writes throughclass_loadercallbacks. - Parallel autoload file scanning. The
scan_autoload_fileswork queue (src/indexing/scan.rs) is inherently sequential due torequire_oncechain following, but the initial batch of files could be processed in parallel before following chains.
Why not rayon?¶
rayon is the obvious choice for "process N files in parallel" and
Libretto uses it successfully. But it runs its own thread pool
separate from tokio's runtime. When rayon saturates all cores on a
batch scan, tokio's async tasks (completion, hover, signature help)
get starved for CPU time. There is no clean way to pause a rayon
batch when a high-priority LSP request arrives.
Why the classmap is not a prerequisite¶
The classmap is a convenience for O(1) class lookup and class name completion. But most resolution already works on demand via PSR-4 (derive path from namespace, check if file exists). Class name completion is a minor subset of what users actually trigger. This means classmap generation can run at normal priority without blocking the user. They can start writing code immediately while the classmap builds in the background.
X7. Recency tracking¶
Impact: Medium · Complexity: Medium-High
The current lazy-loading design provides an implicit recency signal:
classes in uri_classes_index were loaded because the developer interacted with
their file during this session (hovered, navigated, completed). Source
tiers 0 (use-imported) and 1 (same-namespace) already capture this
for the current file's neighborhood. The fqn_uri_index source captures
cross-file interactions (go-to-definition, hover, or completion that
triggered a load).
This implicit signal works because unloaded classes are in a separate bucket (classmap/stubs, tier 2) with lower priority. Now that full indexing is the default (parsing all files at startup), every class appears equally "loaded" and the tier distinction has collapsed. The same-namespace tier now contains every class in the namespace, not just the ones the developer recently touched.
When to implement: Eager/full indexing is now the default, so the tier distinction has already collapsed as described above — this is ready to implement.
Design sketch:
-
Track accepted completions. When the editor sends
completionItem/resolveor the nextdidChangecontains text matching a recently offered completion, record the FQN and a timestamp. -
Track navigation. When go-to-definition or hover resolves a class, record the FQN.
-
Score decay. Use an exponential decay function so that a class used 5 minutes ago scores higher than one used 2 hours ago, but both score higher than one never interacted with.
-
Integration with sort key. The recency score could replace the source tier dimension (since tier 0/1/2 distinctions become less meaningful with full indexing) or be added as a new dimension between affinity and demotion. The sort_text scheme is documented in ARCHITECTURE.md § Class Name Sources and Priority.
-
Persistence. The recency table can be in-memory only (reset on server restart). Cross-session persistence is a nice-to-have but not essential; the affinity table already provides a good cold-start ordering.
X12. Say when an exclude hid the class a diagnostic names¶
Impact: Low-Medium · Complexity: Medium-High
An over-broad [indexing] exclude makes real classes unresolvable,
and the resulting Class App\Generated\Foo not found is
indistinguishable from a typo: the user's own configuration caused
it and nothing says so, which reads as a PHPantom bug. When class
resolution fails, the FQN maps to a PSR-4 path, and that file exists
on disk but is_excluded_path matches it, extend the message with
the cause ("defined in src/Generated/Foo.php, which [indexing]
exclude skips"). The PSR-4 mapping makes the probe a single stat
plus an already-compiled glob match on the failure path only;
classmap-only projects get no probe rather than a disk walk.
X14. Forward Zed's file_scan_exclusions and file_types¶
Impact: Low · Complexity: Low
Waiting on upstream review. Zed's extension API serves extensions only
the language, lsp, and context_servers settings categories, so the
PHP extension cannot read the editor's own file_scan_exclusions or
file_types and forward them the way the VS Code extension forwards
files.exclude and files.associations. Zed users therefore have to
restate those two lists under lsp.phpantom.initialization_options,
which editor-setup.md documents as the
workaround.
zed-industries/zed#66121
adds WorktreeSettings::for_worktree (file_scan_exclusions and
file_scan_inclusions as their source globs) and
FileTypeSettings::for_worktree (the effective file_types map) to
extension API 0.8.0, and the Zed section of editor-setup.md links it.
Zed is slow to review, so nothing here is scheduled until it merges.
What follows it:
- A pull request to
zed-extensions/php, once a Zed release ships the API. Bumpzed_extension_api, read both settings inlanguage_server_initialization_options, and merge them intoindexing.excludeandindexing.extensionswithout overwriting what the user set there. An exclusion that an inclusion overrides must not be forwarded. Afile_typesentry forPHPcontributes only when it is a bare*.extglob, the same rule the VS Code extension applies tofiles.associations. - Drop the manual step from the Zed section of
editor-setup.mdonce that extension release is out.
X18. Watch [indexing] include and stub paths outside the workspace¶
Impact: Low-Medium · Complexity: Medium
An include path outside the workspace is indexed at startup and then
never refreshed. The client only watches its workspace folders, so an
edit to a shared library at /opt/company/lib leaves stale symbols, and
a class added there stays unknown, until the editor restarts. Paths
inside the workspace are covered by the **/*.php watchers every
session registers, and the exclude exemption IndexFilters gives a
named path keeps their events from being dropped.
Followed symlinks have the same problem and already solve it:
build_watched_file_registration adds a
RelativePattern
watcher based at each link. Add the outside include paths to that list,
then check against VS Code that a server-registered relative pattern
outside the workspace actually delivers events
(vscode-languageserver-node#1783
reports that it does not). If it does not, fall back to a server-side
notify watcher for these few named paths.
Stub paths outside the workspace ([stubs] paths and the editor's stub
directory) have the same gap and take the same watchers. An event under
one already sets stubs_changed in classify_watched_changes, which
rebuilds the stub index, so only the registration is missing.
X13. Decide how workspace-wide edits treat excluded files¶
Impact: Low-Medium · Complexity: Medium
Find-references walks via collect_workspace_index_files_gitignore and
namespace rename via collect_php_files_gitignore; both apply the
index filters, so an excluded tree is invisible to both: a rename can leave
excluded code calling a name that no longer exists, with no warning.
That is consistent with what an exclude means, but sharper than
"background discovery" suggests. Options: (a) keep the behaviour and
document it under the exclude setting; (b) let correctness
operations (rename, find-references) ignore [indexing] exclude on
the grounds that the setting is an index-size and startup-time tool,
not a statement that the code does not exist; (c) keep the exclusion
but include a warning in the rename response when excludes are
configured. Maintainer's call on the semantics; whichever way it
goes, the chosen behaviour needs a test and a sentence in
configuration.md.
X22. Read YAML files with a parser¶
Impact: Low-Medium · Complexity: Medium-High
PHPantom has no YAML parser: about 50 functions across 18 files read YAML line by line, each with its own idea of indentation, comments, quoting, and flow collections.
Step 1: the shared parser and the services files. Add
yaml-rust2, the parser PHPlumb uses, so code ported from it fits, and
a shared module, src/yaml.rs, that builds a tree in which every
scalar keeps its byte range and can give the key path to an offset
(PHPlumb's crates/phplumb-index/src/frameworks/yaml.rs is a 220-line
model). The parser's markers count characters, not bytes, so convert
them through a table of line starts, and allow for CRLF. An escaped
quoted scalar's value differs from its source text. Where a project's
files are indexed, read the parser's events directly rather than
building a tree per file, so Drupal core's thousand-plus YAML files do
not each allocate one.
A real parser rejects the whole document at its first error, and a file
being typed into often has one. Keep the last tree that parsed for an
open document, and keep the tolerant line scan for working out what the
cursor is typing (@ service IDs and the other YAML completions).
Then move scan_yaml in src/symfony/resources.rs, which reads both
Symfony's and Drupal's services files, onto the module against its
existing tests. Measure benches/memory_usage.py's Symfony and Drupal
scenarios before and after. Files: Cargo.toml, src/yaml.rs (new),
src/lib.rs, src/symfony/resources.rs.
Step 2: the remaining files.
- Symfony:
src/symfony/routes.rs,translations.rs,validation.rs,serializer.rs,tags.rs,config_tree.rs,bundles.rs,messenger.rs, andsrc/completion/symfony_string_keys.rs. - Doctrine:
src/doctrine/connection.rs,mapping_files.rs, and the repository mappings insrc/framework.rs. - Drupal:
src/drupal/routing.rs,links.rs,libraries.rs,permissions.rs,config.rs, andconfig_keys.rs. - Yii:
src/yii/definitions.rs.
Move them one file per change, each against its existing tests, and
delete the helpers the last one leaves unused (yaml_mapping_key,
yaml_content_before_comment, strip_yaml_quotes). What a file
declares is read from the tree; what the cursor is typing still comes
from the tolerant scan, since a file being edited often does not parse.
T55
(nested parameter values) should be built on the parser rather than
taught to the line scan. Measure indexing time and memory on
benches/memory_usage.py's Symfony and Drupal scenarios after each
move.
X23. Read XML files with a parser¶
Impact: Low-Medium · Complexity: Medium-High
<route id="search" path="/search" condition="request.query.get('page') > 1"/>
<trans-unit id="terms" resname="Terms & conditions">
XML is read by ten hand-written tag scanners (scan_xml in
src/symfony/resources.rs, routes.rs, tags.rs, messenger.rs,
serializer.rs, validation.rs, src/doctrine/mapping_files.rs, and
src/framework.rs, scan_xliff in src/symfony/translations.rs), all
built on xml_attr_value in src/framework.rs. A tag ends at the first
>, so one inside an attribute value cuts the tag short. Character
references are never decoded, so an attribute holding & is read
with the entity in it, and an XLIFF <source> holding one is skipped
(first_source), so the message is never declared. CDATA sections and
namespace prefixes are not understood either.
Read XML with an event parser that reports byte positions (quick-xml
does, and keeps going up to the first error, which suits a document
being edited), behind one shared module, and move the scanners onto it
one file per change.
Symfony 7.4 deprecated XML for service and route configuration, so those two scanners matter less with every release. XLIFF catalogues and Doctrine, validation, and serializer mappings are not deprecated, and they gain the most. Start with them.