Skip to main content

mir_analyzer/session/
incremental.rs

1use super::*;
2
3impl AnalysisSession {
4    /// Retrieve the source text the session has registered for `file`, if
5    /// any. Returns `None` when the file has never been ingested. Used by
6    /// the parallel re-analysis path to re-feed dependents to body analysis without
7    /// the caller having to track sources independently.
8    pub fn source_of(&self, file: &str) -> Option<Arc<str>> {
9        let db = self.snapshot_db();
10        let sf = db.lookup_source_file(file)?;
11        Some(sf.text(&db).clone())
12    }
13
14    /// Re-analyze every transitive dependent of `file` in parallel.
15    ///
16    /// When the user saves a file that other files depend on (e.g. editing
17    /// a base class, an interface, or a trait), those dependents may have
18    /// new diagnostics. This method computes them in parallel using rayon
19    /// and returns the per-file analysis results so the LSP server can
20    /// publish updated diagnostics in one batch.
21    ///
22    /// Source text for dependents is retrieved from the session's salsa
23    /// inputs (set by previous `ingest_file` calls) — the caller doesn't
24    /// need to track or re-read files. Files for which the session has no
25    /// source are silently skipped (returns the analyzable subset).
26    ///
27    /// Cross-file inferred return types are resolved on demand via salsa.
28    pub fn reanalyze_dependents(&self, file: &str) -> Vec<(Arc<str>, crate::FileAnalysis)> {
29        self.reanalyze_dependents_cancellable(file, &crate::IndexCancel::new())
30    }
31
32    /// Cancellable variant of [`Self::reanalyze_dependents`].
33    ///
34    /// The consumer flips `cancel` (typically because a newer edit arrived) to
35    /// abandon the re-analysis; the flag is checked at each file boundary. Salsa
36    /// cannot unwind the plain-Rust body-analysis walk mid-flight, so a file
37    /// already in progress finishes, but no further files are started. Files
38    /// skipped due to cancellation are simply absent from the returned vec —
39    /// the consumer should drop a stale flag and start fresh work on each edit.
40    pub fn reanalyze_dependents_cancellable(
41        &self,
42        file: &str,
43        cancel: &crate::IndexCancel,
44    ) -> Vec<(Arc<str>, crate::FileAnalysis)> {
45        if cancel.is_cancelled() {
46            return Vec::new();
47        }
48
49        // Phase 1: compute dependents outside the analysis loop.
50        let dependents = self.dependency_graph().transitive_dependents(file);
51        if dependents.is_empty() {
52            return Vec::new();
53        }
54        let dependents: Vec<Arc<str>> = dependents
55            .into_iter()
56            .map(|path| Arc::from(path.as_str()))
57            .collect();
58        self.reanalyze_file_set(dependents, cancel)
59    }
60
61    /// Re-analyze an explicit file set — typically the editor's currently
62    /// open files — after an edit elsewhere in the workspace.
63    ///
64    /// This is the rust-analyzer diagnostics model: instead of computing the
65    /// edited file's transitive dependents (an O(all-ingested-files) graph
66    /// rebuild on every keystroke), the caller passes the handful of files it
67    /// actually publishes diagnostics for, and salsa memoization makes the
68    /// unaffected ones ~free — `analyze_file` re-validates each file's memo
69    /// against what actually changed and only re-executes bodies the edit
70    /// reaches. Per-edit cost is O(open files), independent of workspace size.
71    ///
72    /// Files the session has no source for are silently skipped. Cancellation
73    /// semantics match [`Self::reanalyze_dependents_cancellable`].
74    pub fn reanalyze_files_cancellable(
75        &self,
76        files: &[Arc<str>],
77        cancel: &crate::IndexCancel,
78    ) -> Vec<(Arc<str>, crate::FileAnalysis)> {
79        if cancel.is_cancelled() || files.is_empty() {
80            return Vec::new();
81        }
82        self.reanalyze_file_set(files.to_vec(), cancel)
83    }
84
85    /// Shared body of [`Self::reanalyze_dependents_cancellable`] and
86    /// [`Self::reanalyze_files_cancellable`]: warm up, analyze in parallel,
87    /// commit reference locations.
88    fn reanalyze_file_set(
89        &self,
90        files: Vec<Arc<str>>,
91        cancel: &crate::IndexCancel,
92    ) -> Vec<(Arc<str>, crate::FileAnalysis)> {
93        use rayon::prelude::*;
94
95        let dependents = files;
96
97        // Phase 2a: fault in each dependent's direct class references if the
98        // background indexer hasn't reached them yet (mirrors the FileAnalyzer
99        // warm-up behavior, avoiding transient false `UndefinedClass` during
100        // index warm-up).
101        //
102        // This runs SERIALLY and *before* the parallel analyze loop below:
103        // `prepare_ast_for_analysis` resolves and loads classes, and loading
104        // mutates the shared session salsa storage (`load_class` →
105        // `ingest_file` sets salsa inputs). Salsa input mutation cancels and
106        // blocks until every other database handle is released, so it must run
107        // with NO live snapshot in scope:
108        //
109        //  - in parallel (the v0.37.0 regression), sibling rayon workers held
110        //    live snapshot clones mid-`analyze_file`, so the first warm-up
111        //    write blocked on them forever — under high dependent fan-out this
112        //    deadlocked the whole runtime; and
113        //  - even serially, a snapshot held across the loop (e.g. one taken to
114        //    parse the dependents) blocks the very first write.
115        //
116        // `prepare_file_for_analysis` takes a *scoped* snapshot to fetch the
117        // parsed AST, drops it (the `Arc<ParseResult>` is owned), and only
118        // then warms up. Files already prepared against their current text
119        // skip the parse + AST walk entirely — hosts on the
120        // `ingest_file_prepared` write path pre-pay this per edit, making the
121        // whole loop a map-lookup sweep.
122        for file in &dependents {
123            if cancel.is_cancelled() {
124                return Vec::new();
125            }
126            self.prepare_file_for_analysis(file);
127        }
128
129        // Phase 2b: drive each dependent through the `analyze_file` tracked
130        // query in parallel. Salsa's memo validation does the real work
131        // here: after a body-only edit, a dependent whose tracked inputs are
132        // structurally unchanged (`FileDefinitions` backdating) returns its
133        // cached output without re-running body analysis — re-analysis cost
134        // scales with what actually changed, not with dependent count.
135        //
136        // The snapshot is taken AFTER the warm-up above so each worker observes
137        // the freshly-loaded classes. This loop is read-only on salsa: no
138        // worker mutates inputs, so the snapshots never contend on a write.
139        //
140        // Dependents' `FileAnalysis::symbols` are empty on this path:
141        // per-expression symbols are intentionally not memoized (a typical
142        // file resolves thousands; caching them balloons memory), and
143        // diagnostics consumers don't read them. Hover / go-to-definition
144        // flows analyze the open file directly via [`crate::FileAnalyzer`].
145        //
146        // Each worker short-circuits when cancellation has been requested.
147        // Generation before the snapshot: a file add racing the sweep leaves
148        // the commits stale (self-healing), never wrongly fresh.
149        let commit_gen = self.index_generation();
150        // Freeze on the pass-scoped snapshot: warm-up (2a) completed every
151        // lazy load, and a concurrent index write cancels the pass, so the
152        // frozen view is never stale. Same discipline as the batch body pass.
153        let mut db_main = self.snapshot_db();
154        db_main.freeze_workspace_index();
155        // Sweeps are the steady-state population path for the mention index:
156        // every analyzed file gets a current mention scan alongside its
157        // postings, so later reference-gate checks are set lookups.
158        let mention_scanner = db_main.class_mention_scanner();
159        type Analyzed = (
160            Arc<str>,
161            Arc<str>,
162            std::sync::Arc<crate::db::AnalyzeOutput>,
163            Vec<crate::db::SubtypeEntry>,
164            Option<super::RefCachePut>,
165            Option<Box<[mir_types::Name]>>,
166        );
167        let mut results: Vec<Analyzed> = dependents
168            .into_par_iter()
169            .map_with(db_main, |db, file| {
170                if cancel.is_cancelled() {
171                    return None;
172                }
173                let sf = db.lookup_source_file(file.as_ref())?;
174                // Capture the text the analysis ran against: the freshness
175                // marks below must record exactly this Arc, so a text write
176                // racing the sweep leaves the file dirty rather than
177                // wrongly marked fresh.
178                let text = sf.text(&*db as &dyn crate::db::MirDatabase).clone();
179                let out = crate::db::analyze_file(&*db as &dyn crate::db::MirDatabase, sf).clone();
180                let defs =
181                    crate::db::collect_file_definitions(&*db as &dyn crate::db::MirDatabase, sf);
182                let entries = crate::db::subtype_index::entries_from_slice(&defs.slice);
183                // Stage the disk-cache write only when the postings commit
184                // below will actually rewrite — a no-op re-sweep (current
185                // commit) adds no hashing or parse-walk cost per file.
186                let put = if self.ref_commit_is_current(file.as_ref(), &text, &out) {
187                    None
188                } else {
189                    self.stage_ref_cache_put(
190                        &*db as &dyn crate::db::MirDatabase,
191                        sf,
192                        file.as_ref(),
193                        &text,
194                        &out,
195                    )
196                };
197                let mentions = mention_scanner.as_ref().and_then(|s| {
198                    (!db.class_mentions_current(file.as_ref(), &text, s.epoch()))
199                        .then(|| s.scan(&text))
200                });
201                Some((file, text, out, entries, put, mentions))
202            })
203            .flatten()
204            .collect();
205
206        // Serial commit: each dependent's output is its complete reference
207        // set, so replace rather than append. Both inverted indexes and their
208        // freshness marks update here — this is what keeps read queries
209        // lookup-shaped instead of re-validating every candidate memo.
210        // Unchanged files (same text, same memoized output) skip the rebuild
211        // entirely, so a no-op re-sweep is a pointer compare per file.
212        {
213            let guard = self.db.salsa.read();
214            for (file, text, out, entries, put, mentions) in results.iter_mut() {
215                // Pointer-identical memo ⇒ identical postings: skip the
216                // index rewrite. The mark is re-stamped unconditionally so a
217                // no-op sweep still advances the commit's generation.
218                if !self.ref_commit_is_current(file.as_ref(), text, out) {
219                    guard.set_file_reference_locations(file.as_ref(), out.ref_locs.to_vec());
220                }
221                if let (Some(s), Some(m)) = (&mention_scanner, mentions.take()) {
222                    guard.set_file_class_mentions(file, text, s.epoch(), m);
223                }
224                if let Some(put) = put.take() {
225                    self.apply_ref_cache_put(file.as_ref(), out, put);
226                }
227                self.mark_ref_committed(
228                    file,
229                    text,
230                    Some(out),
231                    commit_gen,
232                    !out.has_unresolved_names(),
233                );
234                if !self.is_defs_committed(file.as_ref(), text) {
235                    guard.set_file_class_edges(file, entries.clone());
236                    self.mark_defs_committed(file, text);
237                }
238            }
239        }
240
241        results
242            .into_iter()
243            .map(|(file, _, out, _, _, _)| {
244                (
245                    file,
246                    crate::FileAnalysis {
247                        issues: out.issues.to_vec(),
248                        symbols: Vec::new(),
249                    },
250                )
251            })
252            .collect()
253    }
254
255    /// FQCNs that `file` imports via `use` statements but that aren't yet
256    /// loaded in the session.
257    ///
258    /// Designed as the input to background prefetching: after the LSP server
259    /// Return the `use`-import alias map for a file: a list of `(alias, fqcn)`
260    /// pairs where `alias` is the local name (e.g. `"Str"`) and `fqcn` is the
261    /// fully-qualified name (e.g. `"Illuminate\\Support\\Str"`).
262    ///
263    /// Completion handlers can use this to expand a short class name written
264    /// before `::` into its FQN before looking up static members, mirroring the
265    /// same alias expansion that go-to-definition already performs via
266    /// `symbol_at` + `definition_of`.
267    ///
268    /// Returns an empty Vec if the file has not been ingested or has no use
269    /// imports.
270    pub fn class_imports(&self, file: &str) -> Vec<(Arc<str>, Arc<str>)> {
271        let db = self.snapshot_db();
272        let imports = db.file_class_imports(file);
273        imports
274            .iter()
275            .map(|(alias, fqcn)| (Arc::from(alias.as_str()), Arc::from(fqcn.as_str())))
276            .collect()
277    }
278
279    /// ingests an open buffer, it can call this and lazy-load the returned
280    /// FQCNs on a worker thread so the user's first Cmd+Click into vendor
281    /// code doesn't pay the file-read+parse cost.
282    ///
283    /// Returns an empty Vec if the file hasn't been ingested or has no
284    /// unresolved imports.
285    pub fn pending_lazy_loads(&self, file: &str) -> Vec<Arc<str>> {
286        let db = self.snapshot_db();
287        let imports = db.file_imports(file);
288        if imports.is_empty() {
289            return Vec::new();
290        }
291        let mut out = Vec::new();
292        for fqcn in imports.values() {
293            let here = crate::db::Fqcn::new(&db, *fqcn);
294            if crate::db::find_class_like(&db, here).is_some() {
295                continue;
296            }
297            if let Some(resolver) = &self.resolver {
298                if resolver.resolve(fqcn.as_str()).is_some() {
299                    out.push(Arc::from(fqcn.as_str()));
300                }
301            }
302        }
303        out
304    }
305
306    /// Convenience: synchronously lazy-load every import of `file` that
307    /// isn't already in the codebase. Returns the number successfully loaded.
308    ///
309    /// For non-blocking prefetch, call this from a worker thread:
310    ///
311    /// ```ignore
312    /// let s = session.clone();  // AnalysisSession is wrapped in Arc by callers
313    /// std::thread::spawn(move || {
314    ///     s.prefetch_imports(&file_path);
315    /// });
316    /// ```
317    ///
318    /// Uses a single shared-visited two-tier BFS across all pending imports
319    /// (see [`Self::load_classes_transitive_bounded`]) with a shallow depth so
320    /// member access on imported types type-checks without pulling in the
321    /// entire vendor tree.
322    pub fn prefetch_imports(&self, file: &str) -> usize {
323        let pending = self.pending_lazy_loads(file);
324        if pending.is_empty() {
325            return 0;
326        }
327        // Fault in each imported FQCN directly (single-file load + tier-merge).
328        // Inheritance ancestors / signature types resolve through the eagerly
329        // built workspace symbol index — no transitive walk needed here.
330        let mut loaded = 0;
331        for fqcn in &pending {
332            if self.load_class(fqcn.as_ref()).is_loaded() {
333                loaded += 1;
334            }
335        }
336        loaded
337    }
338
339    /// All class / interface / trait / enum FQCNs currently known to the
340    /// session, each paired with the file that defines them when available.
341    ///
342    /// Use this to build workspace-wide views (outline, fuzzy search, etc.).
343    /// Consumers implement their own search/match logic on top — the analyzer
344    /// only exposes the iterator.
345    pub fn all_classes(&self) -> Vec<(Arc<str>, Option<mir_types::Location>)> {
346        let db = self.snapshot_db();
347        crate::db::workspace_classes(&db)
348            .iter()
349            .filter_map(|fqcn| {
350                let here = crate::db::Fqcn::from_str(&db, fqcn.as_ref());
351                crate::db::find_class_like(&db, here)
352                    .map(|class| (fqcn.clone(), class.location().cloned()))
353            })
354            .collect()
355    }
356
357    /// All global function FQNs currently known to the session, each paired
358    /// with their declaration location when available.
359    pub fn all_functions(&self) -> Vec<(Arc<str>, Option<mir_types::Location>)> {
360        let db = self.snapshot_db();
361        crate::db::workspace_functions(&db)
362            .iter()
363            .filter_map(|fqn| {
364                let here = crate::db::Fqcn::from_str(&db, fqn.as_ref());
365                crate::db::find_function(&db, here).map(|f| (fqn.clone(), f.location.clone()))
366            })
367            .collect()
368    }
369
370    /// Compute `file`'s outgoing dependency edges and persist them to the
371    /// disk cache's reverse-dep graph (if configured). The in-memory graph
372    /// is no longer maintained imperatively: `dependency_graph()` derives
373    /// structural edges from the memoized [`crate::db::file_structural_deps`]
374    /// tracked query, so there is no second copy to drift out of sync.
375    pub(super) fn update_reverse_deps_for(&self, file: &str) {
376        if let Some(cache) = self.cache.as_deref() {
377            let db = self.snapshot_db();
378            let targets = file_outgoing_dependencies(&db, file, true);
379            cache.update_reverse_deps_for_file(file, &targets);
380        }
381    }
382
383    /// File dependency graph: which files depend on which other files.
384    /// Used for incremental invalidation in LSP servers and build systems.
385    ///
386    /// File dependency graph: which files depend on which other files.
387    /// Used for incremental invalidation in LSP servers and build systems.
388    ///
389    /// O(edges) — iterates the `file_references` forward index (file → symbol
390    /// keys it references) which is always current, then resolves each symbol
391    /// to its defining file via O(1) lookup.  Total cost is O(E) where E is the
392    /// number of (file, symbol) reference edges, vs. the old O(F × S × R) scan.
393    pub fn dependency_graph(&self) -> crate::DependencyGraph {
394        let db = self.snapshot_db();
395
396        let all_files: Vec<String> = db
397            .source_file_paths()
398            .iter()
399            .map(|f| f.as_ref().to_string())
400            .collect();
401
402        let mut dependencies: HashMap<String, Vec<String>> = HashMap::default();
403        let mut dependents: HashMap<String, Vec<String>> = HashMap::default();
404
405        for file in &all_files {
406            // O(degree(file)) — forward index lookup, no full-table scan.
407            let symbol_keys = db.file_referenced_symbols(file);
408            let mut file_deps: HashSet<String> = HashSet::default();
409            for symbol_key in &symbol_keys {
410                let lookup = crate::defining_file_lookup_key(symbol_key);
411                if let Some(def_file) = db.symbol_defining_file(lookup) {
412                    let def = def_file.as_ref().to_string();
413                    if &def != file {
414                        file_deps.insert(def);
415                    }
416                }
417            }
418            for dep in &file_deps {
419                dependents
420                    .entry(dep.clone())
421                    .or_default()
422                    .push(file.clone());
423                dependencies
424                    .entry(file.clone())
425                    .or_default()
426                    .push(dep.clone());
427            }
428        }
429
430        // Merge structural deps derived from definition collection. The
431        // forward pass above only captures bare-FQN references recorded
432        // during body analysis; `file_structural_deps` covers imports, class
433        // hierarchy (extends/implements/use), and type-hint-only references
434        // that never appear in file_referenced_symbols. The query is salsa-
435        // memoized, so the warm rebuild costs one map lookup per file rather
436        // than a definition walk — and there is no imperatively-maintained
437        // reverse map to drift out of sync with the definitions.
438        for file in &all_files {
439            let Some(sf) = db.lookup_source_file(file) else {
440                continue;
441            };
442            for target in crate::db::file_structural_deps(&db, sf).iter() {
443                let target = target.as_ref().to_string();
444                if &target != file {
445                    dependents
446                        .entry(target.clone())
447                        .or_default()
448                        .push(file.clone());
449                    dependencies.entry(file.clone()).or_default().push(target);
450                }
451            }
452        }
453
454        for deps in dependents.values_mut() {
455            deps.sort();
456            deps.dedup();
457        }
458        for deps in dependencies.values_mut() {
459            deps.sort();
460            deps.dedup();
461        }
462
463        // Augment with stale dependents: files referencing symbols that were
464        // deleted from their defining file. These edges disappear from the
465        // symbol_defining_file lookup but the referencing file still needs
466        // re-analysis to surface the now-broken reference.
467        {
468            let stale = self.stale_defined_symbols.read();
469            if !stale.is_empty() {
470                for (file, deleted_syms) in stale.iter() {
471                    for sym in deleted_syms {
472                        let lookup = crate::defining_file_lookup_key(sym);
473                        // `defined_symbols()` only yields top-level FQ names
474                        // (classes/interfaces/traits/enums, functions, global
475                        // constants) — never knows here which kind `sym` was,
476                        // so probe every prefix the reference index actually
477                        // uses (see `Name::codebase_key`) rather than guessing
478                        // one and silently missing referencers of the others.
479                        for prefix in ["cls:", "fn:", "gcnst:"] {
480                            for referencing_file in
481                                db.symbol_referencers_of(&format!("{prefix}{lookup}"))
482                            {
483                                let ref_file = referencing_file.as_ref().to_string();
484                                if &ref_file != file {
485                                    dependents
486                                        .entry(file.clone())
487                                        .or_default()
488                                        .push(ref_file.clone());
489                                    dependencies.entry(ref_file).or_default().push(file.clone());
490                                }
491                            }
492                        }
493                    }
494                }
495                // Re-sort and dedup since we may have added entries.
496                for deps in dependents.values_mut() {
497                    deps.sort();
498                    deps.dedup();
499                }
500                for deps in dependencies.values_mut() {
501                    deps.sort();
502                    deps.dedup();
503                }
504            }
505        }
506
507        crate::DependencyGraph {
508            dependencies,
509            dependents,
510        }
511    }
512}