Skip to main content

DocumentStore

Struct DocumentStore 

Source
pub struct DocumentStore { /* private fields */ }

Implementations§

Source§

impl DocumentStore

Source

pub const WARM_SWEEP_MAX_FILES: usize = 16_384

Upper bound on files an analysis warm sweep will process. Each warmed analyze_file memo costs ~50 KiB resident (measured on the Laravel fixture), so an unbounded sweep on a very large workspace would trade too much memory for latency; beyond the cap the references path simply stays lazy for the excess files. Matches mir’s analyze_file lru = 16384 — sweeping more than the memo table holds would evict the sweep’s own tail.

Source

pub fn new() -> Self

Source

pub fn interactive_read_guard(&self) -> InteractiveReadGuard<'_>

Mark an interactive read (a request the user is waiting on) as in flight for the guard’s lifetime. Background bulk writers poll Self::yield_to_interactive_reads between files and pause while any guard is live, giving the read a write-free window to complete.

Source

pub fn settled_write_rev_guard(&self) -> (InteractiveReadGuard<'_>, u64)

Take an interactive-read guard, wait (bounded ~50 ms) for in-flight background writes to go quiet, and return the settled write revision.

For user-facing sweeps that abort when Self::write_rev advances: snapshotting the revision this way ensures only genuine user edits — not the background scan the guard just paused — void the sweep. Sleeps; call from a blocking thread only.

Source

pub fn yield_to_interactive_reads(&self)

Pause the calling (background-writer) thread while interactive reads are in flight, up to 500 ms per call. Bounded so a wedged reader can only slow the scan, never stop it; callers invoke this per file, so sustained interactive traffic keeps yielding at each boundary.

Source

pub fn begin_reanalyze(&self) -> IndexCancel

Install a fresh cancel token for a dependent-diagnostics sweep, cancelling whichever sweep was previously in flight. Pass the returned token to reanalyze_dependents_cancellable; when a newer edit calls this again the old token flips and that older sweep stops at its next file boundary instead of racing this one to publish stale diagnostics.

Source

pub fn begin_warm_sweep(&self) -> IndexCancel

Install a fresh cancel token for an analysis warm sweep, cancelling any sweep previously in flight. Mirrors Self::begin_reanalyze but on a separate slot: edit-triggered diagnostic sweeps and background warming must not cancel each other.

Source

pub fn warm_analysis_sweep(&self, priority: &[Url], cancel: &IndexCancel)

Drive every workspace file through mir’s memoized analyze_file query so later reference/rename requests are memo hits instead of cold analyses (~20 ms per file on real code — a few hundred candidate files makes an interactive request take seconds).

priority files (and the files declaring the classes they reference — the user’s working set) are warmed first, so requests against open files go warm within the sweep’s first seconds even on workspaces where the full sweep takes much longer.

Background-priority: processes files in small chunks, yielding to interactive reads at each boundary, and stops at the next boundary once cancel flips. Re-running after edits is cheap — unaffected files revalidate via salsa without re-analysis. Blocking; call from spawn_blocking.

Source

pub fn warm_sweeps_completed(&self) -> u64

Warm sweeps that ran to completion. See $/php-lsp/debugStats.

Source

pub fn mark_index_ready(&self)

Mark the workspace reference index as fully built. Called by the scan when its final phase completes (alongside $/php-lsp/indexReady).

Source

pub fn is_index_ready(&self) -> bool

Whether the workspace reference index has finished building.

Source

pub fn write_rev(&self) -> u64

Snapshot of the write-revision counter. Long-running reads should capture this before starting and pass it to cancellable operations; if the counter advances, those operations abort and return empty rather than looping indefinitely against a newly-invalidated database.

Source

pub fn set_session_cache_dir(&self, dir: PathBuf)

Set the directory used to persist stub-parse and analysis results across server restarts. Must be called before the first analysis_session use; subsequent calls are silently ignored (OnceLock semantics).

Source

pub fn set_autoload_uris(&self, uris: Vec<Url>)

Register URIs discovered from composer.json autoload.files entries. These PHP files define global helper functions (e.g. tap() in Laravel) that are not class-resolvable via PSR-4. Clears analysis_cache so the next per-file analysis pre-ingests them into the AnalysisSession before running mir’s FileAnalyzer.

Source

pub fn analysis_session(&self, php_version: PhpVersion) -> Arc<AnalysisSession>

Get or build the AnalysisSession for the given PHP version. Rebuilds when the version changes (e.g. user flipped config). The session owns the shared salsa db and AnalysisCache; lazy-loads vendor files via the shared PSR-4 map. Built-in stubs are not pre-loaded: mir’s prepare_ast_for_analysis ingests the stubs each analyzed file references, and [crate::types::stub_members] faults in single stub files for builtin member/hover lookups.

Source

pub fn workspace_php_version(&self) -> PhpVersion

Current PHP version tracked by the workspace input.

Source

pub fn class_subtype_urls(&self, class_fqn: &str) -> Vec<Url>

File URIs of all direct and transitive subclasses of class_fqn, resolved via mir’s inheritance graph. Returns an empty vec when the mir session hasn’t ingested the class yet (cold start, excluded paths).

Used by goto_implementation and subtypes to scope their lookups to the correct files, fixing aliased extends and FQN-qualified forms that the raw-name subtypes_of map misses.

Source

pub fn psr4_arc(&self) -> Arc<ArcSwap<Psr4Map>>

Return the Arc<ArcSwap<Psr4Map>> so callers can share it. Backend clones this arc at construction time so writes (e.g. loading composer.json on initialized) are immediately visible to PSR-4 resolution during analysis without extra plumbing.

Source

pub fn mirror_text(&self, uri: &Url, text: &str)

Mirror a file’s current text into the salsa layer. Creates the FileText input on first sight, otherwise updates text on the existing input (bumping the salsa revision so downstream queries invalidate).

Source

pub fn mirror_text_arc(&self, uri: &Url, text_arc: Arc<str>)

Like [mirror_text] but takes an already-allocated Arc<str>.

Callers that already hold an Arc<str> (e.g. ingest_from_doc reusing ParsedDoc::source_arc()) use this to avoid a second allocation and to ensure text_cache and parsed_cache hold the same Arc pointer — enabling Arc::ptr_eq validation in get_parsed_cached.

Source

pub fn seed_cached_index(&self, uri: &Url, index: Arc<FileIndex>) -> bool

Phase K2: pre-seed a FileIndex loaded from the on-disk cache onto the FileText input for uri. The next file_index call for that file returns the cached index directly, skipping parse + extract.

Must be called before any file_index(db, sf) call for this file — otherwise salsa has already memoized the fresh-parse result and setting cached_index now would only bump the revision without using the cache. In practice the workspace-scan path seeds immediately after mirror_text and before any query runs.

Returns false when uri was not mirrored (caller should mirror first); returns true on success.

Source

pub fn evict_token_cache(&self, uri: &Url)

Evict the semantic-tokens cache for uri. Called by Backend when a file is closed; diff-based tokens computed against the old revision are no longer meaningful.

Source

pub fn ingest(&self, uri: Url, text: &str)

Register a file in the salsa layer without marking it open.

Salsa’s parsed_doc query parses lazily on first read; diagnostics are populated by did_open when the editor actually opens the file.

Source

pub fn ingest_from_doc(&self, uri: Url, doc: &ParsedDoc)

Index a file using an already-parsed ParsedDoc, avoiding a second parse.

Prefer this over [ingest] when the caller already has a ParsedDoc (e.g. after running DefinitionCollector during workspace scan). Reuses the Arc<str> already owned by doc so that text_cache and SourceFile::text share the same pointer — enabling the Arc::ptr_eq fast path in get_parsed_cached on the first subsequent salsa query, without an extra Arc::from(source) allocation.

Source

pub fn remove(&self, uri: &Url)

Source

pub fn get_doc_salsa(&self, uri: &Url) -> Option<Arc<ParsedDoc>>

Salsa-backed parsed document.

Salsa-backed parsed document for any mirrored file (open or background-indexed). Returns None only when the file is not known to the store. Callers that want “only if open” should gate on Backend::open_files at the call site (see Backend::get_doc).

Source

pub fn get_index_salsa(&self, uri: &Url) -> Option<Arc<FileIndex>>

Salsa-backed compact symbol index.

Source

pub fn get_symbol_map_salsa(&self, uri: &Url) -> Option<Arc<SymbolMap>>

Salsa-backed pre-computed symbol map (name → Vec). Memoized per revision: stable files serve from cache in O(1).

Source

pub fn other_symbol_maps( &self, uri: &Url, open_urls: &[Url], ) -> Vec<(Url, Arc<SymbolMap>)>

Pre-computed symbol maps for every entry in open_urls except uri.

Source

pub fn get_doc_snapshot_or_stale(&self, uri: &Url) -> Option<Arc<ParsedDoc>>

Parsed doc for a cosmetic, cursor-triggered read (e.g. documentHighlight) that must stay responsive while the user types. Unlike Self::get_doc_salsa it never spins on the Cancelled retry loop: it tries the lock-free parsed_cache, then a bounded snapshot parse, and if a concurrent write stream keeps cancelling it, returns the last-good cached ParsedDoc (possibly one edit stale — invisible for a highlight, unlike a hang). None only when the file has never been parsed.

Source

pub fn sync_workspace_files(&self)

Refresh workspace.files to mirror the current active file set.

Skips all work when workspace_files_dirty is false (the common case after the workspace scan completes — file-set changes are rare).

Source

pub fn mark_workspace_files_dirty(&self)

Mark the workspace file set as dirty so the next sync_workspace_files call re-runs the collect/sort/compare path. Exposed for benchmarks that need to measure the dirty-path cost in isolation.

Source

pub fn set_php_version(&self, version: PhpVersion)

Update the PHP version tracked by the workspace. Salsa will invalidate all semantic_issues queries so diagnostics are re-evaluated. Skips the setter when the version hasn’t changed to avoid spurious query invalidation.

Source

pub fn session_references_to( &self, symbol: &Name, files: &[Arc<str>], cancel_rev: Option<u64>, ) -> Vec<(Arc<str>, u32, u32, u32)>

Session-backed reference lookup scoped to files. Returns (file, line, col) locations for every occurrence of symbol originating in those files, computed from the memoized analyze_file query — no ingest, no shared-index mutation, so repeated lookups don’t degrade across a session. files should be the text-pre-filtered candidate set.

Returns LSP-style 0-based line/column.

cancel_rev: when Some(rev), the loop throws salsa::Cancelled and returns empty if a concurrent write advances the write_revision counter past rev — preventing unbounded retries against a newly-invalidated db. Pass None to retain the original indefinite-retry behaviour (fast ops like single-file reads where a stale result is not a concern).

Source

pub fn method_reference_scope( &self, owner_fqn: &str, method: &str, ) -> Option<Vec<Url>>

The complete set of files a private method’s references can occur in, or None when the search must stay workspace-wide.

owner_fqn is the enclosing class at the cursor; narrowing applies only when that class directly declares method (so its MethodDef visibility is authoritative — inherited/call-site lookups fall through to None). A reference to Class::method is recorded only where analyze_file resolves an expression to that key, and analyze_file is per-source-file, so a private member — resolvable only inside the declaring class body, which lives in one file — is fully scoped to the declaring file at any indexing stage.

A protected member is reachable from the declaring class and its transitive subclasses ($this->m(), parent::m(), self::/static::), all of which live in the declaring file or a subtype file — never outside the hierarchy in valid PHP. Its scope is therefore the declaring file plus the transitive subtype files. The complete subtype set is only known once the workspace reference index finishes, so this narrowing applies only when Self::is_index_ready; before then it falls back to None (full workspace scope) so references are never under-reported.

Classes that compose traits or mixins are excluded — those inline external resolution context, so a reference could surface in another file.

Source

pub fn get_workspace_index_salsa(&self) -> Arc<WorkspaceIndexData>

Phase J: salsa-memoized aggregate workspace index.

Returns the shared Arc<WorkspaceIndexData> with flat (Url, Arc<FileIndex>) list plus pre-built classes_by_name and subtypes_of reverse maps. Used by workspace_symbols, prepare_type_hierarchy, supertypes_of, subtypes_of, and find_implementations so they don’t each rebuild the aggregate per request. Invalidates automatically when any file’s file_index changes.

Source

pub fn parse_count(&self) -> u64

Total number of real ParsedDoc parses served so far (cache misses). Surfaced via $/php-lsp/debugStats so tests can assert the references read path doesn’t parse the whole workspace.

Source

pub fn ref_index_lock_count(&self) -> u64

Times mir’s legacy RefIndex was locked on the current session. The session opts out of index maintenance (without_reference_index), so edits and reads must keep this flat. Surfaced via $/php-lsp/debugStats for the stress-test guard.

Source

pub fn source_text(&self, uri: &Url) -> Option<Arc<str>>

Return the raw source text for uri if it has been mirrored into the salsa workspace. Used by the references handler to pre-filter session results by checking whether a file mentions the owning class name.

Source

pub fn store_token_cache( &self, uri: &Url, result_id: String, tokens: Arc<Vec<SemanticToken>>, )

Cache the semantic tokens computed for a delta response. result_id is an opaque string (a hash of the token data) returned to the client.

Source

pub fn get_token_cache( &self, uri: &Url, result_id: &str, ) -> Option<Arc<Vec<SemanticToken>>>

Return the cached tokens if result_id matches the stored one.

Source

pub fn get_semantic_issues_salsa(&self, uri: &Url) -> Option<Arc<[Issue]>>

Raw semantic issues for a file, computed via mir’s session-based FileAnalyzer. The session lazy-loads dependencies via PSR-4 so the LSP no longer needs to mirror vendor up-front. Callers apply their own DiagnosticsConfig filter via crate::semantic_diagnostics::issues_to_diagnostics.

Source

pub fn cached_type_map( &self, uri: &Url, doc: &ParsedDoc, meta: Option<&PhpStormMeta>, ) -> Arc<TypeMap>

Run (or reuse) mir’s per-file body analysis, retaining the full mir_analyzer::FileAnalysis — issues and resolved symbols — across requests. Diagnostics read .issues; position features call .symbol_at(offset) for the resolved type at a cursor.

Cache hit when the entry’s captured source Arc is pointer-equal to the file’s current doc.source_arc(). A miss recomputes and overwrites, so the entry self-evicts on any content edit. Build (or reuse) the whole-doc completion crate::types::type_map::TypeMap for uri. Cache hit when the entry’s captured source Arc is pointer-equal to doc.source_arc() and the PHPStorm-meta pointer is unchanged (meta lives behind ArcSwap, so its address is stable until .phpstorm.meta.php is reloaded). A miss rebuilds and overwrites, so the entry self-evicts on any content edit.

Source

pub fn cached_analysis_if_fresh(&self, uri: &Url) -> Option<Arc<FileAnalysis>>

Cache-hit-only variant of Self::cached_analysis: returns the cached analysis when the entry is current for the file’s text, never computes. Lets async handlers take the warm path synchronously and reserve spawn_blocking for the cold path (mir Pass 1 + Pass 2 can take hundreds of ms on large files).

Source

pub fn cached_analysis(&self, uri: &Url) -> Option<Arc<FileAnalysis>>

Source

pub fn cached_analysis_cancellable( &self, uri: &Url, should_cancel: &(dyn Fn() -> bool + Sync), ) -> Option<Arc<FileAnalysis>>

Self::cached_analysis with an early exit: should_cancel is polled whenever a concurrent salsa write cancels the analysis attempt. A handler passes its write-revision staleness probe so a request made obsolete by newer typing stops burning a blocking-pool thread instead of retrying until the writer pauses — the editor re-requests anyway.

Source

pub fn docs_for(&self, open_urls: &[Url]) -> Vec<(Url, Arc<ParsedDoc>)>

Returns (uri, doc) for files currently open in the editor.

Resolve open_urls (from Backend::open_urls()) to parsed docs. Files not mirrored in the salsa layer are filtered out silently.

Source

pub fn doc_with_others( &self, uri: &Url, doc: Arc<ParsedDoc>, open_urls: &[Url], ) -> Vec<(Url, Arc<ParsedDoc>)>

(primary, doc) first, then every other open file’s parsed doc. The open_urls slice should include uri — this helper filters it out.

Source

pub fn other_docs( &self, uri: &Url, open_urls: &[Url], ) -> Vec<(Url, Arc<ParsedDoc>)>

Parsed docs for every entry in open_urls except uri.

Source

pub fn all_indexes(&self) -> Vec<(Url, Arc<FileIndex>)>

Compact symbol index for every mirrored file.

Source

pub fn cache_vendor_index(&self, uri: Url, index: Arc<FileIndex>)

Store a lazily-loaded vendor FileIndex in the session cache. Only call this for files that are not part of the normal workspace scan (i.e. vendor files loaded on-demand by PSR-4 navigation).

Source

pub fn get_vendor_index(&self, uri: &Url) -> Option<Arc<FileIndex>>

Retrieve a previously cached vendor FileIndex.

Source

pub fn other_indexes(&self, uri: &Url) -> Vec<(Url, Arc<FileIndex>)>

Same as all_indexes but excludes uri.

Source

pub fn all_docs_for_scan(&self) -> Vec<(Url, Arc<ParsedDoc>)>

Parsed documents for every mirrored file (open or background-indexed). Suitable for full-scan operations: find-references, rename, call_hierarchy, code_lens.

Source

pub fn candidate_urls_for(&self, word: &str) -> Vec<Url>

URLs of workspace files whose raw source text mentions word as a whole identifier — no parsing. Uses a precompiled memmem finder (the same needle is scanned across the whole workspace) plus a word-boundary check, so save does not match inside saveAll/unsaved; the scan runs in parallel over the file set. The references read path narrows this list by symbol visibility and hands it to mir’s per-file analyze_file, so a method lookup never materializes a ParsedDoc for the workspace.

Files whose text is not yet in text_cache are included conservatively (safe superset — never produces false negatives).

Source

pub fn candidate_docs_for(&self, word: &str) -> Vec<(Url, Arc<ParsedDoc>)>

Parsed documents limited to files whose raw source text contains word.

Self::candidate_urls_for + a salsa parse per survivor. Used by the AST-walker reference paths (constructor refs, non-method kinds) that genuinely need the parsed AST. The method reference path uses candidate_urls_for directly and avoids these parses entirely.

Files whose text is not yet in text_cache are included conservatively (safe superset — never produces false negatives).

Trait Implementations§

Source§

impl Default for DocumentStore

Source§

fn default() -> Self

Returns the “default value” for a type. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> Lookup<T> for T

Source§

fn into_owned(self) -> T

Source§

impl<T> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

impl<T> Read<Exclusive, BecauseExclusive> for T
where T: ?Sized,

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more