Skip to main content

mir_analyzer/session/
ingest.rs

1use super::*;
2
3impl AnalysisSession {
4    /// Cheap clone of the salsa db for a read-only query. The lock is held
5    /// only for the duration of the clone, so concurrent readers never
6    /// serialize on each other or on writes for longer than the clone itself.
7    ///
8    /// **Internal API — exposes Salsa types.** Subject to change without
9    /// notice. Public consumers should use the typed query methods
10    /// ([`Self::definition_of`], [`Self::hover`], etc.) instead.
11    #[doc(hidden)]
12    pub fn snapshot_db(&self) -> MirDbStorage {
13        self.db.snapshot_db()
14    }
15
16    /// Register or update a [`crate::db::SourceFile`] salsa input and return its
17    /// handle, without running definition collection or reference recording.
18    ///
19    /// The write-path entry point for a host that drives this db's salsa inputs
20    /// directly (the LSP database-convergence path) and pulls definitions
21    /// lazily via tracked queries, rather than the eager [`Self::ingest_file`].
22    ///
23    /// **Internal API — exposes Salsa types.** Subject to change without notice.
24    #[doc(hidden)]
25    pub fn upsert_source_file(
26        &self,
27        path: Arc<str>,
28        text: Arc<str>,
29        durability: salsa::Durability,
30    ) -> crate::db::SourceFile {
31        self.db.upsert_source_file(path, text, durability)
32    }
33
34    /// Look up an existing [`crate::db::SourceFile`] handle by path.
35    ///
36    /// **Internal API — exposes Salsa types.** Subject to change without notice.
37    #[doc(hidden)]
38    pub fn lookup_source_file(&self, path: &str) -> Option<crate::db::SourceFile> {
39        self.db.lookup_source_file(path)
40    }
41
42    /// Mark a [`crate::db::SourceFile`] as removed from the workspace.
43    ///
44    /// **Internal API — exposes Salsa types.** Subject to change without notice.
45    #[doc(hidden)]
46    pub fn remove_source_file_input(&self, path: &str) {
47        self.db.remove_source_file(path);
48    }
49
50    /// Run `f` with exclusive `&mut` access to the shared salsa db, for a host
51    /// that owns additional salsa ingredients (inputs/tracked fns) on this db
52    /// and needs to create or mutate them. Held under the db write lock, so it
53    /// serialises with all other writers.
54    ///
55    /// **Internal API — exposes Salsa types.** Subject to change without notice.
56    #[doc(hidden)]
57    pub fn with_db_mut<R>(&self, f: impl FnOnce(&mut MirDbStorage) -> R) -> R {
58        let mut guard = self.db.salsa.write();
59        f(&mut guard)
60    }
61
62    /// Run `f` with shared access to the canonical (non-snapshot) salsa db,
63    /// under the read lock. For host-owned reads of off-salsa state that must
64    /// observe the live db rather than a clone.
65    ///
66    /// `f` MUST NOT run salsa queries/input reads (tracked fns, `X.field(db)`):
67    /// the shared handle has one `ZalsaLocal` query stack, so doing so races any
68    /// concurrent salsa read on this handle and aborts the process. Use
69    /// [`Self::snapshot_db`] for salsa queries.
70    ///
71    /// **Internal API — exposes Salsa types.** Subject to change without notice.
72    #[doc(hidden)]
73    pub fn with_db_ref<R>(&self, f: impl FnOnce(&MirDbStorage) -> R) -> R {
74        let guard = self.db.salsa.read();
75        f(&guard)
76    }
77
78    /// Commit a batch of reference locations from a db snapshot into the
79    /// session's shared maps.  Called by [`crate::FileAnalyzer`] and
80    /// [`crate::BatchFileAnalyzer`] after parallel body analysis to flush the pending
81    /// buffers that accumulate in worker db clones.
82    pub(crate) fn commit_ref_locs_batch(&self, locs: Vec<RefLoc>) {
83        if locs.is_empty() {
84            return;
85        }
86        let guard = self.db.salsa.read();
87        guard.commit_reference_locations_batch(locs);
88    }
89
90    /// Run a closure with read access to a database snapshot.
91    ///
92    /// **Internal API — exposes Salsa types.** Subject to change without
93    /// notice.
94    #[doc(hidden)]
95    pub fn read<R>(&self, f: impl FnOnce(&dyn MirDatabase) -> R) -> R {
96        let db = self.snapshot_db();
97        f(&db)
98    }
99
100    /// definition-collection ingestion. Updates the file's source text in the salsa db,
101    /// runs definition collection, and ingests the resulting stub slice.
102    /// Triggers stub loading on first call. Also updates the cache's reverse-
103    /// dependency graph for `file` so cross-file invalidation stays correct
104    /// across incremental edits — without rebuilding the graph from scratch.
105    ///
106    /// If `file` was previously ingested, its old definitions and reference
107    /// locations are removed first so renames / deletions don't leave stale
108    /// state in the codebase. (Without this, long-running sessions would
109    /// accumulate dead reference-location entries indefinitely.)
110    pub fn ingest_file(&self, file: Arc<str>, source: Arc<str>) {
111        self.ensure_all_stubs();
112
113        // The symbols this file defined as of its last ingest. Read from the
114        // explicit `last_ingested_symbols` map rather than re-deriving via
115        // `file_defined_symbols` (a salsa query on the `SourceFile` input):
116        // when a host drives the db directly it may have already updated that
117        // input to the new text, which would make a re-derived "old" set equal
118        // the new set and silently drop deletions.
119        let old_symbols: HashSet<Arc<str>> = self
120            .last_ingested_symbols
121            .read()
122            .get(file.as_ref())
123            .cloned()
124            .unwrap_or_default();
125
126        {
127            let mut guard = self.db.salsa.write();
128            guard.remove_file_definitions(file.as_ref());
129        }
130        let file_defs =
131            self.db
132                .collect_and_ingest_file(file.clone(), source.as_ref(), self.php_version);
133
134        // Derive this file's defined symbols from the `FileDefinitions` just
135        // computed above — do NOT re-read them via a salsa query on the shared
136        // `.salsa.read()` handle. That query (`collect_file_definitions`) borrows
137        // the handle's single `ZalsaLocal` query stack, so two concurrent
138        // `ingest_file` calls doing it would race and abort the process under
139        // debug assertions. Reusing `file_defs` needs no db access at all.
140        let new_symbols: HashSet<Arc<str>> = file_defs.defined_symbols();
141        self.last_ingested_symbols
142            .write()
143            .insert(file.as_ref().to_string(), new_symbols.clone());
144
145        // Symbols removed from this file must be tracked so dependency_graph()
146        // can still produce edges to files referencing the now-gone symbols.
147        let deleted: Vec<Arc<str>> = old_symbols.difference(&new_symbols).cloned().collect();
148        let re_added: Vec<Arc<str>> = new_symbols.difference(&old_symbols).cloned().collect();
149        if !deleted.is_empty() {
150            // A deleted symbol may unshadow a lazy-loadable one (e.g. a vendor
151            // class with the same FQCN); prepared files must re-run warm-up.
152            self.bump_prepare_generation();
153        }
154        if !deleted.is_empty() || !re_added.is_empty() {
155            let mut stale = self.stale_defined_symbols.write();
156            let entry = stale.entry(file.as_ref().to_string()).or_default();
157            for sym in deleted {
158                entry.insert(sym);
159            }
160            for sym in &re_added {
161                entry.remove(sym);
162            }
163            if entry.is_empty() {
164                stale.remove(file.as_ref());
165            }
166        }
167
168        self.update_reverse_deps_for(&file);
169        // Evict cached analysis results for files that depend on this one so
170        // that the next re_analyze_file call re-analyses them rather than
171        // replaying a stale cache entry. Mirrors the eviction in
172        // `re_analyze_file` (batch.rs) but applies to the ingest path used by
173        // LSP servers that edit a single file without re-analysing it.
174        if let Some(cache) = self.cache.as_deref() {
175            cache.evict_with_dependents(&[file.to_string()]);
176        }
177        // Only evict cache entries whose resolver-mapped path equals this
178        // file. FQCNs the resolver can't map (psr4 miss) stay cached — no
179        // ingest could change their fate. Avoids the per-keystroke storm
180        // where wholesale clearing forces every unresolved FQCN to re-hit
181        // the resolver on the next FileAnalyzer iteration.
182        self.evict_unresolvable_for_file(&file);
183
184        // If the workspace symbol index singleton has already been built, keep
185        // it consistent with this edit *incrementally*: subtract the file's old
186        // declarations and add its new ones (tier-aware). Body-only edits are a
187        // no-op inside `update_workspace_index_for_file` (name-only
188        // FileDeclarations equality → no singleton write → the HIGH-durability
189        // dep does not invalidate body-analysis memos). Only the rare ambiguous
190        // case (a removed name still declared by another file, where this file
191        // owned the winning entry) falls back to a full O(N) rebuild.
192        {
193            let mut guard = self.db.salsa.write();
194            if guard.workspace_symbol_index_singleton().is_some() {
195                if let Some(sf) = guard.lookup_source_file(file.as_ref()) {
196                    if !guard.update_workspace_index_for_file(sf) {
197                        guard.rebuild_workspace_symbol_index();
198                    }
199                }
200            }
201        }
202    }
203
204    /// Register `source` as the text of `file` in the salsa input layer **without**
205    /// parsing or running definition collection.
206    ///
207    /// This is the LSP-friendly bulk-population entry point: after a workspace
208    /// scan, callers can feed every discovered file's text to the session
209    /// cheaply (an Arc clone plus a HashMap insert per file). Name resolution
210    /// then happens on demand via [`Self::load_class`], which reads
211    /// the file from disk through the configured [`crate::ClassResolver`] and
212    /// runs definition collection lazily when a class FQCN actually needs to resolve.
213    ///
214    /// Contrast with [`Self::ingest_file`], which eagerly parses, runs definition collection,
215    /// and populates the symbol index. Use `ingest_file` for files the user is
216    /// actively editing (where in-memory text diverges from disk); use
217    /// `set_file_text` for files known only through the workspace scan.
218    ///
219    /// Clears the negative cache: a previously-unresolvable FQCN may now
220    /// resolve if its defining file is among the newly-registered set.
221    pub fn set_file_text(&self, file: Arc<str>, source: Arc<str>) {
222        {
223            let mut guard = self.db.salsa.write();
224            guard.upsert_source_file(file.clone(), source);
225        }
226        self.evict_unresolvable_for_file(&file);
227    }
228
229    /// Bulk-register vendor / library files with HIGH salsa durability.
230    ///
231    /// HIGH-durability files are not expected to change during the session.
232    /// When a LOW-durability project file is edited, salsa can skip O(N)
233    /// dependency verification for every HIGH-durability file, reducing
234    /// `workspace_symbol_index` re-verification cost to O(project files only).
235    ///
236    /// Definition collection runs lazily on first symbol access; no parsing at call time.
237    pub fn set_vendor_files<I>(&self, files: I)
238    where
239        I: IntoIterator<Item = (Arc<str>, Arc<str>)>,
240    {
241        let mut guard = self.db.salsa.write();
242        for (file, source) in files {
243            guard.upsert_source_file_with_durability(file, source, salsa::Durability::HIGH);
244        }
245    }
246
247    /// Build or refresh the `WorkspaceSymbolIndexSingleton` from all currently
248    /// registered files.
249    ///
250    /// After this call, `find_class_like`, `find_function`, and
251    /// `find_global_constant` read `singleton.index(db)` — a single
252    /// `Durability::HIGH` tracked dep — instead of recomputing the full
253    /// O(N_files) dep list via `workspace_symbol_index`. On subsequent
254    /// LOW-durability (project-file) body edits the dep short-circuits in O(1).
255    ///
256    /// Call this once after all vendor + stub + project files have been
257    /// ingested (end of workspace warm-up). Also called automatically by
258    /// [`Self::ingest_file`] when a file's declared names change.
259    pub fn rebuild_workspace_symbol_index(&self) {
260        self.db.salsa.write().rebuild_workspace_symbol_index();
261    }
262
263    /// Bulk variant of [`Self::set_file_text`]. Acquires the salsa write lock
264    /// once for the entire batch instead of once per file.
265    ///
266    /// The intended LSP scan loop is:
267    /// ```text
268    /// let files: Vec<_> = walk_workspace()
269    ///     .map(|path| (path, fs::read(&path).unwrap()))
270    ///     .collect();
271    /// session.set_workspace_files(files);
272    /// ```
273    /// After this call, every file's source text is known to salsa. No
274    /// parsing has happened yet — Definition collection runs per file on the first
275    /// `load_class` that needs to consult it.
276    pub fn set_workspace_files<I>(&self, files: I)
277    where
278        I: IntoIterator<Item = (Arc<str>, Arc<str>)>,
279    {
280        let registered_paths: Vec<Arc<str>> = {
281            let mut guard = self.db.salsa.write();
282            files
283                .into_iter()
284                .map(|(file, source)| {
285                    guard.upsert_source_file(file.clone(), source);
286                    file
287                })
288                .collect()
289        };
290        if !registered_paths.is_empty() && self.resolver.is_some() {
291            self.evict_unresolvable_for_files(&registered_paths);
292        }
293    }
294
295    /// The workspace generation epoch — the rust-analyzer-style "are we up to
296    /// date" counter. Bumped whenever a file is added or removed. A consumer
297    /// records this alongside the diagnostics it publishes for a file; when the
298    /// value later advances (background indexing registered more files), those
299    /// files become candidates for re-analysis + re-publish.
300    pub fn index_generation(&self) -> u64 {
301        self.db.salsa.read().workspace_revision_value()
302    }
303
304    /// Index one bounded chunk of `(path, text)` files — the chunked background
305    /// indexing primitive.
306    ///
307    /// For each chunk this: (1) registers the files as `Durability::HIGH` salsa
308    /// inputs in one short write window, (2) parses them to prime the in-process
309    /// and on-disk declaration caches (in parallel when `parallelism ==
310    /// `[`IndexParallelism::Rayon`]; sequentially for wasm / single-thread
311    /// consumers), and (3) merges their declarations into the workspace symbol
312    /// index singleton **incrementally** (no full rebuild) so partially-indexed
313    /// symbols resolve immediately.
314    ///
315    /// The library spawns no thread: the consumer pumps chunks from its own
316    /// driver (LSP worker thread, or one chunk per wasm event-loop tick),
317    /// re-checking higher-priority work between calls. `cancel` is honoured at
318    /// chunk boundaries so an edit can abandon queued indexing cheaply.
319    ///
320    /// **Contract:** index the workspace *incrementally* through this method;
321    /// don't bulk-register the entire file set up front and then index — the
322    /// first call lazily seeds the singleton from the currently-registered set
323    /// (built-in stubs + this chunk), so keeping that initial set small keeps
324    /// the first call cheap. Call [`Self::finalize_index`] once after the last
325    /// chunk to reconcile authoritatively.
326    ///
327    /// **Responsiveness:** parsing / declaration collection happens off the
328    /// salsa write lock (on a snapshot); only the cheap symbol-map merge runs
329    /// under the lock, so the write window per chunk is short and an interactive
330    /// read on another thread blocks at most that long. Note that, per salsa's
331    /// snapshot model, a *cancellable query* in flight on another thread (e.g.
332    /// `hover`, `definition_of`, `FileAnalyzer::analyze`) when this batch takes
333    /// the write lock may unwind with `salsa::Cancelled`; a multi-threaded
334    /// consumer should catch that and retry the request (the rust-analyzer
335    /// pattern). A single-threaded consumer that interleaves requests *between*
336    /// `index_batch` calls never observes cancellation.
337    pub fn index_batch(
338        &self,
339        files: &[(Arc<str>, Arc<str>)],
340        parallelism: crate::IndexParallelism,
341        cancel: &crate::IndexCancel,
342    ) -> crate::IndexBatchOutcome {
343        if files.is_empty() || cancel.is_cancelled() {
344            return crate::IndexBatchOutcome {
345                registered: 0,
346                cancelled: cancel.is_cancelled(),
347                generation: self.index_generation(),
348            };
349        }
350        self.ensure_all_stubs();
351
352        // 1. Register the chunk as HIGH-durability inputs — one short write
353        //    window, then release the lock so interactive requests interleave.
354        let sources: Vec<crate::db::SourceFile> = {
355            let mut guard = self.db.salsa.write();
356            files
357                .iter()
358                .map(|(file, source)| {
359                    guard.upsert_source_file_with_durability(
360                        file.clone(),
361                        source.clone(),
362                        salsa::Durability::HIGH,
363                    )
364                })
365                .collect()
366        };
367        let registered = sources.len();
368
369        if cancel.is_cancelled() {
370            return crate::IndexBatchOutcome {
371                registered,
372                cancelled: true,
373                generation: self.index_generation(),
374            };
375        }
376
377        // Is this the seed chunk (no singleton yet)? If so we must collect decls
378        // for the whole currently-registered set (stubs + this chunk); otherwise
379        // just this chunk.
380        let seed = self
381            .db
382            .salsa
383            .read()
384            .workspace_symbol_index_singleton()
385            .is_none();
386        let snap = self.db.snapshot_db();
387        let to_collect: Vec<crate::db::SourceFile> = if seed {
388            snap.all_source_files()
389        } else {
390            sources.clone()
391        };
392
393        // 2. Collect per-file declarations OFF the write lock (on a snapshot).
394        //    This is where parsing happens — crucially NOT while holding the
395        //    write lock, so concurrent interactive reads are not blocked for the
396        //    parse duration. Also primes the shared parse/disk caches.
397        let collect_one = |db: &crate::db::MirDbStorage, sf: crate::db::SourceFile| {
398            (sf, crate::db::collect_file_declarations(db, sf))
399        };
400        let decls: Vec<(crate::db::SourceFile, crate::db::FileDeclarations)> =
401            if parallelism == crate::IndexParallelism::Rayon {
402                use rayon::prelude::*;
403                to_collect
404                    .par_iter()
405                    .map_with(snap.clone(), |db, &sf| collect_one(db, sf))
406                    .collect()
407            } else {
408                to_collect
409                    .iter()
410                    .map(|&sf| collect_one(&snap, sf))
411                    .collect()
412            };
413        drop(snap);
414
415        if cancel.is_cancelled() {
416            return crate::IndexBatchOutcome {
417                registered,
418                cancelled: true,
419                generation: self.index_generation(),
420            };
421        }
422
423        // 3. Apply to the singleton under a SHORT write window — only cheap map
424        //    construction / merge runs here (no parse).
425        {
426            let mut guard = self.db.salsa.write();
427            if guard.workspace_symbol_index_singleton().is_none() {
428                guard.build_workspace_index_from_decls(decls);
429            } else {
430                guard.merge_precomputed_into_workspace_index(&decls);
431            }
432        }
433
434        crate::IndexBatchOutcome {
435            registered,
436            cancelled: cancel.is_cancelled(),
437            generation: self.index_generation(),
438        }
439    }
440
441    /// Authoritative full rebuild of the workspace symbol index. Call once
442    /// after the consumer has pumped every [`Self::index_batch`] chunk (end of
443    /// warm-up) to reconcile the incrementally-merged index against the full
444    /// registered set. Cheap after indexing — every file's declarations are
445    /// already cached.
446    pub fn finalize_index(&self) {
447        self.db.salsa.write().rebuild_workspace_symbol_index();
448    }
449
450    /// Drop a file's contribution to the session: codebase definitions,
451    /// reference locations, salsa input handle, cache entry, and outgoing
452    /// reverse-dependency edges. Cache entries of *dependent* files are
453    /// also evicted (cross-file invalidation).
454    ///
455    /// Use this when a file is closed by the consumer, or before a re-ingest
456    /// of substantially changed content. (Plain re-ingest via
457    /// [`Self::ingest_file`] also drops old definitions, but does not
458    /// remove the salsa input handle — call this for full cleanup.)
459    pub fn invalidate_file(&self, file: &str) {
460        {
461            let mut guard = self.db.salsa.write();
462            guard.remove_file_definitions(file);
463            guard.remove_source_file(file);
464        }
465        // Outgoing structural edges disappear from the derived graph
466        // automatically: the file is no longer in `source_file_paths()`, so
467        // `dependency_graph()` stops iterating it.
468        // Clear stale symbol tracking for this file — it's fully gone.
469        self.stale_defined_symbols.write().remove(file);
470        self.last_ingested_symbols.write().remove(file);
471        // Declarations this file provided are gone; other prepared files may
472        // now need their warm-up re-run to lazy-load replacements.
473        self.forget_prepared(file);
474        self.bump_prepare_generation();
475        if let Some(cache) = &self.cache {
476            cache.update_reverse_deps_for_file(file, &HashSet::default());
477            cache.evict_with_dependents(&[file.to_string()]);
478        }
479        // The file is gone; cache entries that previously mapped to it stay
480        // unresolvable until the file (or another with matching symbols) is
481        // ingested again. Selective evict mirrors the ingest path.
482        self.evict_unresolvable_for_file(file);
483        // Vendor files are static in the eager-index model — closing a project
484        // buffer never evicts them (no per-file pinning). Memory is bounded by
485        // the LRU on `collect_file_definitions` and the parse cache instead.
486    }
487
488    /// Number of files currently tracked in this session's salsa input set.
489    /// Stable across reads; useful for diagnostics and memory bounds checks.
490    pub fn tracked_file_count(&self) -> usize {
491        let guard = self.db.salsa.read();
492        guard.source_file_count()
493    }
494
495    // -----------------------------------------------------------------------
496    // Read-only codebase queries
497    //
498    // All take a brief lock to clone the db, then run the lookup against the
499    // owned snapshot — concurrent edits proceed without blocking.
500    // -----------------------------------------------------------------------
501}