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