Skip to content

PHPantom Architecture

This document explains how PHPantom resolves PHP symbols — classes, interfaces, traits, enums, and functions — across files and from the PHP standard library.

Overview

PHPantom is a language server for PHP projects. It provides completion, go-to-definition, go-to-implementation, find references, hover, signature help, and diagnostics. It works by:

  1. Parsing PHP files into lightweight ClassInfo / FunctionInfo structures (not a full AST — just the information needed for IDE features).
  2. Caching parsed results in an in-memory uri_classes_index keyed by file URI.
  3. Building a precomputed symbol map (part of each file's FileState) during parsing for O(log n) go-to-definition lookups and call-site detection for signature help.
  4. Resolving symbols on demand through a multi-phase lookup chain.
  5. Merging inherited members (from parent classes, traits, interfaces, and mixins) at resolution time.

Multi-file scanning

Most features (completion, go-to-definition, hover, signature help, diagnostics) use maps or known file names and never walk directories. Only two features do multi-file scanning:

  • Go-to-implementation scans for concrete classes that implement an interface or extend an abstract class (see find_implementors). Walks PSR-4 source directories only.
  • Find References scans for all occurrences of a symbol across the project (see ensure_workspace_indexed). Walks the entire workspace root.

Both features follow the same principle for vendor code: the fqn_uri_index (populated from Composer's classmap and the self-scanner) is the source of truth. Vendor directories are never walked. User PSR-4 roots from composer.json are walked because user files change between dump-autoload runs.

The two walkers differ in scope because GTI only needs class declarations (which live in PSR-4 roots), while Find References needs any usage of a symbol, which could be in a standalone script, config file, or index.php at the project root.

Design Philosophy

PHPantom is built in layers. Each layer is independently useful and independently testable.

  • Layer 0: Stubs. Embedded PHP standard library types. Available immediately, no project context needed.
  • Layer 1: Single file. Parse the open file, extract classes/functions/symbols. Completion, hover, and go-to-definition work within the file with no cross-file resolution at all.
  • Layer 2: On-demand resolution. When a symbol references a class in another file, resolve it through the fqn_uri_index or PSR-4 and parse that file. Only the files actually needed are touched.
  • Layer 3: FQN-to-URI index. A name-to-URI index covering the whole project. Enables class name completion and O(1) cross-file lookup. Built from Composer's classmap or self-generated via a fast byte-level scan.
  • Layer 4: Full index (default). Background-parse every file in the fqn_uri_index. Enables workspace symbols, fast find-references, and rich completion item detail.

Each layer builds on the one below it. A bug in the FQN index doesn't break single-file completion. A slow full index doesn't block on-demand resolution. New features can be developed and tested against the lower layers without waiting for a full project scan. This is also why PHPantom starts fast: Layer 0-2 are ready in milliseconds, Layer 3 takes seconds, and Layer 4 fills in afterward.

Module Layout

This tree lists directories and load-bearing files, not every source file; run ls src/ for the current listing. Modules ending in _tests or a sibling tests.rs/*_tests.rs hold unit tests for the module they sit next to.

src/
├── lib.rs                  # Backend struct, state, module declarations, shared constants (PARSE_WORKER_STACK_SIZE, …)
├── main.rs                 # Entry point (stdin/stdout LSP transport, CLI dispatch)
├── server.rs               # LSP protocol handlers (initialize, didOpen, completion, …), each delegating to its module
├── backend.rs, backend/    # Backend construction, file access, workspace startup (startup.rs), document lifecycle (documents.rs)
├── config/                 # .phpantom.toml / workspace configuration, one file per section group
│
│   # Data model
├── types/                  # Core structures (ClassInfo, MethodInfo, ResolvedType, SubjectExpr, …)
├── php_type/               # PHP type representation: parse, display, normalize, subtype, transform
│
│   # Parsing & indexing
├── parser/                 # mago-syntax AST → ClassInfo/FunctionInfo (classes, functions, use statements, attributes, incremental update_ast)
├── docblock/               # PHPDoc parsing (tags, templates, shapes, conditional types, type_strings)
├── symbol_map/             # Precomputed per-file symbol spans, definition sites, call sites
├── scope_collector/        # Variable scope-map construction
├── classmap_scanner/       # Byte-level PHP scanning for class discovery (no full parse)
├── composer/               # composer.json, installed.json, the generated autoload maps, PSR-4 resolution
├── names/                  # Name resolution: written names via imports/namespace, docblock template/alias scoping, per-file resolved names
├── reference_index.rs      # Workspace-wide reference index for find-references / rename
├── reference_counts.rs     # Bounded exact member-reference cache for declaration hints and lenses
│
│   # Class & type resolution
├── resolution/             # Multi-phase class/function/constant lookup across files (find_or_load_class), lazy parsing, loader closures
├── class_lookup.rs         # Class-lookup helpers; class_lookup/subtyping.rs holds the subtype checks (is_subtype_of_typed)
├── inheritance/            # Parent/trait/mixin member merging, generics substitution
├── virtual_members/        # Synthesized members: phpdoc.rs (@method/@property, phpdoc/mixins.rs for @mixin) + laravel/ (one file per Eloquent/framework feature)
├── stubs.rs, stub_patches/   # Embedded phpstorm-stubs index + hand patches
├── phar.rs                 # Class discovery inside PHAR archives
│
│   # The shared type engine ("what is the type of this expression here?")
├── type_engine/
│   ├── subject_expr.rs, subject_extraction.rs, subject_resolution.rs
│   │                       # Extracting and resolving the subject before ->, ?->, ::
│   ├── key_path.rs         # The value a key path ('profile.city') reaches, for every helper that reads one
│   ├── resolver/           # Subject expression → ClassInfo (type engine entry point) + chain cache
│   ├── variable/           # Variable type resolution via assignment scanning
│   │   ├── forward_walk/   #   the forward walker (shared by diagnostics, hover, go-to-def, sig help)
│   │   ├── rhs_resolution/ #   right-hand-side expression resolution
│   │   └── …               #   closure/foreach/class-string/raw-type resolution
│   ├── call_resolution/    # Call expression + callable target resolution, return types, arg types
│   └── types/              # Type-hint → ClassInfo, narrowing/, conditional return types
│
│   # Completion (uses the type engine above)
├── completion/
│   ├── handler/            # Completion request orchestration (member access, class constants, named args, phpdoc)
│   ├── context/            # Context-specific completion (catch, class, keyword, namespace, override, type-hint, …)
│   ├── phpdoc/             # PHPDoc tag completion + docblock generation/
│   ├── source/             # Source-text scanning (comment position, throws analysis)
│   ├── variable/           # Variable-name completion + scope collection
│   ├── builder.rs          # Build LSP CompletionItems from resolved ClassInfo
│   └── …                   # target.rs, array_shape.rs, named_args.rs, use_edit.rs, eloquent_string.rs, laravel_route_controller.rs, …
│
│   # LSP features (one module each)
├── hover/                  # Hover: symbol-map dispatch, type/signature/docblock formatting
├── definition/             # Go-to-definition (resolve, member, variable/, implementation, declaration, type_definition)
├── resource_navigation.rs  # Schema-free PHP class/member indexing and navigation in YAML/XML
├── symfony/                # Symfony service IDs, container parameters, routes, translations, bundle configuration keys, form fields and options, validation mappings, serializer groups, event names, and Messenger buses and handlers: YAML/XML/XLIFF/Twig scanners, declaring files
├── twig/                   # Twig template names in any project that uses Twig: template roots discovered from the names templates reference, the template-name scanner, block names paired across the templates that extend, use, or embed each other, the filters and functions extensions declare (the installed packages' read from disk), and the variables a template reads, traced to the renders, templates, and globals that pass them and typed by what those pass, with the attributes read off them
├── yii/                    # Yii views and the path aliases they are named through (the alias table read from the params files, with where each alias is declared, view keys resolved to templates), the files asset bundles list (resolved under the bundle's source or base path), route names and route arguments (route paths and handlers, looked up in the declaring files' route side tables), DI definitions (the classes they bind, the parameters their argument keys name, and the definition files installed packages contribute), event listeners (read from the files of the events groups the merge plan and the installed packages list), the properties form fields and hydration maps name (member accesses kept only on a form model where the call could be any class's), the key paths `ArrayHelper` reads (which calls take one and how they split it, walked by `type_engine/key_path.rs`), the parameters a render call passes its view (keyed by the view and the name, read against the `@var` block the template opens with, beside the names every view is given by the configuration, `setParameter()` calls, and the renderer's injections), and params (the merge plan read from `composer.json`, which says which files are handed `$params`, and the params files it lists, the installed packages' included, merged into a key tree that types `$params` at the top of those files and judges the keys read from it), translation message IDs (the message files of the directories the DI definitions give their message sources, keyed by category, with the translator's default category and locale read from the params), and the `config-plugin` of a `composer.json`, read in place as a resource document for its group names, `$group` references, and file paths
├── stylesheets.rs          # CSS class selectors of the workspace's `.css`, `.scss`, and `.less` files, which the class names a Yii tag's `class()` and `addClass()` take resolve against
├── references/, rename/, highlight/
├── signature_help.rs, semantic_tokens.rs, inlay_hints.rs, folding.rs, code_lens.rs
├── document_symbols.rs, document_links.rs, workspace_symbols.rs, formatting/
├── selection_range.rs, type_hierarchy.rs
│
│   # Diagnostics
├── diagnostics/
│   ├── mod.rs              # Module map, code naming rules, shared range helpers
│   ├── collect.rs          # Running the fast and slow collectors over one file
│   ├── delivery.rs         # Debounced scheduling, two-phase publish, push and pull delivery, the worker
│   ├── external/           # PHPStan / PHPCS / PHPMD / Mago subprocess pipelines
│   ├── stale.rs, suppression.rs, helpers.rs, ignore_rules.rs, workspace.rs
│   └── <collector>.rs      # One module per diagnostic (unknown_classes, unknown_functions,
│                           #   unknown_members/, undefined_variables/, argument_count, type_errors/, …)
│
│   # External tools & CLI subcommands
├── phpstan.rs, phpcs.rs, phpmd.rs, mago.rs, phpstan_ignore.rs   # External analyzer integrations
├── analyse/                # `analyze` CLI subcommand (batch diagnostics, output formatting)
├── fix.rs                  # `fix` CLI subcommand (automated code fixes)
├── move_cli/               # `move` CLI subcommand (class/namespace refactoring)
├── self_update.rs          # Binary self-update
│
│   # Templates & shared utilities
├── blade/                  # Laravel Blade template support (directives, preprocessor)
├── tempest/                # Tempest templates, routes, and model property names
├── template/               # Shared virtual PHP source maps and LSP coordinate translation
└── util.rs, text_position.rs, text_scan.rs, atom.rs, call_args.rs, return_collection.rs, toposort.rs, ci_map.rs, process.rs, progress.rs

build.rs                    # Parses PhpStormStubsMap.php, generates the stub index at build time
stubs/                      # Composer vendor dir for jetbrains/phpstorm-stubs
tests/
├── integration/            # One file per feature area (completion_*, definition_*, code_action_*, diagnostics_*, hover, …); shared helpers in common/mod.rs
├── unit/                   # Unit tests (composer, docblock, named args, …)
├── fixtures/               # Fixtures driven by fixture_runner.rs
├── psalm_assertions/, phpstan_nsrt/, phpstan_data/   # `$var => 'ExpectedType'` assertion suites ported from Psalm / PHPStan
├── phpstan_symfony/, phpstan_doctrine/   # Projects the PHPStan Symfony and Doctrine extensions' type and rule tests run in
├── support/                # Code both runners share (the fixture projects' backend)
└── assert_type_runner.rs, fixture_runner.rs

The shared type engine lives under type_engine/. type_engine/resolver/, type_engine/variable/ (including the forward_walk/ forward walker), type_engine/call_resolution/, type_engine/type_ops/, and the subject extraction/resolution files are the project's single type-resolution engine — they answer "what is the type of this expression here?" and are consumed by diagnostics, hover, go-to-definition, and signature help, not just completion (see Forward Walker and Name Resolution below). Do not build a second type-resolution path: extend the engine here so every consumer benefits.

External Crates

PHPantom uses several crates from the Mago project for PHP parsing and type representation:

Crate Purpose
mago-names Use-statement and namespace resolution
mago-phpdoc-syntax PHPDoc parsing, including the PHPStan/Psalm type mini-language
mago-syntax PHP source to CST

mago-phpdoc-syntax parses a docblock comment and the type expressions embedded in its tags in one pass. src/docblock/parser.rs adapts its CST to the owned DocblockInfo / TagInfo pair the rest of the codebase works with, reducing each tag to a vendor-agnostic TagKind (src/docblock/tag_kind.rs), the vendor prefix it was written with, and the raw source text of its value.

PhpType (src/php_type/) is a pointer-sized handle to an interned TypeKind node, itself built from the borrowed mago_phpdoc_syntax::cst::type::Type AST. Every type-carrying field in the data model (type_hint, return_type, native_type_hint, native_return_type, asserted_type, template_param_bounds values, generics type arguments, ResolvedType::type_string) uses PhpType. The substitution engine in inheritance.rs operates on HashMap<String, PhpType> so that template parameter replacement never re-parses type strings.

Types are hash-consed: every constructor routes through the interner in php_type/intern.rs, so two structurally equal types always share one allocation. That is what lets a type occurrence cost 8 bytes rather than 24 plus a private copy of its payload on a workload that repeats the same few thousand forms everywhere, and it makes PartialEq a pointer comparison instead of a structural walk. Match on PhpType::kind() to inspect a node, and build new ones through the constructors (PhpType::named, PhpType::nullable, PhpType::union, …) rather than by constructing a TypeKind directly, so the pointer and structural notions of equality never drift apart. The table holds weak references, so forms nothing refers to any more are reclaimed: TypeKind::Raw and TypeKind::Literal carry free text, which would otherwise grow without bound in a long-running server.

Several other Mago crates were evaluated and ruled out:

Crate Reason
mago-codex Replaces ClassInfo model with one that cannot carry LaravelMetadata.
mago-semantics 12K false positives on Laravel; no way to inject our type context.
mago-linter Same problem; Integration::Laravel is surface-level only.
mago-fingerprint Requires mago-names for limited value; signature_eq already works.

All Mago crates are pinned to the same release. When upgrading, update all Mago crates in a single commit and run the test suite.

Docblock string helpers kept by design

The following items in type_strings.rs operate on raw docblock text (tokenizing tag descriptions, separating type tokens from parameter names) rather than on structured type fields, and have no PhpType equivalent:

  • split_type_token — extracts a type token from a tag description
  • PHPDOC_TYPE_KEYWORDS — completion candidate list for PHPDoc types

Go-to-Definition Architecture

The definition subsystem uses a three-tier approach, from fastest to slowest:

Tier 1: Precomputed Symbol Map (primary)

During update_ast, every navigable symbol occurrence in a file is recorded as a SymbolSpan in a sorted vec stored in the file's FileState (Backend::files, keyed by file URI). Each span records the byte range and a SymbolKind variant:

SymbolKind What it captures
ClassReference Class/interface/trait/enum names in type contexts (new Foo, extends, implements, type hints, catch, docblock types)
ClassDeclaration Class name at its declaration site (cursor already at definition)
MemberAccess ->, ?->, :: member names with the subject text and static/method-call flags
Variable $variable tokens (both usage and definition sites)
FunctionCall Standalone function call names
SelfStaticParent self, static, parent keywords in navigable contexts
ConstantReference Constant names (define() name, class constant access, standalone constant reference)
MemberDeclaration Method, property, or constant name at its declaration site (not navigable for go-to-definition, but needed for find-references)
NamedArgument A named argument's label (name: in new Field(name: 'x'), #[Field(name: 'x')] alike), pointing back at the call site it belongs to

When a go-to-definition request arrives, resolve_definition converts the cursor position to a byte offset and does a binary search on the symbol map. If a SymbolSpan is found, it dispatches directly to the appropriate resolution path — no text scanning needed. If the offset falls in a gap (whitespace, string interior, comment interior, etc.), the request is instantly rejected.

Docblock type references (@param, @return, @var, @template, @method, etc.) are extracted by a dedicated string scanner during the AST walk, since docblocks are trivia in the mago_syntax AST and produce no expression/statement nodes. These use the same ClassReference kind and resolution path as code type hints.

A few tags name a symbol without naming a type. @see, and PHPUnit's @covers / @uses / @coversDefaultClass, hold a free-text reference that symbol_map/docblock.rs splits into its class and member parts. Coverage metadata adds one shape the others do not have: @covers ::name is a global function on its own, and a method of the class a @coversDefaultClass names when there is one in scope. That default is read off the class docblock before its tags are walked (so tag order does not matter) and carried down the ExtractionCtx to the docblocks of the class's methods. The attribute spelling of the same metadata is handled in symbol_map/extraction/phpunit.rs: #[CoversClass(Foo::class)] needs nothing special because Foo::class is an ordinary expression, but the targets PHPUnit spells as strings (#[CoversMethod(Foo::class, 'bar')], #[CoversFunction('baz')]) get their spans there.

The symbol map also stores:

  • Variable definition sites (var_defs): records every assignment, parameter, foreach binding, catch variable, static/global declaration, and destructuring site with its byte offset, scope boundary, and effective_from offset (for assignments, this is the end of the statement so the RHS sees the previous definition). Go-to-definition for $var finds the most recent definition before the cursor within the enclosing scope via binary search.
  • Scope boundaries (scopes): function, method, closure, and arrow function body ranges. Used by find_enclosing_scope to determine which scope the cursor is in.
  • Named function bodies (named_function_bodies): each named function-like's name token paired with the offset its body opens at. A parameter is written between the two, and a closure in a parameter's default value declares parameters of its own in that same stretch, so the pair is what tells one function's parameter list from the next. function_parameter_definition answers "which parameter of this declaration carries this name", which is how a named-argument label reaches the parameter it binds.
  • Template parameter definitions (template_defs): @template tag locations so that template parameter names (e.g. TKey, TModel) that appear in docblock types can be resolved to their declaration site.
  • Candidate typed-receiver sites (typed_receiver_sites): the string keys a method call spells when only the receiver's type decides what it names — a constructor-injected Factory $views behind $this->views->make('page'), a mailable held in a local, a Symfony ContainerInterface $container behind $container->get('app.mailer'), a configurator's $services->set('app.mailer'), a URL generator's $urls->generate('blog_index'), a translator's $translator->trans('demo.title'), a controller's or Twig's render('page.html.twig'), an event dispatcher's $events->dispatch($event, 'app.order.placed'). Each site records the classes its receiver may be and the kind of key each makes it (ReceiverClass::targets). Extraction runs before the file's classes are resolved and cannot type the receiver, so it records the candidates and blade/typed_receiver.rs confirms them lazily through the shared type engine, once per file. Consumers of those keys (the call-site diagnostics, call-site inference, lookup_symbol_map, find-references, the Symfony declaration lookup) read the confirmed spans alongside the map's own StringKey spans. The reference candidate index takes the unconfirmed candidates, under every kind each could turn out to be, since a file has to be findable before it can be asked.
  • Config-backed Laravel resource names: one declarative table maps direct helpers, facades, contextual attributes, and middleware parameters to their config subtrees. A SymbolSpan whose string-key kind is ConfigResource(...) stores the short source name, while completion, navigation, diagnostics, and references derive the full dot key only at the config boundary. This keeps source ranges and reference identity exact without duplicating one trigger table across LSP features.
  • Candidate morph-column aliases (morph_column_sites): literals compared with properties or query columns are confirmed lazily by virtual_members/laravel/typed_morph_columns.rs. The shared type engine identifies the receiver model, and its parsed morphTo() metadata identifies the column. Array values in one query share a single model and column check. Confirmed literals become ordinary MorphAlias spans for completion, navigation, references, and diagnostics. Model metadata changes invalidate dependent confirmations, including when a relation's column changes without changing its PHP signature.
  • Routes (routes): each route a file declares, with what its name alone does not say: its path, group prefixes included, the placeholders the file spells out, and the handler it dispatches to. A path's placeholders only mean something under their route, so they are a side table keyed back to the name's span rather than spans of their own. Yii's route definitions fill it (symbol_map/extraction/yii_routes.rs), and a #[RouteArgument] is resolved through it by its handler.
  • Yii DI definitions (yii_definitions): each class a Yii DI definition binds (MailerInterface::class => [...]) or builds ('class' => Mailer::class), by the range of the class's name. A definition is recognised by its shape wherever it is written (symbol_map/extraction/yii_definitions.rs). Its 'name()' and '$name' keys are ordinary MemberAccess spans on the class (DocblockMemberRef::YiiDefinition), so the member machinery navigates, renames, and checks them, and the arguments a method key passes by name are YiiDefinitionArgument string keys. The files holding a definition are among the declaring files, which is how go-to-implementation and the CodeLens on a class find the definitions that bind it. Each definition array that builds a known class is also kept by where it starts (yii_definition_bodies), so diagnostics/yii_definitions.rs can find it in the AST and check its keys and values against the class, feeding the arguments through the call argument check.
  • Yii Active Record relations (yii_relations): each relation a record's relation() family or a query's with() and joinWith() names, one per segment of a path ('author.profile'), with the call's receiver and the segments before it (symbol_map/extraction/yii_active_record.rs). A relation is not a member of the record, so it is kept beside the spans: the parser reads the arms of a record's relationQuery() onto the method (MethodExtras::record_relations), and yii/active_record.rs lists them with the get{Name}Query() getters of a record that uses MagicRelationsTrait. An attribute the record's get() family names is an ordinary MemberAccess span on the receiver (DocblockMemberRef::YiiAttribute), so the member machinery navigates, renames, and checks it on the records among the receiver's classes. A record that declares no properties reads its attributes from its table's columns instead: yii/migrations.rs applies the up() methods of the migrations the yiisoft/db-migration params point at, in file name order, into a schema cached on the backend, and the parser keeps a tableName() that returns a literal on the method (MethodExtras::record_table). The record a query is for comes from the type engine: a third-party patch makes the package's queries generic over their model (stub_patches/active_record.rs).
  • Yii queries (yii_queries, yii_query_names): each yiisoft/db query chain that names tables or columns, read whole from its outermost call (symbol_map/extraction/yii_queries.rs), with the receiver of its first such call and the tables its from() and joins name, aliases included, plus those the earlier chains on the same variable in the same function named, and each table and column name it writes as a string, keyed to its chain. The extractor cannot see types, so yii/queries.rs resolves the receiver, keeps only a query, adds the table of the record an Active Record query is for, and reads the names against the schema yii/migrations.rs builds. A table named by a class constant (Table::POST . ' p') is kept as the constant and read from the class when the chain is resolved; the migrations read theirs the same way, and the schema is forgotten when the class's file changes.
  • Messenger handlers (messenger_handlers): each method a Symfony #[AsMessageHandler] registers, with the message class it receives, read from the attribute's handles: or the method's first parameter type. A handler is a fact about a class rather than a string at a cursor, so it is a side table rather than a span. The files holding one are among the Symfony declaring files (symfony/mod.rs), which is how the CodeLens on a message class finds the handlers that receive it.
  • Event subscriptions keyed by a constant (event_constant_keys, event_listener_lists): each key of a subscriber's getSubscribedEvents() map written as a class constant (KernelEvents::REQUEST), with the class resolved at extraction and the constant's name. The event name is the constant's value, which only loading the class gives, so the Symfony declaration lookup (symfony/mod.rs) reads it, inherited constants included, when names are asked for, and the reference index never does. Beside them, the subscriptions whose value lists other than one listener are kept by where their key starts, for the listener count hover shows.

Tier 2: Stored Byte Offsets (cross-file jumps)

MethodInfo, PropertyInfo, ConstantInfo, and FunctionInfo each carry a name_offset: u32 field recording the byte offset of the member's name token in the source file. ClassInfo carries keyword_offset: u32 for the class/interface/trait/enum keyword. These are populated during parsing.

When a cross-file jump lands on a class or member, find_member_position and find_definition_position convert the stored offset directly to an LSP Position via offset_to_position — no line-by-line text scanning needed.

A value of 0 means "not available" (stubs parsed before offsets were stored, synthetic/virtual members). In that case, the system falls back to Tier 3.

Tier 3: Docblock Tag Scanning (virtual members only)

The only remaining line-by-line text scanner is in find_member_position (definition/member/file_lookup.rs). When a member has no stored AST byte offset (name_offset is None or 0), the function scans docblock comments for @property / @property-read / @property-write and @method tags that declare the virtual member. This is inherent to virtual members: they exist only as docblock annotations and have no AST node to store an offset for.

All cursor context detection (word extraction, member access detection, type-hint resolution) now relies exclusively on the precomputed SymbolMap and AST walks. The former text-based helpers extract_word_at_position, extract_member_access_context, and resolve_type_hint_at_variable_text have been removed.

Variable Definition Resolution

Variable go-to-definition ($var → jump to definition) uses two layers:

  1. Symbol map (var_defs): the primary path. Finds the most recent VarDefSite before the cursor within the enclosing scope. When the cursor is physically on a definition token (parameter, foreach binding, catch variable), it returns None so the caller can fall through to type-hint resolution.
  2. AST-based search (resolve_variable_definition_ast): parses the file and walks the enclosing scope to find the definition site. Handles destructuring ([$a, $b] = ..., list($a, $b) = ...) and nested scopes correctly. Used as a fallback when the symbol map doesn't have a match. Returns None when the AST parse fails.

Framework Names in Strings

Frameworks name things in strings: a Laravel route('home') or config('app.name'), a Symfony $container->get('app.mailer'), generateUrl('app_home'), or dispatch($event, 'app.order.placed'). Each such string is a SymbolKind::StringKey span whose StringKeyKind says what it names, and whose is_write flag says whether it declares the name or reads it. Hover, go-to-definition, find references, highlights, semantic tokens, and the unknown-name diagnostics all read those spans, so a new kind of name is a new StringKeyKind variant plus the code that emits it.

The spans come from two places, and nowhere else:

  • PHP is read from the AST during symbol-map extraction (symbol_map/extraction/laravel/, symbol_map/extraction/symfony.rs, symbol_map/extraction/yii.rs, and symbol_map/extraction/yii_routes.rs). A function, an attribute, or a new is recognised by its resolved name. A method call whose name is too common to claim on sight (get(), set(), render(), dispatch()) is recorded as a candidate typed-receiver site (see above) and settled by the shared type engine, never by guessing from the receiver's spelling. A URL generator may stand behind a class of the project's own whose method passes the name on; that method is read to see which of its parameters it passes to a URL generator (Backend::typed_receiver_key_kind).
  • YAML, XML, XLIFF, and Twig are read as text by the scanners in symfony/ and twig/, which build each resource file's symbol map (resource_navigation.rs). These files have no AST we share, and their shapes are small enough that a line-oriented scan reads them reliably. Whether a file is a resource document is mostly its extension, but an .html file is a Twig template only under a root discovered from the names other templates reference (twig/roots.rs), so the check is Backend::is_resource_uri, not the URI alone.

Completion asks the same questions: it judges the call under the cursor with the predicates extraction uses (symfony_receiver_method, the attribute checks), and a configuration file through the same scan, so completion and navigation cannot disagree about which strings name what.

A Symfony name is declared by a span with is_write set, so there is no separate table of declarations. symfony/mod.rs only tracks which files hold one (the configuration, the controllers with #[Route]s, the listeners, the catalogues), and reads the declared names out of those files' symbol maps on demand. The maps are kept current by the ordinary document and watched-file lifecycle, and the reference index files every span by its key, so references need no second walk. All of it is gated on the project: Symfony names are only read when the project builds a Symfony container, Laravel's only when it is a Laravel application, and Yii's only when it routes with Yii's router. Yii's route names are declared in the same way, by spans in the PHP files that define its routes, so those files are among the declaring files too.

A Yii view is keyed by the path it names rather than by a name a file declares, with its alias left in (@views/blog/index), so two spellings of one template share no key. Its references are found by resolving each view key in the workspace to a file and comparing files, and the template itself declares nothing: the CodeLens at its top runs the same search.

Go-to-Type-Definition Architecture

"Go to Type Definition" (textDocument/typeDefinition) jumps from a symbol to the class declaration of its resolved type, rather than to the definition site. For example, if $user is typed as User, go-to-definition jumps to the $user = ... assignment, while go-to-type-definition jumps to class User { … }.

The handler (definition/type_definition.rs) reuses the same symbol-map lookup as go-to-definition and the same type-resolution pipelines as hover and completion:

  1. Symbol map lookup. Convert the cursor position to a byte offset and binary-search the symbol map (same as go-to-definition, including the offset-1 retry for end-of-token cursors).

  2. Type resolution by symbol kind:

SymbolKind Resolution path
Variable resolve_variable_type (type-string path) with fallback to resolve_variable_types (ClassInfo path). $this resolves to the enclosing class.
MemberAccess resolve_target_classes finds the subject's class, then the method's return_type or the property's type_hint is extracted. self/static/$this in return types are replaced with the owning class name.
SelfStaticParent self/static resolve to the enclosing class; parent resolves to the parent class.
ClassReference The type is the class itself.
FunctionCall The function's return_type is extracted.
ClassDeclaration, MemberDeclaration, ConstantReference No type definition target; returns None.
  1. Type string to class names. extract_class_names_from_type_string splits union types at depth-0 | separators, strips ? (nullable), generic parameters (<…>), array shapes ({…}), and trailing []. Scalar types (int, string, array, void, mixed, bool, float, null, false, true, never, callable, iterable, resource, object) are excluded since they have no user-navigable declaration.

  2. Class name to location. Each surviving class name is resolved via resolve_class_reference (the same function go-to-definition uses for class references), which tries same-file AST lookup, cross-file fqn_uri_index + uri_classes_index, PSR-4, and template parameter fallback. Duplicate locations are deduplicated.

For union types, the handler returns multiple locations (one per non-scalar class in the union), which editors display as a peek list.

Signature Help Architecture

Signature help shows parameter hints when the cursor is inside the parentheses of a function or method call. Detection uses a two-tier strategy:

Tier 1: Precomputed Call Sites (primary)

During update_ast, every call expression in the file is recorded as a CallSite in the SymbolMap. Each entry stores:

Field Purpose
args_start Byte offset immediately after the opening (
args_end Byte offset of the closing )
call_expression The call target in resolve_callable format (see below)
comma_offsets Byte offsets of each top-level comma separator

Call sites are emitted for all five AST call kinds: Call::Function, Call::Method, Call::NullSafeMethod, Call::StaticMethod, and Expression::Instantiation. The call_expression string is built by expr_to_subject_text, which recursively converts the AST expression into the text format the resolver expects:

  • "functionName" for standalone function calls
  • "$subject->method" for instance and null-safe method calls
  • "ClassName::method" for static method calls
  • "new ClassName" for constructor calls

When a signature help request arrives, detect_call_site_from_map converts the LSP position to a byte offset and searches the call_sites vec in reverse for the innermost entry whose argument range contains the cursor. The active parameter index is computed by counting how many precomputed comma offsets fall before the cursor. This handles nesting, strings containing commas/parens, and arbitrary chain depth correctly because the offsets come from the parser's token stream.

Tier 2: Text-Based Fallback

When the symbol map has no matching call site (typically because the parser could not recover the call node from incomplete code, e.g. an unclosed ( while the user is typing), the text-based scanner detect_call_site_text_fallback fires. It walks backward from the cursor to find an unmatched (, extracts the call expression with simple character-level scanning, and counts top-level commas. This path handles simple calls reliably but cannot resolve property chains, method return chains, or expressions containing balanced parentheses.

If the text fallback also fails to resolve the callable (e.g. because the class context is missing from the broken AST), a content-patching strategy inserts ); at the cursor position and re-parses the file to recover class context for resolution.

Call Expression Resolution

resolve_callable dispatches on the call expression format:

  1. new ClassName — loads the class via class_loader, finds __construct. Returns an empty parameter list when no constructor is defined.
  2. $subject->method — splits at the last ->, resolves the subject via resolve_target_classes (which handles $this, variables, property chains, call return chains, array access, etc.), then looks up the method on the resolved class.
  3. ClassName::method — resolves self/static/parent keywords and bare class names via class_loader, with a fallback to resolve_target_classes for class-string variables (e.g. $cls = Pen::class; $cls::make()).
  4. functionName — resolves via resolve_function_name (use map, namespace, stubs). Falls back to first-class callable resolution: if the expression is a $variable, looks up the last $var = target(...) assignment visible from the call among the file's first-class callable assignments (collected by one AST walk per parse, collect_fcc_assignments) and recursively resolves the underlying target.

Source Names and Resolved Names

The same spelling can name different classes depending on where it was read. With use App\Facades\Redis; in namespace App, the written name Redis is the facade, while the resolved name Redis (from \Redis, or from use Redis as PhpRedis;) is the global class. Every name is one of two kinds, and each kind has one rule:

  • Written names are spelled in the file: in code (new Foo, Foo::bar(), Foo::class, instanceof Foo, catch (Foo $e), a type hint) or in a docblock (@var Foo, @param Foo). They follow PHP's rule: the block's imports, else the current namespace, and never a global class. PHP falls back to the global namespace only for functions and constants, and PHPStan, Psalm and Mago read docblock names the same way. The source loader applies this rule. Resolve a name in code with names::resolve_code_class_name (or the contexts' resolve_written_class), a native hint with resolve_hint_type, and a docblock type with resolve_written_type.
  • Resolved names (ClassInfo::fqn(), parent_class, stored member types, any type the engine produced) are exactly the FQN they spell, so a bare Redis is the global class. Look them up with the resolved loader, which only accepts a class_lookup::Fqn.

A written name that no class answers to still has to come out as the FQN PHP reads it, or the resolved loader would later read the bare spelling as a global class. resolve_code_class_name qualifies it through the block's imports and namespace. A docblock name is qualified the same way unless a docblock anywhere in the file declares it as a template parameter or a type alias, in which case it keeps its spelling. Checking the whole file rather than the declarations in scope is filed in docs/todo/bugs.md.

A declaration's own types are code-name qualified by the parser while their file's imports are in scope (resolve_parent_class_names, parser/initializers.rs), so every consumer sees them as resolved names: extends, implements, trait use, @property and @method tags, constant initializers and declared types, @template bounds and defaults, @param-out and @phpstan-assert types, and the effective type of every method, parameter, property and function (the docblock type when it wins over the native hint, else the native hint). A re-parse of patched content goes through Backend::parse_php_resolved for the same reason; parse_php leaves names as written. Some native hints kept alongside for display stay as written: MethodInfo::native_return_type, PropertyInfo::native_type_hint and a function parameter's native_type_hint. Qualify those before comparing them with anything.

The parser decides whether a docblock type wins from the two types alone, which it cannot do where the docblock names a class the native hint does not: whether that class narrows the hint takes the class hierarchy. There it lets the docblock win and records the type with the hint qualified (ClassInfo::unverified_doc_types, FunctionInfo::unverified_doc_types). Loading the declaration puts the hint back unless the docblock class narrows it (type_engine/type_ops/docblock_narrowing.rs): Backend::link_loaded_class for every class the loader returns and the open file's own classes, and Backend::verify_function_doc_types for a function. The forward walker reads a parameter's docblock again inside the body, and checks it the same way.

The type engine contexts (ResolutionCtx, VarResolutionCtx, ForwardWalkCtx) carry two loaders and the imports:

  • source_class_loader (Backend::class_loader_with) applies the written-name rule: a leading \ is exact, otherwise the first segment goes through the imports, else the name is qualified with the current namespace. Hand it only written names: a resolved global Exception read through it inside namespace App is App\Exception.
  • class_loader (Backend::resolved_class_loader_with) takes an Fqn and looks the name up as exactly that FQN, in the index and then among the caller's own classes (a re-parse of patched content holds classes the index does not). A miss is final: it is never retried against a file's imports or namespace.
  • source_imports is the block's use table, which resolve_code_class_name qualifies a name no class answers to with. It is None only where no file context exists; a miss then keeps its spelling.

The two loaders have distinct types (class_lookup::ResolvedClassLoader and class_lookup::SourceClassLoader), so handing one where the other is expected does not compile. Fqn::new strips a leading \ once, so a resolved loader never sees one and no caller strips it by hand. Wrapping a written name in Fqn::new is the one remaining way to mix the two up; the module doc of src/class_lookup.rs says which loader entry point to use when.

Rules for code that touches names:

  1. Resolve a name once, where it is read, by the rule for its kind, then carry the FQN. Never hand a resolved name back to anything that resolves source text: the source loader, resolve_code_class_name, resolve_source_php_type_names, or resolve_arg_text_to_type.
  2. Text built from a resolved name gets a leading \. Rewriting self::X to Foo\Bar::X, or building Foo\Bar::class, produces source text, and a reader inside namespace App qualifies an unprefixed Foo\Bar as App\Foo\Bar. qualify_class_keyword, the initializer qualifier and a Foo::class parameter default write \Foo\Bar::X.
  3. Text written in another file is not read with the reader's loaders. A callee's parameter defaults, a constant's initializer and a parent's docblock were written against their own file's imports. Qualify them when that file is parsed, or resolve them as resolved names, never through the call site's source loader. Constant names in such text are qualified at parse time too where they have one meaning (use const, qualified names). An unqualified one inside a namespace is that namespace's constant when one is declared and the global constant otherwise, which only the index can say, so it is looked up when read: a class constant's initializer through FileCtx::namespace, a namespaced constant's value by Backend::lookup_global_constant_candidates from DefineInfo::namespace, and a parameter default through ResolutionCtx::written_in with the callee's namespace (FunctionInfo::namespace, or MethodInfo::default_namespace, kept only for a method whose defaults need it).
  4. Identify classes by FQN. ClassInfo::name is the short name, and class_lookup::find_class_by_name matches a bare name against the classes of every namespace block in the file. Use ClassInfo::fqn() and find_class_by_fqn when the question is "which class".

A change to name resolution needs tests with a global class and a namespaced class sharing one short name: the global one imported, not imported, and written with a leading \; inside a namespace and in the global namespace; and read from a caller in a different namespace than the file that declares it.

Symbol Resolution: find_or_load_class

When the LSP needs to resolve a class name (e.g. during completion on Iterator:: or when following a type hint), it calls find_or_load_class. This method tries these phases in order, returning as soon as one succeeds:

find_or_load_class("Iterator")
│
├── Stub paths: ExternalStubIndex (FQN → stub file)
│   The `[stubs]` paths and the editor's stub directory. A name
│   one of them declares means that declaration, over every other
│   (see "Stub Paths" below).
│   ↓ miss
│
├── Project scope: another Composer project's dependency
│   In a workspace of several Composer projects, a name the index
│   holds in another project's vendor/ resolves to the asking
│   project's own copy, or to nothing (see "Monorepo Support").
│   ↓ not another project's
│
├── Phase 0: fqn_class_index (O(1) hash hit)
│   Direct lookup by FQN. This is where cached results from
│   previous phases are found on subsequent lookups.
│   ↓ miss
│
├── Phase 0.5: built-in global names → embedded stubs
│   A global name the embedded stubs know is a PHP built-in, so a
│   conditional polyfill in vendor cannot shadow it.
│   ↓ miss
│
├── Phase 1: fqn_uri_index (FQN → file URI)
│   Direct hash lookup in the unified FQN-to-URI index, populated
│   at init time from Composer's classmap, the self-scanner, and
│   phar archives. Covers all classes (including vendor) that don't
│   need PSR-4 path computation.
│   ↓ miss
│
├── Phase 2: PSR-4 resolution
│   Uses PSR-4 mappings from composer.json to locate the file on disk.
│   These mappings only cover user code (vendor PSR-4 is not loaded).
│   Example: "App\Models\User" → workspace/src/Models/User.php
│   Reads, parses, resolves names, caches in uri_classes_index.
│   ↓ miss
│
├── Phase 3: Embedded PHP stubs
│   Looks up the class name in the compiled-in stub index
│   (from phpstorm-stubs). Parses the stub PHP source, caches
│   in uri_classes_index under a phpantom-stub:// URI.
│   ↓ miss
│
└── None

Caching

Every phase that successfully parses a file caches the result in uri_classes_index, fqn_class_index, and fqn_uri_index. This means:

  • Phase 1 (fqn_uri_index) files are parsed once, then found via Phase 0.
  • Phase 2 (PSR-4) files are parsed once, then found via Phase 0.
  • Phase 3 (stubs) are parsed once, then found via Phase 0.
  • Files opened in the editor are parsed on didOpen/didChange and always in Phase 0.

Index Write Sites

update_ast_inner (didOpen/didChange): writes all three class maps plus the file's FileState (symbol map, imports, namespaces, resolved names, parse errors, a template's lowering), replaced as a whole.

parse_and_cache_content_versioned (lazy loading): writes only uri_classes_index, fqn_class_index, fqn_uri_index. The editor-only FileState is skipped for lazily loaded files to reduce memory usage.

clear_file_maps (didClose): removes uri_classes_index and the file's FileState. Keeps fqn_class_index and fqn_uri_index so cross-file resolution survives file close.

Init functions: populate fqn_uri_index from Composer classmap, Drupal scans, PSR-0, phar archives, or full workspace scans. All paths are converted to URI strings at init time.

Duplicate Declarations

A class or function name can be declared by more than one file, which is how a package ships a variant behind a class_exists / function_exists guard. The lowest-sorting URI wins, so the name resolves to the same declaration however the parse workers were scheduled, and the declarations that lost are kept in duplicate_classes / duplicate_functions (keyed by name, then by declaring URI). A name only appears there once a second file declares it, so the overwhelming majority of symbols cost nothing, and keeping the runners-up is what lets the name pass to the next declarant when the winning file stops declaring it (rename, deletion, or an edit that removes it) instead of vanishing.

duplicate_classes only knows parsed declarations. Discovery also finds names in more than one file before anything parses them (two Composer projects of a workspace installing the same package), and a merge that keeps one location records the others in class_alternates, again only for names found more than once. A name whose indexed file goes away passes to one of them.

Both class indexing paths (apply_ast_index_updates_batch for editor files, parse_and_cache_content_versioned for lazily loaded ones) and the watched-file purge record declarations through SymbolIndex::with_class_declarations, which locks fqn_uri_index, fqn_class_index, and duplicate_classes together in that order. That is what keeps the two class indexes from describing different files for one name, and keeps a runner-up recorded by one path from going stale when the other withdraws a declaration. Readers that take more than one of these locks must take them in the same order.

The index derived from the class index (gti_index) is keyed by FQN, so it is repopulated from whichever declaration won rather than from the classes the current parse produced.

Lifecycle Invariants

  1. Every class in uri_classes_index has a corresponding entry in fqn_class_index. Both write sites maintain this. For a name two files declare, that entry is the winning declaration, so the losing file's uri_classes_index entry is described by duplicate_classes instead.
  2. Every FQN in fqn_class_index has a corresponding entry in fqn_uri_index. Violating this breaks GTD after didClose.
  3. fqn_uri_index entries are never removed by didClose. Once a class URI is registered it persists for the session (file renames trigger didClose + didOpen with the new URI).

Embedded PHP Stubs

PHPantom bundles the JetBrains phpstorm-stubs directly into the binary. This provides type information for ~1,450 built-in classes/interfaces, ~5,000 built-in functions, and ~2,000 built-in constants without requiring any external files at runtime.

Build-Time Processing

The build.rs script:

  1. If stubs/jetbrains/phpstorm-stubs/ does not exist, fetches the latest release tarball from the JetBrains/phpstorm-stubs GitHub repository and extracts it. This makes cargo install and cargo build work without any prior setup.
  2. Reads stubs/jetbrains/phpstorm-stubs/PhpStormStubsMap.php — a generated index mapping symbol names to file paths.
  3. Emits stub_map_generated.rs containing:
  4. STUB_FILES: an array of include_str!(...) calls embedding every referenced PHP file (~502 files, ~8.5MB of source).
  5. STUB_CLASS_MAP: maps class/interface/trait names → index into STUB_FILES.
  6. STUB_FUNCTION_MAP: maps function names → index into STUB_FILES.
  7. STUB_CONSTANT_MAP: maps constant names → index into STUB_FILES.

The stubs are cached in the stubs/ directory (gitignored). To update to the latest version, delete stubs/ and rebuild.

Runtime Lookup — Classes

At Backend construction, stubs.rs converts the static arrays into HashMaps for O(1) lookup. When find_or_load_class reaches Phase 3:

  1. Look up the class short name in stub_index → get the PHP source string.
  2. Parse it with the same parser used for user code.
  3. Run name resolution (for parent classes, trait uses, etc.).
  4. Cache in uri_classes_index under phpantom-stub://ClassName.
  5. Return the ClassInfo.

Because stubs are cached after first access, repeated lookups (e.g. every enum needing UnitEnum) hit Phase 1 and skip parsing entirely.

Runtime Lookup — Functions (find_or_load_function)

Built-in PHP functions (e.g. array_map, date_create, str_contains) are resolved through find_or_load_function, which mirrors the multi-phase pattern used for classes:

find_or_load_function(["str_contains", "App\\str_contains"])
│
├── Stub paths: ExternalStubIndex (FQN → stub file)
│   Parses the stub file with update_ast the first time, then
│   returns the declaration that file makes, even where another
│   file's declaration of the name is the one global_functions
│   resolves to.
│   ↓ miss
│
├── Phase 1: global_functions (user code + cached stubs)
│   Checks all candidate names against the global_functions map.
│   Keys are always FQNs: "array_map" for global functions,
│   "Illuminate\Support\enum_value" for namespaced ones.
│   No short-name fallback entries are stored.
│   ↓ miss
│
├── Phase 1.5: autoload_function_index (byte-level scan)
│   Checks candidate names against autoload_function_index
│   (function FQN → file path on disk).  Populated by the
│   find_symbols byte-level scan for both Composer projects
│   (autoload_files.php) and non-Composer projects (workspace
│   full-scan).
│   When found:
│     1. Reads the file from disk.
│     2. Calls update_ast to get full FunctionInfo + ClassInfo.
│     3. Results are cached in global_functions (so future
│        lookups hit Phase 1).
│     4. Returns the matching FunctionInfo.
│   ↓ miss
│
├── Phase 1.75: Last-resort autoload file parse
│   The byte-level scanner misses functions inside conditional
│   blocks (e.g. `if (! function_exists(...))` guards).  As a
│   safety net, lazily parses each known autoload file path
│   (stored in autoload_file_paths) via update_ast until the
│   function is found.  Skips files already in uri_classes_index.  Each
│   file is parsed at most once; subsequent lookups hit Phase 1.
│   ↓ miss
│
├── Phase 2: Embedded PHP stubs
│   Looks up each candidate name in stub_function_index.
│   When found:
│     1. Parses the entire stub file (extracting all FunctionInfo).
│     2. Caches ALL functions from that file into global_functions
│        under phpantom-stub-fn:// URIs (FQN keys only).
│     3. Also caches any classes defined in the same stub file into
│        uri_classes_index (so return type references can be resolved).
│     4. Returns the matching FunctionInfo.
│   ↓ miss
│
└── None

The function_loader closures in both server.rs (completion) and definition/resolve.rs (go-to-definition) build a list of candidate names — the bare name, the use-map resolved name, and the namespace-qualified name — then delegate to find_or_load_function. Because global_functions is keyed by FQN only, bare calls like enum_value() in namespace App succeed via the namespace-qualified candidate App\enum_value. This means built-in function return types are available for:

  • Variable type resolution: $dt = date_create(); → $dt is DateTime
  • Call chain completion: date_create()-> offers format(), modify(), etc.
  • Nested call resolution: simplexml_load_string(...)->xpath(...) works

User-defined functions in global_functions always take precedence over stubs because Phase 1 is checked first — stubs use entry().or_insert() to avoid overwriting existing entries.

Stub Paths

The [stubs] paths of .phpantom.toml, the stub packages Composer installed, and the directory an editor extension passes as initializationOptions.stubs.path (indexing/stub_paths.rs) are the one place a declaration is meant to win over every other: project code, vendor code, and the embedded stubs. A stub package is recognised from installed.json by name or package type (composer/installed.rs) when its Composer project's paths are registered, which a composer.lock change repeats. Discovery scans them into an ExternalStubIndex (the [stubs] paths in order, then each Composer project's stub packages, then the editor's directory, first declaration wins; a phpstorm-stubs checkout is read from its PhpStormStubsMap.php), and the class, function and constant lookups each consult it before any other phase (resolution/external_stubs.rs). Embedded-stub loading checks it too, so the embedded copy of an overridden built-in is never read.

A stub file is an ordinary file:// file in every other respect: it is parsed and cached like any other, so go-to-definition lands in it and the watcher's re-parse covers it, and its scanned names are merged into the discovery indexes so they complete before anything loads them. What keeps it out of analysis, rename and find-references is its registration as library code, inside the workspace or not. The parse-time skip of a redeclared built-in function, the constant publisher's last-writer-wins, and the third-party class patches all exempt a stub file. A phpstorm-stubs checkout has the gaps the embedded copy has, so it gets the same stub_patches corrections.

An untyped global $x; looks last, after the function's own @global tag and the file's top level, at the @global tags of every file discovery reads for its functions and constants: the stub paths, vendor packages, autoload and include files, and the workspace walk of a project without Composer (SymbolIndex::global_tags). The scans record only which files document which global, since a tag's type is written against its file's imports; the first lookup of a global reads those files, qualifies each tag's type with its own file's namespace and imports, and caches the union until the tags change (load_global_tag_type). When a stub path documents the global, only its tags count. A tag on one function counts for the global everywhere: it states what the global holds. A class file a Composer project autoloads by PSR-4 is scanned for its classes only, so its tags do not count, rather than counting once something happens to parse it. The watcher rereads a changed file's tags along with the rest of its rescan, and also for an open file and for a never-parsed file already known to hold tags. Other never-parsed files are left alone, since an editor's refocus reports the whole workspace as changed.

The index is rebuilt whole by refresh_stub_paths at the end of discovery, when the paths change (DiscoveryInputs), when a watched file under one changes, and after a Composer rescan, whose replacement of the vendor tree also drops the discovery entries of the stub packages inside it. A rebuild first drops everything parsed from a file under the old or new paths, so a removed path stops overriding at once and an added one is re-parsed in its new role.

Function Completion: Namespace Awareness

build_function_completions handles two modes:

  • use function context (for_use_import = true): The insert text is the FQN (e.g. Illuminate\Support\enum_value) so the resulting statement reads use function Illuminate\Support\enum_value;. The label is the FQN for namespaced functions and the signature for global ones.

  • Inline context (for_use_import = false): The insert text is a snippet using the short name (e.g. enum_value($0)). For namespaced functions, an additional_text_edits entry inserts use function FQN; at the alphabetically correct position, mirroring how class auto-import works. The detail shows the namespace (e.g. function (Illuminate\Support)). Functions in the same namespace as the current file do not receive an auto-import.

Deduplication uses the map key (FQN), so two functions with the same short name in different namespaces both appear as separate completion items.

Stub Patches

The embedded phpstorm-stubs sometimes lack @template annotations or have overly broad return types (e.g. mixed) for functions whose return type actually depends on an argument. PHPStan solves this with dynamic return type extensions written in PHP; PHPantom solves it by patching the parsed FunctionInfo or ClassInfo at load time.

Function patches

stub_patches/ provides apply_function_stub_patches(func), called from find_or_load_function in Phase 2 after parsing each function from stub source and before caching it in global_functions. The function dispatches to per-function patch functions based on the function name. Only functions with known deficiencies are patched; all others pass through unchanged.

Current patches:

  1. array_reduce — phpstorm-stubs declare mixed return type. The actual return type is the type of the initial value (3rd argument). The patch adds @template TReturn bound to $initial and sets the return type to TReturn, matching PHPStan's stubs/arrayFunctions.stub.

This is analogous to the Laravel Class Patches system but for built-in PHP functions rather than framework classes. When phpstorm-stubs gains proper annotations for a patched function, the corresponding patch can be deleted.

When to add a patch here vs. hardcoded logic in rhs_resolution.rs: if the correct behaviour can be expressed with @template / @return annotations (i.e. PHPStan's own stubs already have the fix), it belongs in stub_patches/. If the behaviour requires inspecting call-site argument values at resolution time (e.g. array_map's callback return type, or array_filter preserving the input array's element type), it must stay as hardcoded logic in rhs_resolution.rs / raw_type_inference.rs. Those functions are tracked in ARRAY_PRESERVING_FUNCS and ARRAY_ELEMENT_FUNCS in type_engine/variable/mod.rs, with the full inventory in docs/todo/completion.md C1.

Class patches

Class stub patches work the same way but are applied by apply_class_stub_patches(class) in parse_and_cache_content_versioned for URIs starting with phpantom-stub:// or phpantom-stub-fn://. Current class patches add @template parameters, @extends/@implements generics, and constructor bindings to the SPL iterator wrappers (IteratorIterator and its subclasses), which phpstorm-stubs leave ungeneric. This lets generic types flow through the wrapper (e.g. new LimitIterator($rules) over an ArrayIterator<int, Rule> yields Rule from current()). Other class patches tighten individual method return types on ReflectionClass, SimpleXMLElement, and the DOM classes. The full inventory is in the stub_patches module documentation.

Runtime Lookup — Constants

The stub_constant_index (HashMap<&'static str, &'static str>) is built at construction time from STUB_CONSTANT_MAP, mapping constant names like PHP_EOL, PHP_INT_MAX, SORT_ASC to their stub file source. It is consulted by the constant-value loader (Backend::constant_loader) during variable type resolution: when a variable is assigned from a global constant (e.g. $eol = PHP_EOL), the loader extracts the constant's initializer value from the stub source and the type is inferred from the literal (string, int, float, bool, null, or array). The same lookup chain also serves hover, completion of standalone constant names, and go-to-definition.

Go-to-Definition on Built-ins

An embedded stub has no file to open, so a jump to a built-in class, member, function, or constant finds nothing unless a stub path declares it. The usual one is the project's own jetbrains/phpstorm-stubs: as a Composer stub package it is a stub path, so the built-in resolves to its file and the jump is an ordinary one.

Version-Aware Filtering

phpstorm-stubs annotate functions, methods, and parameters with #[PhpStormStubsElementAvailable] attributes to indicate which PHP versions they apply to. For example, array_map has two variants of its second parameter: array $array (from PHP 8.0) and an untyped $arrays (PHP 5.3 to 7.4). Without filtering, both appear in signatures.

PHPantom detects the target PHP version during initialized:

  1. Read config.platform.php from composer.json (explicit platform override).
  2. Fall back to require.php from composer.json (e.g. "^8.4" → 8.4).
  3. Default to PHP 8.5 when neither is available.

The detected version is stored on the Backend as a PhpVersion(major, minor).

When parsing stubs (both class stubs via find_or_load_class and function stubs via find_or_load_function), the PHP version is passed through DocblockCtx.php_version to the extraction functions. Four filtering points apply:

  • Function-level: extract_functions_from_statements checks the function's #[PhpStormStubsElementAvailable] attribute. If the version range excludes the target, the entire function is skipped. This handles duplicate function definitions (e.g. array_combine has separate signatures for PHP ≤7.4 and ≥8.0).
  • Method-level: extract_class_like_members applies the same check to methods. For example, SplFixedArray::__serialize (from PHP 8.2) is excluded when targeting PHP 8.1.
  • Parameter-level: extract_parameters filters individual parameters. For example, array_map's untyped $arrays parameter (PHP 5.3–7.4) is excluded when targeting PHP 8.0+, leaving only the typed array $array.
  • Constant-level: set_php_version calls is_stub_constant_removed to evict constants whose @removed X.Y tag indicates they were removed at or before the target version (e.g. MCRYPT_ENCRYPT with @removed 7.2).

The attribute supports named arguments (from: '8.0', to: '7.4') and a positional argument ('8.1' treated as from). Both bounds are inclusive. A missing bound means unbounded in that direction.

User code is never filtered. The php_version field in DocblockCtx is None for files parsed via update_ast, so the filtering logic is a no-op for non-stub code.

Graceful Degradation

If the stubs can't be fetched (e.g. no network access during the build), build.rs generates empty arrays and the build succeeds. The LSP just won't know about built-in PHP symbols.

Inheritance Resolution

When building completion items or resolving definitions, PHPantom merges members from the full inheritance chain. Resolution proceeds in two phases:

  1. Base resolution (resolve_class_with_inheritance in inheritance.rs): merges own members, trait members, and parent chain members with generic type substitution.

  2. Virtual member providers (resolve_class_fully in virtual_members/mod.rs): queries registered providers in priority order and merges their contributions. Virtual members never overwrite real declared members or contributions from higher-priority providers.

All completion and go-to-definition call sites use resolve_class_fully, which is the primary entry point for full resolution.

Base Resolution

ClassInfo (own members)
│
├── 1. Merge used traits (via `use TraitName;`)
│   └── Recursively follows trait composition and parent_class chains
│
└── 2. Walk the extends chain (parent_class)
    └── For each parent: merge its traits, then its public/protected members

Virtual Member Providers

After base resolution, resolve_class_fully applies registered virtual member providers. These are implementations of the VirtualMemberProvider trait (defined in src/virtual_members/mod.rs) that synthesize methods and properties not present in the PHP source code.

Each provider implements two methods:

  • applies_to(class, class_loader) -> bool: cheap pre-check to skip providers early.
  • provide(class, class_loader) -> VirtualMembers: produce the virtual methods and properties.

Providers receive the base-resolved class (own + traits + parents) but without other providers' contributions. This prevents circular loading.

resolve_class_fully(class)
│
├── 1. resolve_class_with_inheritance(class)
│   └── Returns base-resolved ClassInfo
│
├── 2. For each provider (in priority order):
│   └── if applies_to(class): merge provide(class) into result
│       └── Skips members that already exist (no overwrites)
│
├── 3. Merge members from implemented interfaces
│
└── 4. apply_laravel_patches(class, fqn)
    └── Post-resolution fixups for Laravel classes (see below)

Provider priority order (highest first):

  1. Framework provider (e.g. Laravel): richest type info
  2. PHPDoc provider: @method, @property, @property-read, @property-write, @mixin

Among the providers registered in default_providers():

  • LaravelModelProvider (virtual_members/laravel/model_provider.rs): synthesizes virtual members for classes extending Illuminate\Database\Eloquent\Model. Produces relationship properties (methods returning HasMany, HasOne, BelongsTo, etc. generate a virtual property typed from the relationship's generic parameters), scope methods (both the scopeActive naming convention and the #[Scope] attribute from Laravel 11+ are supported; either style becomes active() as both static and instance), Builder-as-static forwarding (User::where()->get() resolves end-to-end), accessors (legacy getXAttribute() and modern Attribute casts), and cast properties ($casts array or casts() method entries are mapped to PHP types like datetime to \Carbon\Carbon, boolean to bool, framework class casts such as AsEnumCollection::of(Status::class) to Collection<array-key, Status>, custom cast classes to their get() return type). Highest priority among virtual member providers. Scope methods are also injected onto Builder<Model> instances via a post-generic-substitution hook in type_hint_to_classes_depth (see "Scope Methods on Builder Instances" below).
  • PHPDocProvider (virtual_members/phpdoc.rs, with @mixin collection in phpdoc/mixins.rs): surfaces @method, @property, @property-read, @property-write, and @mixin tags from the class-level docblock. Explicit @method / @property tags are parsed once during AST extraction into ClassInfo.doc_members (an Arc<DocblockMembers>, None when the docblock declares neither), so provide only reads structured data and applies the per-consumer generic substitutions. The provider collects those tags from the class itself, its used traits, its parent chain, and its implemented interfaces. For @mixin tags, it loads the referenced classes and merges their public members. Within the provider, explicit tags take precedence over mixin members. Recurses into mixin-of-mixin chains up to MAX_MIXIN_DEPTH.
  • FieldableEntityProvider (drupal/fields.rs), in a Drupal project only: gives the classes and interfaces under FieldableEntityInterface the fields of the entity types they may hold as typed properties, read from the entity classes' baseFieldDefinitions() (drupal/base_fields.rs) and from the field storage files of extensions and of the site's exported configuration (drupal/field_storage.rs), and gives the interfaces the untyped __get() and __set() every content entity has. Providers never see the Backend, so the field index reaches it through the resolved-class cache, whose slot reads the index through the Backend it is bound to when the workspace becomes a Drupal project. A reference field's target is the entity type its target_type setting names, the entity type's own bundle_entity_type for getBundleEntityType(), or else the default its item class's defaultStorageSettings() gives. An entity class's fields show on interfaces that do not depend on the entity class, so a change to them, to a field storage file, or to the parent, interfaces, or traits of a class the index was read through, evicts FieldableEntityInterface and everything under it, found through the inheritance index, once per publish batch.
  • FieldItemProvider (drupal/field_items.rs), in a Drupal project only: gives field item classes the properties their propertyDefinitions() declare, following parent::propertyDefinitions(), from the same field index. An item list reads a property on its first item, and a field is typed List<Item> with a reference field's target class as a second argument, so the list's properties, its first() and get(), which give the item carrying the target, and the target's typing of entity and referencedEntities() depend on the type arguments: resolve_class_for_type_hint adds them, as it does Doctrine's repository members, and specialises the list's template with the item alone. A change to an item class's propertyDefinitions() evicts that class and every class that extends it, found through the inheritance index, since a resolved class records no dependency on an ancestor further up than its parent.

Laravel Class Patches

After virtual members and interface members are merged, resolve_class_fully_inner calls apply_laravel_patches(class, fqn) from virtual_members/laravel/patches.rs. Unlike virtual member providers (which add new members), patches modify existing members' type information to fix framework-specific type inaccuracies that break chain resolution.

The patch system is centralized in a single module with one entry point. Dispatching is based on the fully-qualified class name and trait usage. Current patches:

  1. Eloquent\Builder::__call / __callStatic return type. Laravel's Builder::__call() is declared as returning mixed, but in practice always returns $this (scope dispatch, macro dispatch, Query\Builder forwarding). The patch overrides the return type to static so that method chains through unknown calls preserve the Builder type.

  2. Conditionable::when() / unless() return type. The trait declares @return $this|TWhenReturnType but the unresolved method-level template parameter TWhenReturnType prevents is_self_like_type from recognizing the return as self-referential, breaking method chain resolution on Builder and Collection. The patch replaces the return type with $this. Applied to the Conditionable trait itself, to Eloquent\Builder (which uses the trait), and to any class whose used_traits includes Conditionable.

  3. Bare Builder return types on scope methods. Handled separately in scopes.rs (is_bare_builder_type) because it runs at scope-injection time (post-generic-substitution), not during resolve_class_fully_inner. Documented in the patch module as part of the inventory but not dispatched from it.

Precedence Rules

  • Class own members always win.
  • Trait members override inherited members but not own members.
  • Parent members fill in anything not already present.
  • Virtual members from providers sit below all real declared members (own, trait, parent). Higher-priority providers shadow lower-priority ones. Within the PHPDoc provider, @method / @property tags beat @mixin members.
  • Private members are never inherited from parents (but trait private members are copied, matching PHP semantics).

Scope Methods on Builder Instances

Scope methods (both scopeX convention and #[Scope] attribute) are synthesized on the Model class by LaravelModelProvider, but they also need to be available on Builder<Model> instances (e.g. Brand::where('id', $id)->isActive()). This cannot be handled by a virtual member provider alone because providers run before generic argument substitution, so the provider would not know the concrete model type.

Instead, scope injection happens in three places:

  1. Post-generic-substitution hook (type_engine/resolver/, inside type_hint_to_classes_depth): after resolve_class_fully + apply_generic_args produces a Builder<User> class, the resolver detects that the result is an Eloquent Builder with a concrete model generic argument. It calls build_scope_methods_for_builder(model_name, class_loader) which loads the model, fully resolves it, extracts scope methods, and returns them as instance methods with static in return types substituted to the concrete model name. These are merged onto the Builder's method list, giving $q->active() after $q = User::where(...).

  2. Scope body Builder enrichment (type_engine/variable/resolution.rs, enrich_builder_type_in_scope): inside a scope method body, the $query parameter is typically typed as Builder without generic arguments. The enrichment function detects when the enclosing method is a scope (either the scopeX naming convention or the #[Scope] attribute) on a class that extends Eloquent Model, and the parameter type is Builder without generics. It rewrites the type to Builder<EnclosingModel>, which then flows through the generic-args path and triggers the post-substitution hook above. This makes $query->otherScope() resolve inside scope bodies.

  3. Go-to-definition fallback (definition/member.rs, find_scope_on_builder_model): when go-to-definition resolves a member on a Builder class and the normal lookup chain (own members, traits, parents, mixins, builder forwarding) fails, this fallback checks whether the member is a scope method injected from the model. It confirms the resolved candidate (with injected scopes) has the method, extracts the model name from the scope method's return type generic argument, loads the model, and finds the declaration through the model's inheritance chain. For scopeX-style scopes it looks for scopeXxx; for #[Scope]-attributed methods it falls back to the original method name. This bridges the gap between completion (which works on the merged ClassInfo) and GTD (which traces back to the declaring source file).

Interface Inheritance in Traits/Used Interfaces

The merge_traits_into function also walks the parent_class chain of each trait/interface it loads. This is critical for enums: a backed enum's used_traits contains BackedEnum, and BackedEnum extends UnitEnum. The parent chain walk ensures UnitEnum's members (cases(), $name) are merged alongside BackedEnum's own members (from(), tryFrom(), $value).

Implicit Enum Interfaces

PHP enums implicitly implement UnitEnum (for unit enums) or BackedEnum (for backed enums). The parser detects this and adds the appropriate interface to the enum's used_traits:

enum Color { ... }           → used_traits: ["\UnitEnum"]
enum Status: int { ... }     → used_traits: ["\BackedEnum"]

The leading backslash marks the name as fully-qualified so that namespace resolution doesn't incorrectly prefix it (e.g. an enum in namespace App\Enums won't resolve to App\Enums\UnitEnum).

At resolution time, merge_traits_into loads the UnitEnum or BackedEnum stub from the embedded phpstorm-stubs, and the interface inheritance chain provides all the standard enum methods and properties.

Composer Integration

PSR-4 Autoloading

composer/ parses:

  • composer.json → autoload.psr-4 and autoload-dev.psr-4 mappings

PSR-4 mappings come exclusively from the project's own composer.json. Vendor PSR-4 (vendor/composer/autoload_psr4.php) is not loaded. The fqn_uri_index is the sole source of truth for vendor code.

Design principle: vendor PSR-4 mappings are not loaded separately. The fqn_uri_index (populated from the Composer classmap and augmented by the self-scanner, see below) is the sole source of truth for vendor code. User PSR-4 roots are walked by Go-to-implementation (Phase 5) and Find References because user files change between dump-autoload runs.

Self-Generated Classmap

When Composer's autoload_classmap.php is missing or incomplete, PHPantom builds a classmap itself using a fast byte-level PHP scanner (classmap_scanner.rs). The scanner is a single-pass state machine that extracts namespace\ClassName pairs without a full AST parse, handling comments, strings, heredocs, and property accesses ($node->class). memchr provides SIMD-accelerated keyword pre-screening so files without class-like keywords are rejected immediately. Inside matched files, memchr also accelerates skipping of line comments (jump to newline), block comments (jump to *), single-quoted strings (jump to ' or \), double-quoted strings (jump to " or \), and heredocs/nowdocs (jump to newline) instead of scanning byte-by-byte.

Scanning is parallelised using a two-phase approach: directory walks collect file paths first (single-threaded, via the ignore crate), then files are read and scanned in parallel batches using std::thread::scope. Three helpers cover the 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). The thread count is capped at std::thread::available_parallelism(). Small batches (≤ 4 files) skip threading overhead and run sequentially.

The indexing strategy is configurable via [indexing] strategy in .phpantom.toml:

  • "full" (default) — same discovery as "self", then background-parses user PHP files to populate symbol maps and the reference candidate index.
  • "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 self-scan, ignoring Composer's classmap entirely. Equivalent to the merged approach with an empty skip set.
  • "none" — no proactive scanning; uses Composer's classmap if present but never self-scans to fill gaps.

The merged pipeline works in three steps: (1) load autoload_classmap.php into a HashMap<String, PathBuf>, (2) collect the classmap's file paths into a HashSet<PathBuf> skip set, (3) self-scan all PSR-4 and vendor directories, skipping files already in the skip set. The result is a merged index: classmap entries for everything Composer already knew about, plus self-scanned entries for everything it missed. When the classmap is complete (the common case), the self-scanner walks directories but skips every file, finishing almost instantly. When the classmap is empty or absent, it falls back to a full self-scan. When the classmap is partial (e.g. vendor classes only), vendor files are skipped and only user code is scanned. Every state of the classmap helps.

When self-scanning with a composer.json present, the scanner reads autoload.psr-4, autoload-dev.psr-4, autoload.classmap, and autoload-dev.classmap to determine which directories to walk. PSR-4 directories are filtered: only classes whose FQN matches the namespace prefix plus the relative file path are included. Vendor packages are discovered from vendor/composer/installed.json (both Composer 1 and 2 formats); the JSON packages array is borrowed rather than cloned to avoid allocating a copy of the entire vendor manifest. 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. Hidden directories are skipped automatically, and .gitignore rules are respected at every level. Paths listed under [indexing] include in .phpantom.toml are scanned at the end of every discovery pipeline with the gitignore and hidden-entry filters disabled. [indexing] exclude still prunes below an included directory, but no exclude applies to a named path itself, including the built-in laravel-ide-helper skip, which is compiled into a matcher of its own so a ! in exclude cannot cancel it. IndexFilters carries the named paths so the watcher and eviction honour the same exemption. The class lists Composer hands over without a walk (the classmap, the PSR-0 map, and the bootstrap classes in vendor/composer) pass through IndexFilters::retain_unexcluded where they merge into the index, so exclude means the same thing for a listed file as for a walked one. Because they run last, included paths fill gaps rather than displacing what discovery found. An included path inside the workspace is project code: the full background index parses it, so function-only files reach find-references and workspace symbols, and analyze reports on it. One outside the workspace is registered like a vendor directory, so it resolves but is never analysed, renamed into, or searched for references. The editor's other workspace folders (from initialize and workspace/didChangeWorkspaceFolders, deduplicated by containment in Backend::extra_roots) are library code in the same way: they join the project root's walk_roots call, so a link between them is walked once, and each registration records its claimant in library_claims so removing a folder releases only the spellings nothing else claims before its files are evicted. When no composer.json exists at all, the scanner falls back to walking all .php files under the workspace root.

Directory symlinks. The walkers descend into a symlinked directory, so a project that keeps its framework or a shared library outside the repository and links it into the tree gets the linked code indexed with the rest. Every path keeps the symlink spelling rather than the target's, which is what makes a file reached through the link the same file the editor opened. LinkClaims gives each walk one visit per target directory: the walk's own roots and its skipped trees are claimed up front, and each link claims its target the first time it is descended, so two links to one tree, a link pointing back at something the walk already covers, and a chain of directories holding several links apiece all cost one pass rather than one per route. orchestra/testbench-core ships laravel/vendor -> <project>/vendor, which is why the skipped trees are claimed and not merely pruned by path. Each link the index reached through also gets a watcher based at it (see build_watched_file_registration), since a workspace-relative watcher pattern never covers a path outside the workspace folders.

The scan results are converted to URI strings and inserted into fqn_uri_index. Everything downstream (resolution, diagnostics, go-to-definition) uses the unified index.

Redundant I/O elimination: init_single_project parses composer.json once and passes the pre-parsed serde_json::Value to build_self_scan_composer. Previously each function re-read and re-parsed the file independently.

Vendor dir detection: the config.vendor-dir setting is read from composer.json once during initialized (via parse_composer_json, which returns both the PSR-4 mappings and the vendor dir name). The absolute vendor directory path is cached on Backend.vendor_dir_paths and a file:// URI prefix is stored in Backend.vendor_uri_prefixes for fast vendor-file detection at runtime. Both fields are Vecs to support monorepo workspaces with multiple subprojects (see below). For single-project workspaces, each collection has exactly one entry.

Autoload Files

vendor/composer/autoload_files.php lists files containing global function definitions and define() constants. During initialized(), these files are scanned with the lightweight find_symbols byte-level pass (not a full AST parse). This populates autoload_function_index (function FQN → file path), autoload_constant_index (constant name → file path), and fqn_uri_index (class FQN → file URI). Full parsing is deferred to the moment a symbol is first accessed via find_or_load_function (Phase 1.5), find_or_load_define (Phase 2), or find_or_load_class (through fqn_uri_index).

The byte-level scanner only discovers top-level declarations. Functions wrapped in if (! function_exists(...)) guards (common in Laravel helpers) are at brace depth > 0 and are missed. As a safety net, all visited autoload file paths are stored in autoload_file_paths. When a function or constant is not found in any index, find_or_load_function (Phase 1.75) and find_or_load_define (Phase 3) lazily parse each known autoload file via update_ast as a last resort. Each file is parsed at most once.

Non-Composer Function and Constant Discovery

In projects without composer.json, there is no autoload_files.php to consult. Instead, the full-scan (find_symbols) runs on all workspace files during initialization, populating three indices in a single pass: fqn_uri_index (classes), autoload_function_index (functions), and autoload_constant_index (constants). When a function or constant is first accessed, find_or_load_function or find_or_load_define lazily calls update_ast on the file, caching the result for subsequent lookups.

Monorepo / Multi-Composer-Root Support

When the workspace root has no composer.json but contains subdirectories that are independent Composer projects, PHPantom discovers and processes each subproject automatically. This is a best-effort mitigation for workspaces where the editor opens a monorepo root as a single folder. The monorepo path only activates when there is no root composer.json.

Discovery. discover_subproject_roots in composer/mod.rs walks the workspace using the ignore crate (WalkBuilder), respecting .gitignore at every level. Any directory containing a composer.json is recorded as a subproject root. Nested subprojects (a composer.json inside an already-accepted root) are filtered out. Each discovered composer.json is read to extract the config.vendor-dir setting.

Per-subproject processing. For each discovered (subproject_root, vendor_dir), the same Composer pipeline runs: PSR-4 mappings (with base paths resolved to absolute paths so resolve_class_path works regardless of workspace root), classmap parsing, vendor package scanning from installed.json, and autoload file indexing. Results are merged into the shared backend state with first-subproject-wins semantics for duplicate FQNs.

Loose file discovery. After all subprojects are processed, the gitignore-aware full-scan walker (scan_workspace_fallback_full) runs on the workspace root with a skip set containing all subproject root paths. This picks up PHP files outside any subproject tree (e.g. top-level scripts, shared utilities) without double-scanning subproject content.

Vendor tracking. Each subproject's vendor directory is registered in both vendor_uri_prefixes (for URI-level vendor detection in diagnostics, find references, and rename) and vendor_dir_paths (for filesystem-level skip logic in go-to-implementation and workspace indexing).

Per-project class lookups. The class index is shared, but a file only sees its own Composer project's classes and dependencies. When the workspace has two or more projects with a vendor directory, each gets a ProjectScope (resolution/project_scope.rs): its own root and vendor directory, the packages it installed from outside its vendor directory (path repositories, which can live in another project's tree), and every other project's root and vendor directory. A file belongs to the innermost project whose root holds it, and files outside every project are visible to all of them. The work done for one file (an LSP request through RequestScope, the file's diagnostic pass, analyze and fix) runs with the scope of the innermost project holding it, and find_or_load_class answers a name the index holds in another project with the project's own copy from class_alternates or duplicate_classes, or with nothing. Work that is not about one file, and files outside every project, see the shared index. The class memo and the resolved-class cache key their entries by scope, since a class resolves differently when its ancestors come from a different copy. A workspace with a single installed project has no scopes and pays nothing.

Trade-offs. A single PHP version is used for the entire workspace. Per-subproject .phpantom.toml is not supported. Multi-root LSP workspaces (separate workspaceFolders) are a separate feature.

Function Resolution Priority

When resolving a standalone function call (e.g. app(), date_create()), the lookup order is:

  1. User code (global_functions from opened/changed files and lazily parsed autoload index hits)
  2. Autoload function index (autoload_function_index, populated by find_symbols for both Composer and non-Composer projects, triggers lazy update_ast on first access)
  3. Known autoload files (autoload_file_paths, last-resort lazy parse for functions missed by the byte-level scanner, e.g. those inside function_exists() guards)
  4. Embedded stubs (stub_function_index from phpstorm-stubs, parsed lazily)

This ensures that user-defined overrides or polyfills always win over stubs.

Go-to-Implementation: find_implementors

When the user invokes go-to-implementation on an interface or abstract class, PHPantom scans for concrete classes that implement or extend it. When invoked on a method definition in a concrete class, it performs a reverse jump to the interface or abstract method that declares the prototype. The forward scan runs five phases, each progressively wider:

find_implementors("Cacheable", "App\\Contracts\\Cacheable")
│
├── Phase 1: uri_classes_index (already-parsed classes)
│   Iterates every ClassInfo in every file already in memory.
│   Checks interfaces list and parent_class chain against the target.
│   ↓ continue
│
├── Phase 2: fqn_uri_index (FQN → URI entries not yet covered)
│   Loads classes via class_loader for entries not seen in Phase 1.
│   ↓ continue
│
├── Phase 3: fqn_uri_index files (string pre-filter → parse)
│   Collects unique file paths from fqn_uri_index.
│   Skips files already in uri_classes_index.
│   Reads each file's raw source and checks contains(target_short).
│   Only matching files are parsed via parse_and_cache_file.
│   Every class in a parsed file is checked (not just the looked-up FQN).
│   ↓ continue
│
├── Phase 4: embedded stubs (string pre-filter → lazy parse)
│   Checks each stub's static source string for contains(target_short).
│   Matching stubs are loaded via class_loader (parsed and cached).
│   ↓ continue
│
├── Phase 5: PSR-4 directory walk (user code only)
│   Recursively collects all .php files under every PSR-4 root.
│   Skips files already covered by fqn_uri_index (Phase 3) or uri_classes_index.
│   Reads raw source, applies the same string pre-filter.
│   Matching files are parsed via parse_and_cache_file.
│   Discovers classes missing from fqn_uri_index.
│   ↓ done
│
└── Vec<ClassInfo> (concrete implementors only)

Workspace-Index Fast Path and Vendor-Owned Targets

Once the workspace index is ready, Phase 1 alone answers the request and its results are restricted to project classes. The reverse-inheritance index is populated by every parse, so a vendor or stub class that happened to be loaded earlier in the session would otherwise appear while an identical class that was never loaded would not, making results depend on session history. The full workspace index parses only project files, so user-only is the deterministic set to return.

The exception is a target that itself lives under /vendor/. An interface shipped by a Composer package is normally implemented inside that same package, so the project-only restriction would answer a request about HttpKernelInterface with everything Symfony ships filtered out. Such a target keeps the class-index scans (Phases 2–5), which is the only way to reach classes the workspace index never parses. Embedded stubs stay on the fast path: PHP's own interfaces (Countable, Iterator) are implemented across the whole dependency tree, so scanning it for them costs far more than the answer is worth.

Phase 5 Scope: User Code Only (by design)

Phase 5 walks PSR-4 roots from composer.json (autoload and autoload-dev). Since PSR-4 mappings are sourced exclusively from the project's own composer.json (vendor PSR-4 is not loaded), Phase 5 inherently only discovers classes in the user's own source directories (e.g. src/, app/, tests/). Vendor dependencies are fully covered by fqn_uri_index (Phase 3).

Phase 5 exists to catch newly-created or not-yet-indexed user classes that are missing from fqn_uri_index.

Note: the walk (collect_php_files_gitignore) still receives the vendor dir paths because a fallback mapping like "" => "." resolves to the workspace root, where the walk must skip the vendor directory (and hidden directories like .git).

String Pre-Filter

Phases 3–5 avoid expensive parsing by first reading the raw file content and checking whether it contains the target class's short name. A file that doesn't mention "Cacheable" anywhere in its source can't possibly implement the Cacheable interface, so it's skipped without parsing. This keeps the scan fast even for large projects with thousands of files.

Caching

parse_and_cache_file follows the same pattern as find_or_load_class: it parses the PHP file, resolves parent/interface names via resolve_parent_class_names, and stores the results in uri_classes_index, fqn_class_index, and fqn_uri_index. This means files discovered during a go-to-implementation scan are immediately available for subsequent completion, definition, and implementation lookups without re-parsing.

Member-Level Implementation

When the cursor is on a method call (e.g. $repo->find()), resolve_member_implementations first resolves the subject to candidate classes. If any candidate is an interface or abstract class, find_implementors is called and each implementor is checked for the specific method. The location returned for an implementor is the declaration that supplies the body: its own when it declares the method, otherwise the trait or ancestor it inherits the method from, searched in PHP's member precedence order, since a class that inherits a method unchanged still implements it. The implementation CodeLens counts through the same helpers, so its count and go-to-implementation's list agree. A method that is only re-declared abstract is another declaration rather than an implementation and is skipped, which is also why implementors are collected with abstract classes included — whether the class is abstract says nothing about the method that was asked for.

Reverse Jump: Concrete Method → Prototype Declaration

When go-to-implementation is invoked on a MemberDeclaration symbol (a method name at its definition site), resolve_reverse_implementation checks whether the enclosing class implements any interface or extends an abstract class that declares a method with the same name. If found, it returns the location of the prototype method in the interface or abstract class. This covers:

  • Direct interfaces (class Foo implements Bar)
  • Interfaces inherited from parent classes (class Foo extends Base where Base implements Bar)
  • Interface-extends chains (interface A extends B)
  • Abstract parent methods (abstract class Base { abstract function foo(); })

For interface and abstract class method declarations, the same handler works in the forward direction: it calls resolve_interface_member_implementations to find all concrete classes that define the method.

FQN-Based Comparison

All comparisons in class_implements_or_extends and deduplication in find_implementors use fully-qualified names (built from ClassInfo.name + ClassInfo.file_namespace). The short-name fallback is only used when the target has no namespace information, preventing false positives when two interfaces in different namespaces share the same short name (e.g. App\Logger vs Vendor\Logger).

Find References: ensure_workspace_indexed

When the user invokes "Find All References", PHPantom scans all user files for occurrences of the symbol. Vendor files are excluded (matching PhpStorm's behaviour).

Indexing

Before scanning, ensure_workspace_indexed ensures all user files have symbol maps:

  1. Phase 1: fqn_uri_index files (user only) — files already known from update_ast calls. Vendor and stub URIs are skipped.
  2. Phase 2: .gitignore-aware workspace walk — uses the ignore crate's WalkBuilder to recursively discover PHP plus YAML/XML resource files (and, in a Symfony project, XLIFF catalogues, and in a project that uses Twig, its .twig, .html, and .htm files, which root discovery reads before any template is indexed) under the workspace root, respecting .gitignore rules (including nested and global gitignore files). This automatically skips generated/cached directories like storage/framework/views/ (Laravel blade cache), var/cache/ (Symfony), and node_modules/. The vendor directory is always skipped regardless of .gitignore content. Hidden directories are skipped by default.

PHP files are parsed in parallel using std::thread::scope. The work is split into chunks (one per CPU core) and each thread reads a file from disk and calls update_ast, which acquires write locks briefly to store results while the expensive parsing step runs without any locks held. Batches of 2 or fewer files skip threading overhead. YAML/XML files take the lightweight schema-free scanner and publish synthetic class/member symbol maps into the same reference index.

Parsed files stay cached in uri_classes_index, symbol_maps, file_imports, and file_namespaces after the scan completes. There is no post-scan eviction; keeping the entries means subsequent operations (a second find-references call, go-to-definition on a cross-file symbol) benefit from the work already done.

The workspace reference index keeps its primary map deliberately coarse: it stores candidate URIs and occurrence counts, not a second copy of every source position. CodeLens can therefore answer a conclusive zero without a semantic scan. A named-argument label registers under the member key of the name it spells, and counts as a reference rather than registering with a zero: which parameter a label names is the callee's, so only the exact search can say, and a promoted property whose only other spelling is a label at a constructor call has to reach that search instead of being answered as having nothing to find. The first nonzero member query resolves every member receiver in each candidate file while one forward-walked variable scope is active, packs the target class atoms by symbol-span index, and retains that compact per-file semantic layer for later member names. Candidate files are filled in parallel; edits evict their own layer, and signature changes clear layers whose receiver types may have changed. Exact locations remain bounded behind the 50,000-location annotation cache. Refresh-capable clients receive the lens after the background result is ready; other clients retain lazy codeLens/resolve as a compatibility path.

Cross-file scanning

The user_file_symbol_maps() helper snapshots all symbol maps whose URI does not fall under the vendor directory or the internal stub scheme. With Arc<SymbolMap>, the snapshot is a vector of cheap reference-count increments rather than deep clones. Five scanners use this snapshot:

  • find_class_references — matches ClassReference spans by resolved FQN
  • find_member_references — matches MemberAccess and MemberDeclaration spans by member name, filtered by class hierarchy, together with the NamedArgument labels that fill one of its promoted properties — the property spelled at the call that builds the object, which no receiver walk sees
  • find_function_references — matches FunctionCall spans by resolved FQN
  • find_constant_references — matches ConstantReference spans by name
  • find_parameter_label_references — matches NamedArgument spans whose label binds the searched parameter, resolving each label through its own call so that a same-named label of another callee is left out

Variable references ($this, local variables) are scoped to the enclosing function/class in the current file only, and do not use the cross-file scan. A parameter is the exception: every call that hands it a value by name writes its name outside the declaring file, so a search for a parameter runs the label scan across the workspace beside the file-local uses.

Class-aware member filtering

When the user triggers "Find References" on a method, property, or constant, the handler resolves the target class and builds a hierarchy set containing all related class FQNs. Only references whose subject resolves to a class in this set are included. This prevents $user->save() from matching $order->save() when User and Order are unrelated.

The hierarchy set is built in two passes:

  1. Ancestors — walk the parent chain, interfaces, traits, and mixins upward from the target class, collecting every FQN encountered.
  2. Descendants — walk the reverse inheritance index (gti_index) down from the declaring classes until no new FQNs are added (transitive closure).

That index only holds classes from files something has parsed, so a receiver it does not account for (typically a class in a package nothing has needed yet) is settled by walking up from the receiver's own class to the declaring classes instead, loading the ancestors that walk needs. Without it the same search would answer differently depending on what the session parsed before it.

For each candidate MemberAccess span, the subject text is resolved to class FQNs using a lightweight path:

  • self / static / $this → enclosing class FQN via find_class_at_offset
  • parent → enclosing class's parent FQN
  • Bare class name (static access) → resolved via the file's use-map and namespace
  • $variable → full variable type resolution via resolve_variable_types

When the subject resolves to one or more FQNs, the reference is included only if at least one FQN is in the hierarchy set. When resolution fails entirely (untyped variable, complex expression), the reference is included conservatively to avoid false negatives.

For MemberDeclaration spans, the enclosing class at the span offset is checked against the hierarchy set. Property declaration sites (which use Variable spans for GTD compatibility) are filtered by checking the declaring class's FQN.

Union Type Completion (by design)

When a variable can hold one of several types (from match arms, ternary branches, null-coalescing, or conditional return types), the completion list shows the union of all members across all possible types, not just the intersection of shared members.

This is a deliberate choice that matches PHPStorm and Intelephense behaviour. The rationale:

  1. The developer may not have isolated branches yet. When working through a match or ternary, the code often starts with a shared variable before the developer splits behaviour per type. Hiding branch-specific members would block progress during that phase.
  2. Missing completions are worse than extra completions. Restricting to the intersection would hide useful members whenever a variable has more than one possible type.
  3. Type safety belongs in diagnostics. Calling a method that only exists on one branch is a potential bug, but the right place to flag it is a diagnostic/static-analysis pass, not the completion list.

This is distinct from narrowing via early return, unset(), or instanceof guards. Those reflect deliberate developer intent to eliminate types, so the narrowed-out members are correctly hidden. Union completion is about types the developer has not yet separated.

Members that are only available on a subset of the union already show the originating class in the detail field (e.g. "Class: AdminUser"), which gives the developer a visual hint. A future enhancement could sort intersection members above branch-only members or add an explicit marker.

Context-Aware Class Name Completion

When the user types a class name outside of a member-access chain (->, ::), the LSP needs to decide which symbols to offer. PHP reuses many of the same keywords in positions that accept very different kinds of symbols. new only makes sense with concrete classes. implements only accepts interfaces. use inside a class body only accepts traits. Offering the wrong kind of symbol is noisy at best and confusing at worst. This section explains how the LSP detects the context, selects which symbols to show, and handles the many edge cases that arise from incomplete information.

Context Detection

detect_class_name_context() in class_completion.rs walks backward from the cursor through whitespace and comma-separated identifier lists to find the keyword that governs the completion position. It recognises twelve contexts:

Context Trigger What is shown
Any Bare identifier (e.g. $x = DateT\|) All class-likes, constants, and functions
New new \| Concrete (non-abstract) classes only
ExtendsClass class A extends \| Non-final classes (abstract is OK)
ExtendsInterface interface B extends \| Interfaces only
Implements class C implements \| Interfaces only
TraitUse class D { use \| Traits only
Instanceof $x instanceof \| Classes, interfaces, enums (not traits)
TypeHint function f(\|), ): \|, public \| Classes, interfaces, enums (not traits)
UseImport use \| (top level) All class-likes + function/const keyword hints
UseFunction use function \| Functions only
UseConst use const \| Constants only
NamespaceDeclaration namespace \| Namespace names only

TypeHint is not detected by detect_class_name_context (which only handles keyword-triggered contexts). Instead, the type-hint completion handler (complete_type_hint) and the PHPDoc type completion handler (complete_docblock_type_or_variable) pass ClassNameContext::TypeHint directly to build_class_name_completions. This excludes traits from parameter types, return types, property types, and PHPDoc @param/@return/@var type positions. @throws uses a separate Throwable-filtered path instead.

Comma-separated lists are handled by walking past Identifier, sequences so that implements Foo, Bar, \| still resolves to Implements. Multi-line declarations work the same way because the backward walk skips all whitespace including newlines.

TraitUse vs UseImport is distinguished by brace depth: use at brace depth >= 1 is inside a class body (trait use), while brace depth 0 is a top-level import.

Handler Routing

try_class_constant_function_completion() in handler.rs is the entry point. It extracts the partial identifier, detects the context, and branches:

  • UseFunction and UseConst short-circuit to dedicated builders (build_function_completions, build_constant_completions). These bypass class-name logic entirely. Items from the current file are filtered out (importing a function from the file you are editing is pointless). A semicolon is appended to the insert text. For UseFunction, namespaced functions use their FQN as insert text so the resulting statement reads use function Illuminate\Support\enum_value;.

  • NamespaceDeclaration short-circuits to build_namespace_completions, which produces namespace-path items from PSR-4 prefixes and known class FQNs.

  • UseImport calls build_class_name_completions with an empty use-map (the file's own use-map contains the half-typed use line, which the parser interprets as a real import and would appear as a bogus completion item). The results are post-processed: classes defined in the current file are removed, a semicolon is appended, and function/const keyword hints are injected when the partial matches.

  • All other class-only contexts (New, ExtendsClass, ExtendsInterface, Implements, TraitUse, Instanceof) call build_class_name_completions normally. Constants and functions are suppressed.

  • Any calls all three builders (classes, constants, functions) and merges the results.

Class Name Sources and Priority

build_class_name_completions collects candidates from five sources. Deduplication is by FQN (seen_fqns set). All candidates are ranked by a five-dimension sort_text key:

{match_quality}{source_tier}{affinity}{demote}{gap}_{short_name_lower}

Match quality (highest weight). Compares the typed prefix against the short name: a = exact match, b = starts-with (or empty prefix), c = substring only. An exact match always ranks above every prefix match, regardless of source or affinity.

Source tier. Three tiers based on how the class relates to the current file:

Tier Source Meaning
0 Use-imported classes Developer explicitly imported this name
1 Same-namespace classes (from uri_classes_index) PHP auto-resolves without a use statement
2 Everything else (fqn_uri_index, stubs) Requires a use import

Import affinity. A four-digit inverted score derived from the file's namespace declaration and existing use imports. Namespaces that appear frequently in the file's imports score higher, pushing related classes above unrelated ones within the same tier. The score sums occurrence counts across all ancestor prefixes of the candidate's namespace.

Heuristic demotion. 0 = normal, 1 = demoted by naming-convention heuristics (see below). Demotion sits after affinity but before gap, so a demoted exact match still ranks above every non-demoted prefix match (match quality is higher weight), and a non-demoted name always beats a demoted name within the same affinity group regardless of name length.

Name-length gap. A three-digit distance between the short name length and the typed prefix length (short_name.len() - prefix.len()). Smaller gaps sort first. This is the lowest-weight dimension, breaking ties within the same affinity and demotion group. The effect: typing "Pro" ranks Product (gap 4) above ProductFilterTerm (gap 14) when both live in the same namespace. This smooths the visual transition as a prefix match narrows toward an exact match. Without it, there is a visible "snap" when a candidate suddenly jumps to the top upon becoming an exact match.

The result set is capped at 300 items. When truncated, is_incomplete is set to true so the editor re-requests completions as the user types more characters. Items are sorted by sort_text before truncation so higher-priority items survive.

Kind Filtering

Each context defines which class-like kinds are valid through matches_kind_flags(kind, is_abstract, is_final). For example, TraitUse only matches ClassLikeKind::Trait, and New only matches non-abstract classes. This filter is applied at every source, but the amount of information available varies by source, which creates a layered filtering strategy.

Loaded classes (in uri_classes_index). The full ClassInfo is available, so the filter is exact. An interface will never appear in TraitUse completions if it has been parsed.

Unloaded stubs (in stub_index but not yet parsed into uri_classes_index). The raw PHP source is available. detect_stub_class_kind scans it for the declaration keyword (class, interface, trait, enum) and modifiers (abstract, final, readonly). This is fast (string search, no tree-sitter parse) and gives accurate kind information for filtering.

Unloaded project classes (in fqn_uri_index but not parsed). No kind information is available. These are allowed through the filter with benefit of the doubt. A naming-convention heuristic (likely_mismatch) demotes but does not remove suspicious names (e.g. FooInterface is demoted in ExtendsClass context).

Use-Map Validation

The file's use map is the most problematic source because it can contain entries that are not class-likes at all:

  • Namespace aliases (use App\Models as M; puts M -> App\Models in the map, but App\Models is a namespace, not a class).
  • Non-existent imports (the user may have typed use Vendor\Something; for a class the LSP has never seen).
  • Half-typed lines (the parser interprets use c as importing "c").

Three filters run on use-map entries, in order:

  1. is_likely_namespace_not_class. Checks all four class sources (uri_classes_index, fqn_uri_index, stubs). If the FQN is found in any of them, it is a real class and passes. If not found, the function looks for positive namespace evidence: is the FQN declared as a namespace in file_namespaces, or do known classes exist under it as a prefix (e.g. Cassandra\Exception\AlreadyExistsException proves Cassandra\Exception is a namespace)? If positive evidence is found, the entry is rejected. If there is no evidence either way, the entry passes (benefit of the doubt).

  2. matches_context_or_unloaded. If the class is loaded in uri_classes_index, applies exact kind filtering. If not loaded but present in stub_index, scans the stub source for the declaration keyword. If truly unknown, allows through. This catches stub interfaces appearing in TraitUse and similar mismatches.

  3. is_known_class_like (narrow contexts only). For contexts that expect a very specific kind (TraitUse, Implements, ExtendsInterface), an additional check rejects use-map entries whose FQN cannot be found in any class source at all. The reasoning: if we are looking specifically for traits and we have never seen this FQN anywhere, it is almost certainly not a trait. This is deliberately not applied to broader contexts like New or Instanceof, where an imported-but-not-yet-indexed class should still appear.

The half-typed-line problem is solved at a higher level: the UseImport handler passes an empty use-map to build_class_name_completions, so the parser's misinterpretation never enters the candidate set.

UseImport Special Handling

The UseImport context (use | at top level) has several differences from other contexts:

  • FQN insertion. The insert text is always the full qualified name, not a short name. Writing use User; is invalid PHP even if User is in the current namespace. The is_fqn_prefix flag is forced to true and effective_namespace is set to None to prevent namespace-relative simplification.

  • No auto-import text edits. In other contexts, selecting a class from a different namespace generates an additional_text_edits entry that inserts a use statement. In UseImport context this would be circular (you are already writing the use statement), so no text edit is generated.

  • Semicolons. All class items get a ; appended to the insert text so accepting a completion produces use App\Models\User;.

  • Keyword hints. When the partial matches, function and const keyword items are injected with a trailing space (not a semicolon) so the user can continue typing the function or constant name.

  • Current-file exclusion. Classes defined in the cursor file are filtered out. The same applies to UseFunction (functions from the current file) and UseConst (constants from the current file).

Unloaded Stub Scanning

Many stubs are never parsed into uri_classes_index during a session. Rather than parse thousands of stub files eagerly, the LSP scans the raw PHP source on demand. detect_stub_class_kind finds the short name in the source, checks that it is preceded by a declaration keyword (class, interface, trait, enum), and extracts abstract/final modifiers. This gives accurate filtering without the cost of a full parse.

The scan handles PHP 8.2 readonly classes (final readonly class Foo) by stripping readonly before checking for abstract/final. Multi-class stub files (e.g. V8Js which declares both V8Js and V8JsException) are handled by searching for each name independently.

Naming-Convention Heuristics

When a class is not loaded and not a stub (typically a fqn_uri_index entry whose file has not been opened), the LSP has no kind information. Rather than guess, it uses naming conventions to adjust sort order via the demotion flag in sort_text:

  • Names ending in Interface or starting with I[A-Z] are demoted in ExtendsClass and New.
  • Names starting with Abstract or Base[A-Z] are demoted in Implements, ExtendsInterface, TraitUse, and New.

Demotion sets the fourth dimension of the sort key to 1, pushing the item below non-demoted items within the same match quality, tier, and affinity group. The item is never removed, because naming conventions are not reliable enough to exclude candidates entirely. A demoted exact match still ranks above every non-demoted prefix match, since match quality is the primary dimension.

Memory Overhead

The symbol_maps store is keyed by file URI, matching uri_classes_index. A typical PHP file has 100–400 navigable symbol tokens. Each SymbolSpan is ~50–100 bytes (two u32 fields plus the SymbolKind enum with a String or two), totalling ~20–40 KB per open file. Variable definition sites add ~1–3 KB. For comparison, open_files already stores the full file content (often 50–200 KB per file), so the symbol map is a small fraction of existing memory use.

Files that are not open (vendor files loaded via PSR-4 on demand) do not get a symbol map — they use the stored byte offsets from Tier 2 (which live on ClassInfo / MethodInfo / etc. in uri_classes_index).

Diagnostic Philosophy

PHPantom earns trust through two promises:

  1. Provide suggestions for everything the developer expects. Completion, hover, go-to-definition, and every other LSP feature should work on every symbol in the project with no dead spots.
  2. Stay silent on everything the developer knows works. Every diagnostic PHPantom reports must be something that is genuinely wrong, not something that is merely imprecise or unconventional. If the code runs without errors, PHPantom should not complain about it.

Most PHP developers have learned to ignore IDE errors. They have seen tools produce walls of false positives from bugs in the inference engine, mistakes in stubs, or overly strict rules applied to code that works perfectly well in production. The result is that developers treat red squiggles as noise and test in production to see if a problem is real. PHPantom exists to break that cycle. When a diagnostic appears, it must mean something. A single false positive costs more trust than ten missed true positives, because it teaches the developer to stop reading.

Type Coverage Diagnostics

The core diagnostic categories assert type coverage: can the LSP resolve every class, member, and function call in the project?

Diagnostic What it asserts
Syntax errors The file parses.
Unused imports The use-map is clean.
Unknown classes Every class reference resolves to a real class.
Unknown members Every member access resolves to a declared member.
Unknown functions Every function call resolves to a declared function.
Argument count Call sites match the target's parameter count.
Argument type mismatch Every argument's type is definitely compatible with the parameter's declared type.
Implementation errors Concrete classes satisfy their interface/abstract contracts.
Undefined variables Every variable read has a prior definition in scope.
Deprecated usage The developer is aware of deprecation.

A project that passes all of these has 100% type coverage from the LSP's perspective: every symbol is resolvable, every completion trigger produces results, and every hover shows a type.

This also serves as a deliberate division of labour with PHPStan. PHPStan only complains about missing types at levels 6, 9, and 10. PHPantom fills those gaps cheaply and immediately so PHPStan can focus on logic errors rather than fighting incomplete type information. PHPantom rejects structural problems fast (unknown class, unknown member, wrong argument count, unimplemented interface method), and PHPStan hunts for semantic bugs with full type context available.

Type Compatibility Diagnostics: Yes / No / Maybe

Argument type mismatch diagnostics (type_error.argument) go beyond coverage into type-compatibility territory. Here the risk of false positives is highest, because PHP is a dynamically typed language with pervasive implicit coercion, and real-world codebases are full of patterns that are technically imprecise but functionally correct.

Every type check is classified into one of three buckets:

  • Yes (definitely compatible). Cat passed to Animal where Cat extends Animal. No diagnostic.
  • No (definitely incompatible). array passed to int. Diagnostic reported.
  • Maybe (might work, might not). ?Carbon passed to Carbon, bare array passed to array<string>, HtmlString passed to string. No diagnostic.

Only "no" produces a diagnostic. The "maybe" bucket is deliberately wide. If there is any reasonable interpretation under which the code could work at runtime, PHPantom stays silent. Examples of "maybe":

  • Nullable to non-nullable (?Carbon to Carbon). The developer may have null-checked before the call. We cannot see the guard clause from the call site alone.
  • Bare array to typed array (array to array<string>). A bare array is untyped. It might contain strings. We cannot prove otherwise.
  • Stringable objects to string (HtmlString to string). PHP calls __toString() at runtime. We follow PHP's runtime behaviour.
  • Int to string (without strict_types). PHP coerces integers to strings in many contexts. When declare(strict_types=1) is present in the calling file, this coercion is flagged as a type error.
  • list<X> and array<int, X>. Used interchangeably in practice. array might have sequential-keys in actuality.
  • Interface to concrete subtype (CarbonInterface to Carbon). The interface is broader, but in practice the value is almost always the expected concrete type.

This conservatism is the foundation for trust. Once developers learn that PHPantom's red squiggles are never false alarms, they start paying attention to them. At that point, a stricter mode can be offered as an opt-in for teams that want more help. But the default must be: if we are not certain, we stay silent.

Analyze Command

The analyze subcommand (phpantom_lsp analyze --project-root <DIR>) runs all native diagnostics across a project in headless batch mode. It reuses the same Backend initialization pipeline as the LSP server, so results match exactly what a user sees in their editor.

The command exists so users can measure and maintain type coverage without opening files one by one. A clean run (exit code 0) means the LSP can resolve every symbol in the project. Any reported diagnostic is a spot where completion, hover, or go-to-definition will have a gap.

The batch pipeline runs in two parallel phases:

  1. Parse phase. Read every user file (discovered via PSR-4 source directories) and call update_ast to populate fqn_class_index, uri_classes_index, symbol_maps, file_imports, file_namespaces, and fqn_uri_index. After this phase, all user classes are in fqn_class_index and cross-file references resolve via O(1) hash lookup.

  2. Diagnose phase. Run all seven diagnostic collectors on every file in parallel (std::thread::scope with one chunk per CPU core). Because Phase 1 already indexed all user classes, the diagnostic phase never triggers lazy parse_and_cache_file for other user files, eliminating write-lock contention.

Output uses PHPStan's table format (with progress bar and coloured output) so the results are familiar to teams already using PHPStan. Severity filtering (--severity error|warning|all), code filtering (--code, --exclude-code) and path scoping let users focus on specific areas.

Diagnostic Worker Architecture

Diagnostics run in three independent background tokio::spawn tasks so they never block completion, hover, or signature help:

  1. Native diagnostic worker — collects fast (syntax errors, unused imports, deprecated usage) and slow (unknown classes/members/functions, argument count, implementation errors) diagnostics. Debounces at 500 ms.
  2. PHPStan worker — runs PHPStan in editor mode (--tmp-file / --instead-of). Debounces at 2 000 ms.
  3. PHPCS worker — runs PHP_CodeSniffer via phpcs --report=json with stdin piping. Debounces at 2 000 ms.
  4. PHPMD worker — runs PHP Mess Detector 3 via phpmd analyze --format=json - with stdin piping.

Native transport choice

For native diagnostics, PHPantom chooses exactly one LSP delivery model per client:

  1. Pull if supported (textDocument/diagnostic / workspace/diagnostic)
  2. Push otherwise (textDocument/publishDiagnostics)

This is intentional, not a client-specific workaround. Pull diagnostics are the newer client-driven model and are the preferred path when available. Pushing the same native diagnostics alongside pull creates two competing streams for one source of truth, which clients may merge, replace, or deduplicate differently. The server therefore treats push as a compatibility fallback for older clients rather than mixing both transports for the same native diagnostic set.

The diagnosticProvider capability itself is advertised to every client, so a tool that inspects the server's capabilities without declaring pull support sees it. Push delivery still caches each published set with a resultId, so a pull from a push client answers with what was last published instead of an empty set.

A textDocument/diagnostic pull is held until the diagnostics reflect the document's current text, since editors pull right after every didChange and some (Neovim, Emacs) do not pull the document again when the server sends workspace/diagnostic/refresh. The pull waits for startup to finish, for the edit's background parse, for the pass that parse queues, and for the pass in flight, without computing anything on the request path. In clients known to pull the document again on a refresh (VS Code and Zed, fast_phase_answers_pulls), it answers once that pass has delivered its fast phase, and the fast phase sends no refresh for it (VS Code would cancel and re-send the held pull on one); the slow phase follows through the usual refresh. Every other client's pull waits for the slow phase as well, since the protocol gives no way to tell whether the client would pull the document on that refresh. Each stage hands the URI on before letting go of it (edits_awaiting_parse, then pending_uris, then in_flight_uris on DiagnosticState), so the wait never sees a gap. A newer pull for the same document releases the held one, and shutdown or the worker stopping releases every held pull. The workspace/diagnostic pull still answers at once from the cache.

Each worker is created during initialized via clone_for_blocking, which hands it a Backend sharing the main one's BackendState, so every worker sees all mutations the main Backend makes. The PHPStan and PHPCS workers each have their own notify handle, pending-URI slot, and diagnostic cache so they run independently of each other and of the native diagnostic worker.

Non-Arc fields are snapshotted at spawn time: php_version, vendor_uri_prefixes, and vendor_dir_paths. These fields are only written during initialized (before the workers are spawned) and never change afterwards. If a future feature adds runtime PHP version changes, the workers would need to be notified or re-cloned. This invariant ("init-time fields are write-once") should be verified before adding any post-init mutation to these fields.

config is the one exception: it is wrapped in Arc<Mutex<Config>> rather than snapshotted, because it is hot-reloaded. src/indexing/watch.rs reloads it on a project's own .phpantom.toml change (via apply_watched_file_changes) and on a global config change (via global_config_watcher, a background task polling the global config file's mtime since it lives outside the workspace and no client file watcher glob can reach it). Both reloads run on a cloned Backend, so config has to be Arc-shared for the write to reach every other clone, including the long-lived one that answers LSP requests.

Re-diagnosing only the functions an edit touched

The slow native pass (type resolution for every expression) is the expensive part of each refresh. When the edit since the last pass only changed the bodies of some functions and methods, the native worker runs the slow collectors for those functions alone and keeps every other diagnostic from the previous pass, moved to its new position (src/diagnostics/incremental/). Psalm keeps diagnostics across edits the same way; PHPantom finds the edited functions by comparing the text outside the function bodies rather than with a line diff, since any edit outside a body forces a full pass anyway.

Every slow pass leaves a baseline behind: the text it diagnosed, the function bodies in it, what the file declared, and what it reported. The next pass starts from it only when:

  • The index describes the text. The file's symbol map was built from exactly the text being diagnosed (open files record a hash of their parsed text), and nothing was published while the pass ran.
  • Nothing else changed. Every publication to the workspace index bumps a counter on DiagnosticState, and each open file's own publications are counted separately, so a pass can tell its own file's edits from a change anywhere else. A configuration reload or a deleted file bumps it too.
  • Only bodies changed. Every byte outside the function and method bodies is the same: signatures, docblocks, imports, class headers, properties, constants, top-level code.
  • The declarations did not change. The parser reads a few method bodies into the class (an Eloquent relationship's related model, a casts() map), so the file's classes, functions, and constants must still compare equal.
  • Nothing else reads the edited bodies. Inference that reads a body to type a call to it (a return type the declaration leaves open, what a by-reference parameter is left holding) records the read (type_engine::body_reads), and an edit to a body an earlier pass read forces a full pass, whichever file's code asked for it. Constructors, other magic methods, and the few framework methods read straight from the source by name always force one. body_is_observable lists the paths each case mirrors.

Collectors learn which part of the file they report on from a pass-scoped filter (incremental::reports_site) they check before resolving each site, and the forward walk visits only the edited bodies. A save always runs a full pass, which also brings back in line anything an edit changed through a project-wide registry the file feeds, the way other open files catch up on save.

Any new inference that reads a function body from outside it has to report the read through body_reads::record, or be added to body_is_observable when it scans the source for a method by name. The ignored test partial_passes_match_full_passes_on_a_project edits every function body of a real project (PHPANTOM_INCREMENTAL_VERIFY_ROOT=<project>) and checks each partial pass against a full one; partial_passes_match_full_passes_on_the_diagnostics_demo does the same over examples/php in the regular suite.

Workspace diagnostics (files that are not open)

Everything above diagnoses files the user has opened. src/diagnostics/workspace.rs covers the rest of the project, off by default and enabled with [diagnostics] workspace = true: after the full background index finishes (which itself only starts after startup indexing completes), it runs the same fast/slow collectors over every unopened user file on a throttled worker pool, then runs each configured external tool once over the whole project (only when that tool has its own project-level config file, e.g. phpstan.neon). Results are stored in Backend::workspace_diags and reported through workspace/diagnostic (or pushed directly for non-pull clients). This pass never runs before the server is usable — it is chained onto the tail of the full-index task, so it can never compete with startup for CPU. Toggle with [diagnostics] workspace / workspace-external in .phpantom.toml.

Forward Walker

The forward walker (src/type_engine/variable/forward_walk/) walks method bodies top-to-bottom, building a scope of variable types at each statement boundary. It is shared by diagnostics, completion, hover, go-to-definition, and signature help.

Inside a statement, the walk follows PHP's evaluation order (forward_walk/expr.rs): each sub-expression runs on the scope the ones before it left, so a write or a check partway through an expression (($a = g()) && $a->bar(), $x instanceof Foo ? $x->foo() : null) is in force for whatever is evaluated after it. A condition also hands back what each of its outcomes proves (forward_walk/condition.rs), and the right operand of &&/||, the arms of a ternary or match, the branches of an if/elseif chain, and loop bodies run on the outcome that lets them run. A walk to the cursor answers with the scope of the innermost expression holding it, and walks to the same position within one request are shared, so asking about several variables and member paths there costs one walk.

The same walk answers which branches cannot run (forward_walk/reachability.rs): a guard whose value the source decides (a boolean literal, the logical operators over decidable operands, or a method_exists() naming one class and one method) marks its dead branches. The walker uses that to keep a dead branch out of the join after the if; the diagnostic pass collects the branches' byte ranges while the scope cache is live and drops everything the collectors reported inside one, since no collector knows on its own whether the span it is looking at can be reached.

Name Resolution

PHP class names go through resolution at parse time (resolve_parent_class_names):

  1. Fully-qualified (\Foo\Bar) → strip leading \, use as-is.
  2. In use map (Bar with use Foo\Bar;) → expand to Foo\Bar.
  3. Qualified (Sub\Bar with use Foo\Sub;) → expand first segment.
  4. Unqualified, not in use map → prepend current namespace.
  5. No namespace → keep as-is.

This runs on every name a ClassInfo extracted from a file carries: its parents, interfaces, traits and mixins, its members' native and docblock types, its @property and @method tags, and the classes its constants' initializers name. A function's types get the same treatment. Names read later, in a method body or by whoever consumes a resolved name, follow Source Names and Resolved Names.

Container invocation arguments

container_calls.rs resolves the callable passed to Tempest's invoke() and Laravel's call() through the shared type engine. Both completion and definition read its parameters; definition looks up their source spans only when requested. Container recognition checks the receiver's resolved interface and method signature, so unrelated methods with the same name retain ordinary handling.

Tempest routes

In a Tempest project, route attributes are collected alongside classes in the symbol map. Only attribute classes implementing Tempest\Router\Route contribute routes; the declaring-file index keeps requests from rescanning unrelated attributes. URI action types come from the shared PHP engine. Completion, navigation, and parameter rename consume the same route records and source ranges.

Tempest View templates

In a project that requires tempest/view or tempest/framework, files ending in .view.php are lowered by tempest/preprocessor.rs before parsing. Elsewhere the suffix is left to plain PHP, since other renderers use it too. Native PHP, echo expressions, and bound attributes become PHP in a synthetic function, with element-scoped branches and loops. They use the same parser, symbol map, and forward walker as ordinary PHP. Template imports and @var declarations remain in that PHP; no second type resolver is involved.

template/ owns coordinate translation shared with Blade. Tempest records exact copied regions because an attribute written before :foreach still runs inside the loop. Both directions use sorted indexes, and generated syntax has no source position. Blade retains its existing column anchors.

Component discovery is lazy and cached, under Composer and configured roots, with project components taking precedence over vendor components. Installed packages follow Tempest's dependency and opt-in discovery rules. tempest/configuration.rs reads discovery locations and component registrations using the shared PHP engine. PHP edits refresh configuration values; unchanged locations reuse their filesystem scans. File creation/deletion and Composer changes invalidate the catalogue. Open buffers supply current declarations. View-path spans identify the fully qualified Tempest\View\view helper; navigation resolves paths from the project, caller, and discovery roots. References compare the resolved file, since identical relative paths in two callers can name different views.

tempest/view_data.rs resolves render arguments through the shared type engine in the caller's namespace. Helpers returning a View are read under their call-site parameter types, using shared forward-walker parameter seeding and the declaration's URI. File magic constants in stored initializers retain their declaration-file value when read through inheritance or from another namespace. Custom View declarations supply the renderer proxy's $this type; only explicit view data becomes local variables. tempest/inference.rs caches these declarations before parsing, and refreshes them after indexing, saves, and changes to a view or to a file that renders one; edits to any other file skip the refresh. Indexing, saves and watcher batches recompute everything. An unsaved edit reuses the data of every other render caller, and the results of every component call whose two templates and incoming scope are unchanged, so typing in one view re-evaluates only the calls that edit reaches. A stale indexing batch cannot overwrite a lowering built with newer inferred data.

Named data arguments to view() reverse that same path lookup. Completion reads the target template's source-backed variable uses, excluding local bindings and data the call already supplies. Definition and hover use each input's first source read, with the template's normal PHP type resolution. This lookup reads only the selected template and retains no separate cache.

Component arguments are evaluated in the caller, while slot contents are lowered into isolated closures. tempest/component_context.rs resolves slot locals at the receiving component's outlet for that invocation. Component attributes override global view data without inheriting arbitrary caller locals. A work queue propagates changed scopes through component calls; recursive component inference is bounded.

Component attribute navigation maps the first variable read in the receiving view back to its source. Attribute hover uses that read's normal PHP hover, so declared and inferred types follow the same rules as the component body. Built-in tag and directive documentation is shared by source completion and hover; PHP expressions still use their copied source mappings. A tag is documented only while it resolves to the packaged component, so a project component that replaces a built-in shows nothing borrowed from Tempest.

Dynamic component selectors use the same expression engine. The work queue loads selected targets as their names become known and removes contributions when a selector changes. The dynamic wrapper's scalar attributes become strings, while objects and arrays enter the inner view's data. Literal :is names navigate to components; variables and constants keep PHP navigation.

Tempest route attributes keep their built-in prefixes precomputed. Custom route decorators are resolved once per attribute class within a request, in method-then-class order. Their decorate() bodies are read in the declaring file's namespace, including inherited and trait methods; recognized literal prefix transformations supply the same URI to completion, navigation, and parameter references without copying the route's declaration data.

Tempest model property names

Tempest database property arguments use the shared resolver to read the model from a query builder's generic type. Model helpers are recognized by their method's declaring trait, so an override keeps its own parameter handling. Completion and navigation share the same argument roles and property lookup. Composer classifies database support separately from view rendering; requiring only the database package does not lower .view.php files as templates.