Skip to main content

mir_analyzer/batch/
run.rs

1use super::*;
2
3impl AnalysisSession {
4    /// Run the full batch analysis pipeline on a set of file paths.
5    pub fn analyze_paths(&self, paths: &[PathBuf], opts: &BatchOptions) -> AnalysisResult {
6        let php_version = self.batch_php_version(opts);
7        let mut all_issues = Vec::new();
8        let _t0 = std::time::Instant::now();
9
10        // ---- Load PHP built-in stubs (before definition collection so user code can override)
11        self.load_batch_stubs(php_version);
12        // Index vendor autoload.files (global function/constant helpers such as
13        // Laravel's `confirm()`, `select()`, etc.) before body analysis so
14        // calls to these functions resolve rather than emitting UndefinedFunction.
15        self.ensure_vendor_eager_functions();
16        let _t_stubs = _t0.elapsed();
17
18        // ---- Read files in parallel ----------------------------------
19        let parsed_files: Vec<ParsedProjectFile> = paths
20            .par_iter()
21            .filter_map(|path| match std::fs::read_to_string(path) {
22                Ok(src) => {
23                    let file = Arc::from(path.to_string_lossy().as_ref());
24                    Some(ParsedProjectFile::new(file, Arc::from(src)))
25                }
26                Err(e) => {
27                    eprintln!("Cannot read {}: {}", path.display(), e);
28                    None
29                }
30            })
31            .collect();
32        let _t_read = _t0.elapsed();
33
34        let file_data: Vec<(Arc<str>, Arc<str>)> = parsed_files
35            .iter()
36            .map(|parsed| (parsed.file.clone(), parsed.source.clone()))
37            .collect();
38
39        // ---- Detect files deleted since the last run ------------------------
40        // A file analyzed previously but now gone from disk leaves dependents
41        // holding results that assume its definitions still exist. (A file
42        // merely absent from this run's path set but still on disk is NOT a
43        // deletion — checking disk existence avoids evicting during partial-path
44        // analysis.) Drop their own entries here; dependent eviction happens
45        // below, once per-file surface fingerprints are known.
46        //
47        // `topology_changed` tracks whether this run touched the cache (any file
48        // changed, added, or removed). When nothing changed, the reverse-dep
49        // graph loaded from disk is still accurate, so the rebuild + full
50        // cache.bin rewrite at the end of this pass is skipped.
51        let mut topology_changed = false;
52        let mut removed_files: Vec<String> = Vec::new();
53        if let Some(cache) = &self.cache {
54            let current: rustc_hash::FxHashSet<&str> =
55                file_data.iter().map(|(f, _)| f.as_ref()).collect();
56            removed_files = cache
57                .cached_files()
58                .into_iter()
59                .filter(|f| !current.contains(f.as_str()) && !std::path::Path::new(f).exists())
60                .collect();
61            for f in &removed_files {
62                cache.evict(f);
63            }
64            topology_changed = !removed_files.is_empty();
65        }
66
67        // ---- Register Salsa source inputs for incremental follow-up calls ----
68        {
69            let mut guard = self.db.salsa.write();
70            for parsed in &parsed_files {
71                guard.upsert_source_file(parsed.file.clone(), parsed.source.clone());
72            }
73        }
74        let _t_salsa_reg = _t0.elapsed();
75
76        // ---- Definition collection from the already-parsed AST -------
77        // Returns (FileDefinitions, content_hash, has_hard_parse_errors) so we
78        // can prime the parse cache before the pre-warm loop below.
79        type Pass1Entry = (FileDefinitions, [u8; 32], bool, String);
80        let file_defs: Vec<Pass1Entry> = parsed_files
81            .par_iter()
82            .map(|parsed| {
83                let content_hash = hash_source(parsed.source());
84                let has_hard_parse_errors = parsed
85                    .errors()
86                    .iter()
87                    .any(crate::parser::is_hard_parse_error);
88                let mut all_issues: Vec<Issue> = parsed
89                    .errors()
90                    .iter()
91                    .filter(|err| !crate::parser::is_spurious_reserved_class_error(err))
92                    .map(|err| {
93                        crate::parser::parse_error_to_issue(
94                            err,
95                            &parsed.file,
96                            parsed.source(),
97                            parsed.source_map(),
98                        )
99                    })
100                    .collect();
101                let collector = crate::collector::DefinitionCollector::new_for_slice(
102                    parsed.file.clone(),
103                    parsed.source(),
104                    parsed.source_map(),
105                );
106                let (mut slice, collector_issues) = collector.collect_slice(parsed.owned());
107                all_issues.extend(collector_issues);
108                mir_codebase::definitions::deduplicate_params_in_slice(&mut slice);
109                let defs = FileDefinitions {
110                    slice: Arc::new(slice),
111                    issues: Arc::new(all_issues),
112                };
113                let surface_hash = surface_fingerprint(parsed.source(), parsed.owned());
114                (defs, content_hash, has_hard_parse_errors, surface_hash)
115            })
116            .collect();
117        let _t_collect_defs = _t0.elapsed();
118
119        // Pair each file with its cross-file surface fingerprint (par_iter().map
120        // preserves order, so file_defs aligns with parsed_files).
121        let surface_hashes: HashMap<Arc<str>, String> = parsed_files
122            .iter()
123            .zip(file_defs.iter())
124            .map(|(parsed, (_defs, _h, _e, surface))| (parsed.file.clone(), surface.clone()))
125            .collect();
126
127        // Hex content hashes derived from the pass-1 digests, so the
128        // content-changed pass and the body pass below don't re-hash every
129        // source file (BLAKE3 over all bytes, twice).
130        let content_hexes: HashMap<Arc<str>, String> = parsed_files
131            .iter()
132            .zip(file_defs.iter())
133            .map(|(parsed, (_defs, hash, _e, _surface))| {
134                (
135                    parsed.file.clone(),
136                    blake3::Hash::from(*hash).to_hex().to_string(),
137                )
138            })
139            .collect();
140        let transient_replay = self
141            .cache
142            .is_none()
143            .then(|| {
144                self.transient_batch_replay(
145                    php_version.cache_byte(),
146                    opts.skip_symbols,
147                    &content_hexes,
148                )
149            })
150            .flatten();
151
152        // ---- Cross-file invalidation: evict dependents whose surface changed --
153        // A file whose content changed re-analyzes itself regardless (its body
154        // pass misses the cache below). It cascades to dependents only when its
155        // declaration-level surface changed: a body-only edit to a declared-
156        // return callable leaves every dependent's result intact. A missing or
157        // pre-firewall (empty) stored surface is treated as unknown and cascades.
158        if let Some(cache) = &self.cache {
159            let content_changed: Vec<String> = file_data
160                .iter()
161                .filter_map(|(f, _src)| {
162                    let valid = content_hexes.get(f).is_some_and(|h| cache.is_valid(f, h));
163                    if valid {
164                        None
165                    } else {
166                        Some(f.to_string())
167                    }
168                })
169                .collect();
170            if !content_changed.is_empty() {
171                topology_changed = true;
172            }
173            let mut seeds: Vec<String> = content_changed
174                .into_iter()
175                .filter(|f| {
176                    let new_surface = surface_hashes
177                        .get(f.as_str())
178                        .map(String::as_str)
179                        .unwrap_or("");
180                    // Keep (cascade) unless the stored surface is known and equal.
181                    !matches!(
182                        cache.surface_hash(f),
183                        Some(stored) if !stored.is_empty() && stored == new_surface
184                    )
185                })
186                .collect();
187            seeds.extend(removed_files.iter().cloned());
188            if !seeds.is_empty() {
189                cache.evict_with_dependents(&seeds);
190            }
191        }
192
193        // Prime the in-process parse cache so the pre-warm loop below avoids
194        // re-parsing every project file through collect_file_definitions.
195        {
196            let guard = self.db.salsa.read();
197            let php_v = php_version.cache_byte();
198            for (defs, hash, has_hard_parse_errors, _surface) in &file_defs {
199                if !*has_hard_parse_errors {
200                    guard.prime_parse_cache(
201                        *hash,
202                        php_v,
203                        Arc::clone(&defs.slice),
204                        Arc::clone(&defs.issues),
205                    );
206                }
207            }
208        }
209
210        let mut files_with_parse_errors: HashSet<Arc<str>> = HashSet::default();
211        {
212            // Commit subtype-index class edges alongside issue collection —
213            // parity with `ingest_file`'s single-file path, so goto-implementation
214            // sees implementors from a batch/vendor run without waiting for
215            // each file to be individually touched by an on-demand commit path.
216            let guard = self.db.salsa.read();
217            for (parsed, (defs, _hash, _hard_err, _surface)) in parsed_files.iter().zip(file_defs) {
218                for issue in defs.issues.iter() {
219                    if matches!(issue.kind, mir_issues::IssueKind::ParseError { .. })
220                        && issue.severity == mir_issues::Severity::Error
221                    {
222                        files_with_parse_errors.insert(issue.location.file.clone());
223                    }
224                }
225                let entries = crate::db::subtype_index::entries_from_slice(&defs.slice);
226                guard.set_file_class_edges(&parsed.file, entries);
227                all_issues.extend(Arc::unwrap_or_clone(defs.issues));
228            }
229        }
230        let _t_ingest = _t0.elapsed();
231
232        // ---- Pre-warm collect_file_definitions for project files -------------
233        {
234            let db_prewarm = {
235                let guard = self.db.salsa.read();
236                (**guard).clone()
237            };
238            let project_source_files: Vec<SourceFile> = {
239                let guard = self.db.salsa.read();
240                parsed_files
241                    .iter()
242                    .filter_map(|p| (**guard).lookup_source_file(&p.file))
243                    .collect()
244            };
245            project_source_files
246                .into_par_iter()
247                .for_each_with(db_prewarm, |db, sf| {
248                    let _ = collect_file_definitions(db as &dyn MirDatabase, sf);
249                });
250        }
251        let _t_prewarm_ms = (_t0.elapsed() - _t_ingest).as_secs_f64() * 1000.0;
252
253        // Fold the freshly-registered project files into the workspace symbol
254        // index singleton. The singleton may have been built from vendor before
255        // this run (CLI indexes vendor before analyze_paths); since adding files
256        // no longer nulls it, project classes would otherwise be invisible to
257        // find_class_like and reported as false UndefinedClass.
258        self.refresh_workspace_index();
259
260        // ---- Lazy-load unknown classes via PSR-4 ----------------------------
261        let _t_before_lazy = _t0.elapsed();
262        if let Some(psr4) = self.psr4.clone() {
263            self.lazy_load_missing_classes(psr4, php_version, &mut all_issues);
264        }
265        let _t_lazyload_ms = (_t0.elapsed() - _t_before_lazy).as_secs_f64() * 1000.0;
266
267        // ---- Class-level checks ---------------------------------------------
268        let analyzed_file_set: HashSet<Arc<str>> =
269            file_data.iter().map(|(f, _)| f.clone()).collect();
270
271        // Definitions are all collected and indexed — fire the plugin hook
272        // (Psalm's AfterCodebasePopulated) before any body/class analysis.
273        if let Some(plugins) = mir_plugin::snapshot() {
274            if plugins.hooks().after_codebase_populated {
275                let files: Vec<Arc<str>> = analyzed_file_set.iter().cloned().collect();
276                plugins.after_codebase_populated(&mut mir_plugin::AfterCodebasePopulatedEvent {
277                    files: &files,
278                });
279            }
280        }
281        let _t_class_analyzer = std::time::Instant::now();
282        {
283            let class_db = {
284                let guard = self.db.salsa.read();
285                (**guard).clone()
286            };
287            let class_issues = crate::class::ClassAnalyzer::with_files(
288                &class_db,
289                analyzed_file_set.clone(),
290                &file_data,
291            )
292            .analyze_all();
293            all_issues.extend(class_issues);
294        }
295        let _t_class_analyzer_ms = _t_class_analyzer.elapsed().as_secs_f64() * 1000.0;
296
297        let _t_class_checks = _t0.elapsed();
298
299        let mut db_main = {
300            let guard = self.db.salsa.read();
301            (**guard).clone()
302        };
303        // All index mutation for the body pass is done (lazy_load_missing_classes
304        // + refresh ran above; lazy_load_from_body_issues runs *after* this pass
305        // on a separate db). Freeze the index on this ephemeral clone so each
306        // find_class_like borrows it instead of cloning the singleton's three
307        // Arcs per call — the per-worker `map_with` clone bumps the refcount once.
308        db_main.freeze_workspace_index();
309
310        // ---- Body analysis: function/method bodies in parallel --------------
311        type BodyResult = (
312            Arc<str>,
313            Vec<Issue>,
314            Vec<crate::symbol::ResolvedSymbol>,
315            Vec<RefLoc>,
316        );
317        let body_results: Vec<BodyResult> = parsed_files
318            .par_iter()
319            .filter(|parsed| !files_with_parse_errors.contains(&parsed.file))
320            .map_with(db_main, |db, parsed| {
321                let mut driver = BodyAnalyzer::new(&*db as &dyn MirDatabase, php_version);
322                // Diagnostics-only consumers never read the symbol vecs —
323                // don't build them (a Type clone per reference) at all.
324                driver.collect_symbols = !opts.skip_symbols;
325                if let Some(replay) = transient_replay.as_ref() {
326                    if let Some(hit) = replay.files.get(&parsed.file) {
327                        let locs: Vec<RefLoc> = hit
328                            .ref_locs
329                            .iter()
330                            .map(|(symbol, line, col_start, col_end)| RefLoc {
331                                symbol_key: Arc::clone(symbol),
332                                file: parsed.file.clone(),
333                                line: *line,
334                                col_start: *col_start,
335                                col_end: *col_end,
336                            })
337                            .collect();
338                        return (
339                            parsed.file.clone(),
340                            hit.issues.to_vec(),
341                            hit.symbols.to_vec(),
342                            locs,
343                        );
344                    }
345                }
346                let (issues, symbols) = if let Some(cache) = &self.cache {
347                    let h = content_hexes
348                        .get(parsed.file.as_ref())
349                        .cloned()
350                        .unwrap_or_else(|| hash_content(parsed.source()));
351                    if let Some((cached_issues, ref_locs)) = cache.get(&parsed.file, &h) {
352                        // Cache replay: rebuild the file's complete reference
353                        // set straight from the cached tuples — no pending-
354                        // buffer detour. Symbol keys are Arc-shared with the
355                        // cache entry, so this allocates no strings.
356                        let locs: Vec<RefLoc> = ref_locs
357                            .iter()
358                            .map(|(symbol, line, col_start, col_end)| RefLoc {
359                                symbol_key: Arc::clone(symbol),
360                                file: parsed.file.clone(),
361                                line: *line,
362                                col_start: *col_start,
363                                col_end: *col_end,
364                            })
365                            .collect();
366                        return (
367                            parsed.file.clone(),
368                            cached_issues.to_vec(),
369                            Vec::new(),
370                            locs,
371                        );
372                    }
373                    let (issues, symbols) = driver.analyze_bodies(
374                        parsed.owned(),
375                        parsed.file.clone(),
376                        parsed.source(),
377                        parsed.source_map(),
378                    );
379                    let pending = db.take_pending_ref_locs();
380                    let cache_locs: Arc<[crate::cache::CachedRefLoc]> = pending
381                        .iter()
382                        .map(|r| (Arc::clone(&r.symbol_key), r.line, r.col_start, r.col_end))
383                        .collect();
384                    let surface = surface_hashes
385                        .get(parsed.file.as_ref())
386                        .cloned()
387                        .unwrap_or_default();
388                    cache.put(
389                        &parsed.file,
390                        h,
391                        surface,
392                        issues.as_slice().into(),
393                        cache_locs,
394                    );
395                    if let Some(cb) = &opts.on_file_done {
396                        cb();
397                    }
398                    let symbols = if opts.skip_symbols {
399                        Vec::new()
400                    } else {
401                        symbols
402                    };
403                    return (parsed.file.clone(), issues, symbols, pending);
404                } else {
405                    driver.analyze_bodies(
406                        parsed.owned(),
407                        parsed.file.clone(),
408                        parsed.source(),
409                        parsed.source_map(),
410                    )
411                };
412                let pending = db.take_pending_ref_locs();
413                if let Some(cb) = &opts.on_file_done {
414                    cb();
415                }
416                // Drop the per-file symbol vec inside the worker when the
417                // consumer opted out — the orchestrator never accumulates.
418                let symbols = if opts.skip_symbols {
419                    Vec::new()
420                } else {
421                    symbols
422                };
423                (parsed.file.clone(), issues, symbols, pending)
424            })
425            .collect();
426
427        let _t_body_analysis = _t0.elapsed();
428
429        if self.cache.is_none() {
430            let replay_files: HashMap<Arc<str>, crate::session::BatchReplayFile> = body_results
431                .iter()
432                .map(|(file, issues, symbols, ref_locs)| {
433                    let cached_ref_locs: Arc<[crate::cache::CachedRefLoc]> = ref_locs
434                        .iter()
435                        .map(|r| (Arc::clone(&r.symbol_key), r.line, r.col_start, r.col_end))
436                        .collect();
437                    (
438                        file.clone(),
439                        crate::session::BatchReplayFile {
440                            issues: issues.as_slice().into(),
441                            ref_locs: cached_ref_locs,
442                            symbols: symbols.as_slice().into(),
443                        },
444                    )
445                })
446                .collect();
447            self.store_transient_batch_replay(
448                php_version.cache_byte(),
449                opts.skip_symbols,
450                &content_hexes,
451                replay_files,
452            );
453        }
454
455        // Serial commit with replace semantics: each file's output (or cache
456        // replay) is its complete reference set, so stale entries from a
457        // prior run cannot survive an append.
458        let mut all_symbols = Vec::new();
459        {
460            let guard = self.db.salsa.read();
461            for (file, issues, symbols, ref_locs) in body_results {
462                all_issues.extend(issues);
463                all_symbols.extend(symbols);
464                guard.set_file_reference_locations(file.as_ref(), ref_locs);
465            }
466        }
467
468        // ---- Post-analysis lazy loading: FQCNs used without `use` imports ------
469        if let Some(psr4) = self.psr4.clone() {
470            self.lazy_load_from_body_issues(
471                psr4,
472                php_version,
473                &file_data,
474                &files_with_parse_errors,
475                &mut all_issues,
476                &mut all_symbols,
477                opts.skip_symbols,
478            );
479        }
480
481        // ---- Build reverse dep graph and persist it for the next run ---------
482        // Must run AFTER `commit_reference_locations_batch` (above): the graph's
483        // call-site / instantiation / inferred-return edges are derived from the
484        // committed reference-location map. Built any earlier (the salsa db is
485        // fresh each session) that map is empty, so only structural edges
486        // (parent/interface/trait/declared types) survive — and any dependent
487        // reachable only through a call site or inferred type goes stale.
488        if topology_changed {
489            if let Some(cache) = &self.cache {
490                let db_snapshot = {
491                    let guard = self.db.salsa.read();
492                    (**guard).clone()
493                };
494                let rev = build_reverse_deps(&db_snapshot);
495                cache.set_reverse_deps(rev);
496            }
497        }
498
499        // Persist cache hits/misses to disk
500        if let Some(cache) = &self.cache {
501            cache.flush();
502        }
503
504        // ---- Dead-code detection -------------------------------------------
505        if opts.should_run_dead_code() {
506            let salsa = self.snapshot_db();
507            let _t_dead_code = std::time::Instant::now();
508            let dead_code_issues =
509                crate::dead_code::DeadCodeAnalyzer::with_files(&salsa, analyzed_file_set.clone())
510                    .analyze();
511            all_issues.extend(dead_code_issues);
512            if std::env::var("MIR_TIMING").is_ok() {
513                eprintln!(
514                    "[timing] dead_code_analyzer={:.0}ms",
515                    _t_dead_code.elapsed().as_secs_f64() * 1000.0
516                );
517            }
518        }
519
520        let _t_total = _t0.elapsed();
521        if std::env::var("MIR_TIMING").is_ok() {
522            eprintln!(
523                "[timing] stubs={:.0}ms read={:.0}ms salsa_reg={:.0}ms collect_defs={:.0}ms ingest={:.0}ms class_checks={:.0}ms (prewarm={:.0}ms lazy_load={:.0}ms class_analyzer={:.0}ms) body_analysis={:.0}ms total={:.0}ms",
524                _t_stubs.as_secs_f64() * 1000.0,
525                (_t_read - _t_stubs).as_secs_f64() * 1000.0,
526                (_t_salsa_reg - _t_read).as_secs_f64() * 1000.0,
527                (_t_collect_defs - _t_salsa_reg).as_secs_f64() * 1000.0,
528                (_t_ingest - _t_collect_defs).as_secs_f64() * 1000.0,
529                (_t_class_checks - _t_ingest).as_secs_f64() * 1000.0,
530                _t_prewarm_ms,
531                _t_lazyload_ms,
532                _t_class_analyzer_ms,
533                (_t_body_analysis - _t_class_checks).as_secs_f64() * 1000.0,
534                _t_total.as_secs_f64() * 1000.0,
535            );
536        }
537
538        // Plugin issue veto (Psalm's BeforeAddIssue) — applied to the final
539        // set before config-level suppression so a veto can't be shadowed.
540        if let Some(plugins) = mir_plugin::snapshot() {
541            if plugins.hooks().before_add_issue {
542                all_issues.retain(|i| plugins.before_add_issue(i));
543            }
544        }
545
546        opts.apply(&mut all_issues);
547        let analyzed_files_vec: Vec<Arc<str>> = analyzed_file_set.iter().cloned().collect();
548        self.apply_suppressions_and_emit_unused(&mut all_issues, &analyzed_files_vec);
549        if let Some(dump) = crate::metrics::dump() {
550            eprintln!("{dump}");
551        }
552
553        // ---- Build workspace symbol index singleton -------------------------
554        {
555            let mut guard = self.db.salsa.write();
556            guard.rebuild_workspace_symbol_index();
557        }
558
559        AnalysisResult::build(all_issues, rustc_hash::FxHashMap::default(), all_symbols)
560    }
561    /// Re-analyze a single file (definition collection + body analysis) within the batch context.
562    ///
563    /// Mirrors the old `ProjectAnalyzer::re_analyze_file` cache-aware path.
564    /// Use [`Self::reanalyze_dependents`] for LSP-style per-file flows that
565    /// don't need batch options.
566    pub fn re_analyze_file(
567        &self,
568        file_path: &str,
569        new_content: &str,
570        opts: &BatchOptions,
571    ) -> AnalysisResult {
572        self.clear_transient_batch_replay();
573        let php_version = self.batch_php_version(opts);
574
575        // Fast path: content unchanged and cache has a valid entry.
576        if let Some(cache) = &self.cache {
577            let h = hash_content(new_content);
578            if let Some((cached_issues, ref_locs)) = cache.get(file_path, &h) {
579                let mut issues = cached_issues.to_vec();
580                let file: Arc<str> = Arc::from(file_path);
581                // Replace semantics: the cached set is the file's complete
582                // reference set, so stale entries from a prior version are
583                // cleared rather than appended over.
584                let locs: Vec<RefLoc> = ref_locs
585                    .iter()
586                    .map(|(symbol, line, col_start, col_end)| RefLoc {
587                        symbol_key: Arc::clone(symbol),
588                        file: file.clone(),
589                        line: *line,
590                        col_start: *col_start,
591                        col_end: *col_end,
592                    })
593                    .collect();
594                let guard = self.db.salsa.read();
595                guard.set_file_reference_locations(file_path, locs);
596                drop(guard);
597                opts.apply(&mut issues);
598                self.apply_suppressions_and_emit_unused(&mut issues, std::slice::from_ref(&file));
599                return AnalysisResult::build(issues, HashMap::default(), Vec::new());
600            }
601        }
602
603        let file: Arc<str> = Arc::from(file_path);
604
605        {
606            let mut guard = self.db.salsa.write();
607            guard.remove_file_definitions(file_path);
608        }
609
610        let collected =
611            self.db
612                .collect_and_ingest_file_with_parsed(file.clone(), new_content, php_version);
613        let file_defs = collected.file_defs;
614
615        let mut all_issues: Vec<Issue> = Arc::unwrap_or_clone(file_defs.issues.clone());
616
617        {
618            let mut guard = self.db.salsa.write();
619            if guard.workspace_symbol_index_singleton().is_some() {
620                if let Some(sf) = guard.lookup_source_file(file.as_ref()) {
621                    if guard.file_declarations_changed(sf) {
622                        guard.rebuild_workspace_symbol_index();
623                    }
624                }
625            }
626        }
627
628        let (symbols, surface_hash) = {
629            let guard = self.db.salsa.write();
630            let parsed = collected
631                .parsed
632                .unwrap_or_else(|| php_rs_parser::parse(new_content));
633            let surface_hash = surface_fingerprint(new_content, &parsed.program);
634
635            let has_hard_errors = parsed.errors.iter().any(crate::parser::is_hard_parse_error);
636            let symbols = if !has_hard_errors {
637                let db_ref: &dyn MirDatabase = &**guard;
638                let mut driver = BodyAnalyzer::new(db_ref, php_version);
639                driver.collect_symbols = !opts.skip_symbols;
640                let (body_issues, symbols) = driver.analyze_bodies(
641                    &parsed.program,
642                    file.clone(),
643                    new_content,
644                    &parsed.source_map,
645                );
646                all_issues.extend(body_issues);
647                let pending = guard.take_pending_ref_locs();
648                guard.set_file_reference_locations(file.as_ref(), pending);
649                if opts.skip_symbols {
650                    Vec::new()
651                } else {
652                    symbols
653                }
654            } else {
655                Vec::new()
656            };
657            (symbols, surface_hash)
658        };
659
660        // Bake inline-suppression marks in *before* caching: suppression is a
661        // pure function of file content (and the cache key hashes content), so
662        // the cached issues should already carry their marks. The cache-hit
663        // branch above replays this file's source without re-registering the
664        // `SourceFile` input, so the db-backed post-filter cannot recompute
665        // marks there — caching the canonical result is what keeps a fresh
666        // process honoring `@mir-ignore` on an unchanged file.
667        mark_suppressed(
668            &mut all_issues,
669            &crate::suppression::SuppressionMap::from_source(new_content),
670        );
671
672        if let Some(cache) = &self.cache {
673            let h = hash_content(new_content);
674            // Cascade to dependents only when this file's cross-file surface
675            // changed; a body-only edit to a declared-return callable leaves
676            // their results valid. Unknown (absent/empty) stored surface cascades.
677            let surface_changed = match cache.surface_hash(file_path) {
678                Some(stored) if !stored.is_empty() => stored != surface_hash,
679                _ => true,
680            };
681            if surface_changed {
682                cache.evict_with_dependents(&[file_path.to_string()]);
683            }
684            let db = self.snapshot_db();
685            let ref_locs = extract_reference_locations(&db, &file);
686            cache.put(
687                file_path,
688                h,
689                surface_hash,
690                all_issues.as_slice().into(),
691                ref_locs,
692            );
693        }
694
695        opts.apply(&mut all_issues);
696        // Emit `UnusedSuppress` for named suppressions that matched nothing —
697        // present on the cache-hit branch above and on `analyze_paths`, but
698        // missing here, so every non-cached re-analysis (the actual
699        // incremental/LSP-edit pipeline) silently dropped this diagnostic.
700        // `mark_suppressed` above already baked suppression marks into what
701        // gets cached; this only adds the (uncached, always-fresh) unused-
702        // suppression pass on top, mirroring the cache-hit branch's order.
703        self.apply_suppressions_and_emit_unused(&mut all_issues, std::slice::from_ref(&file));
704        AnalysisResult::build(all_issues, HashMap::default(), symbols)
705    }
706
707    /// Collect type definitions only from `paths` into the codebase
708    /// without analyzing method bodies or emitting issues. Used to load
709    /// vendor types.
710    ///
711    /// When a disk-backed cache is attached, per-file `StubSlice` results
712    /// from previous runs are reused on a content-hash match, eliminating
713    /// the parse + definition-collection step. Cache misses run the normal
714    /// pipeline and write back so subsequent runs hit.
715    pub fn collect_definitions(&self, paths: &[PathBuf]) {
716        self.clear_transient_batch_replay();
717        let _timing = std::env::var("MIR_TIMING").is_ok();
718        let _t0 = std::time::Instant::now();
719
720        let php_v = self.php_version.cache_byte();
721
722        struct FileEntry {
723            file: Arc<str>,
724            src: Arc<str>,
725            hash: [u8; 32],
726            cached: Option<mir_codebase::definitions::StubSlice>,
727        }
728        let entries: Vec<FileEntry> = paths
729            .par_iter()
730            .filter_map(|path| {
731                let src = std::fs::read_to_string(path).ok()?;
732                let file: Arc<str> = Arc::from(path.to_string_lossy().as_ref());
733                let src: Arc<str> = Arc::from(src);
734                let hash = hash_source(&src);
735                let cached = self.db.stub_cache.as_ref().and_then(|c| {
736                    let (mut slice, _issues) = c.get(&file, &hash, php_v)?;
737                    prepare_for_ingest(&mut slice);
738                    Some(slice)
739                });
740                Some(FileEntry {
741                    file,
742                    src,
743                    hash,
744                    cached,
745                })
746            })
747            .collect();
748        let _t_read = _t0.elapsed();
749
750        let source_files: Vec<SourceFile> = {
751            let mut guard = self.db.salsa.write();
752            entries
753                .iter()
754                .map(|e| {
755                    guard.upsert_source_file_with_durability(
756                        e.file.clone(),
757                        e.src.clone(),
758                        salsa::Durability::HIGH,
759                    )
760                })
761                .collect()
762        };
763        let _t_reg = _t0.elapsed();
764
765        let db_pass1 = {
766            let guard = self.db.salsa.read();
767            (**guard).clone()
768        };
769        let stub_cache = self.db.stub_cache.clone();
770        let prepared: Vec<(Arc<str>, mir_codebase::definitions::StubSlice)> = entries
771            .into_par_iter()
772            .zip(source_files.into_par_iter())
773            .map_with(db_pass1, |db, (mut entry, salsa_file)| {
774                if let Some(slice) = entry.cached.take() {
775                    let slice_arc = Arc::new(slice);
776                    db.parse_cache().insert(
777                        entry.hash,
778                        php_v,
779                        Arc::clone(&slice_arc),
780                        Arc::new(Vec::new()),
781                    );
782                    return (entry.file.clone(), (*slice_arc).clone());
783                }
784                let defs = collect_file_definitions(&*db, salsa_file);
785                if let Some(cache) = stub_cache.as_ref() {
786                    cache.put(&entry.file, &entry.hash, php_v, &defs.slice, &defs.issues);
787                }
788                (entry.file.clone(), (*defs.slice).clone())
789            })
790            .collect();
791        let _t_collect = _t0.elapsed();
792        // Commit subtype-index class edges for the vendor tree: without this,
793        // goto-implementation can't surface implementors that live only in
794        // vendor/ (index_batch's project-file warm sweep has the same gap for
795        // project files, but no StubSlice is cheaply available there — see
796        // the persistence work tracked separately).
797        {
798            let guard = self.db.salsa.read();
799            for (file, slice) in &prepared {
800                let entries = crate::db::subtype_index::entries_from_slice(slice);
801                guard.set_file_class_edges(file, entries);
802            }
803        }
804        drop(prepared);
805        let _t_ingest = _t0.elapsed();
806
807        if _timing {
808            let (hits, misses) = self.stub_cache_stats();
809            eprintln!(
810                "[vendor] read={:.0}ms reg={:.0}ms collect={:.0}ms ingest={:.0}ms total={:.0}ms (cache hits={hits} misses={misses})",
811                _t_read.as_secs_f64() * 1000.0,
812                (_t_reg - _t_read).as_secs_f64() * 1000.0,
813                (_t_collect - _t_reg).as_secs_f64() * 1000.0,
814                (_t_ingest - _t_collect).as_secs_f64() * 1000.0,
815                _t_ingest.as_secs_f64() * 1000.0,
816            );
817        }
818
819        {
820            let mut guard = self.db.salsa.write();
821            guard.rebuild_workspace_symbol_index();
822        }
823
824        crate::collector::print_collector_stats();
825    }
826}
827
828#[cfg(test)]
829mod tests {
830    use rustc_hash::FxHashMap as HashMap;
831    use std::fs;
832    use std::sync::{Arc, Mutex, OnceLock};
833
834    use crate::{AnalysisSession, BatchOptions, PhpVersion};
835
836    fn metrics_test_lock() -> &'static Mutex<()> {
837        static LOCK: OnceLock<Mutex<()>> = OnceLock::new();
838        LOCK.get_or_init(|| Mutex::new(()))
839    }
840
841    fn write_php(dir: &tempfile::TempDir, name: &str, contents: &str) -> std::path::PathBuf {
842        let path = dir.path().join(name);
843        fs::write(&path, contents).expect("write fixture");
844        path
845    }
846
847    #[test]
848    fn identical_batch_rerun_replays_without_symbols() {
849        let _guard = metrics_test_lock().lock().expect("metrics test lock");
850        let dir = tempfile::tempdir().expect("tempdir");
851        let file = write_php(
852            &dir,
853            "Example.php",
854            "<?php\nclass Example {\n    public function answer(): int { return 42; }\n}\n(new Example())->answer();\n",
855        );
856        let session = AnalysisSession::new(PhpVersion::LATEST);
857        let opts = BatchOptions::new().without_symbols();
858        let hash = crate::cache::hash_content(
859            "<?php\nclass Example {\n    public function answer(): int { return 42; }\n}\n(new Example())->answer();\n",
860        );
861        let hashes = HashMap::from_iter([(Arc::from(file.to_string_lossy().as_ref()), hash)]);
862
863        let first = session.analyze_paths(std::slice::from_ref(&file), &opts);
864        assert!(first.issues.is_empty());
865        assert!(
866            session
867                .transient_batch_replay(PhpVersion::LATEST.cache_byte(), true, &hashes)
868                .is_some(),
869            "expected first run to populate transient replay"
870        );
871
872        crate::metrics::test_reset();
873        let second = session.analyze_paths(std::slice::from_ref(&file), &opts);
874        assert!(second.issues.is_empty());
875        assert!(second.symbols.is_empty());
876
877        let dump = crate::metrics::dump().expect("metrics enabled in tests");
878        assert!(
879            dump.contains("whole-file walks     : 0"),
880            "expected replay to skip body walks, got:\n{dump}"
881        );
882        assert!(
883            dump.contains("symbols allocated    : 0"),
884            "expected diagnostics-only replay to avoid symbol allocation, got:\n{dump}"
885        );
886    }
887
888    #[test]
889    fn identical_batch_rerun_replays_with_symbols() {
890        let _guard = metrics_test_lock().lock().expect("metrics test lock");
891        let dir = tempfile::tempdir().expect("tempdir");
892        let file = write_php(
893            &dir,
894            "Example.php",
895            "<?php\nclass Example {\n    public function answer(): int { return 42; }\n}\n(new Example())->answer();\n",
896        );
897        let session = AnalysisSession::new(PhpVersion::LATEST);
898        let opts = BatchOptions::new();
899        let hash = crate::cache::hash_content(
900            "<?php\nclass Example {\n    public function answer(): int { return 42; }\n}\n(new Example())->answer();\n",
901        );
902        let hashes = HashMap::from_iter([(Arc::from(file.to_string_lossy().as_ref()), hash)]);
903
904        let first = session.analyze_paths(std::slice::from_ref(&file), &opts);
905        assert!(
906            !first.symbols.is_empty(),
907            "expected first run to collect symbols"
908        );
909        assert!(
910            session
911                .transient_batch_replay(PhpVersion::LATEST.cache_byte(), false, &hashes)
912                .is_some(),
913            "expected first run to populate transient replay"
914        );
915
916        crate::metrics::test_reset();
917        let second = session.analyze_paths(std::slice::from_ref(&file), &opts);
918        assert_eq!(second.symbols.len(), first.symbols.len());
919
920        let dump = crate::metrics::dump().expect("metrics enabled in tests");
921        assert!(
922            dump.contains("whole-file walks     : 0"),
923            "expected replay to skip body walks, got:\n{dump}"
924        );
925    }
926
927    #[test]
928    fn session_mutation_clears_batch_replay() {
929        let _guard = metrics_test_lock().lock().expect("metrics test lock");
930        let dir = tempfile::tempdir().expect("tempdir");
931        let file = write_php(
932            &dir,
933            "Example.php",
934            "<?php\nclass Example {\n    public function answer(): int { return 42; }\n}\n(new Example())->answer();\n",
935        );
936        let file_arc: Arc<str> = Arc::from(file.to_string_lossy().as_ref());
937        let session = AnalysisSession::new(PhpVersion::LATEST);
938        let opts = BatchOptions::new().without_symbols();
939
940        let _ = session.analyze_paths(std::slice::from_ref(&file), &opts);
941        session.ingest_file(
942            Arc::clone(&file_arc),
943            Arc::from(
944                "<?php\nclass Example {\n    public function answer(): string { return 'forty two'; }\n}\n(new Example())->answer();\n",
945            ),
946        );
947
948        crate::metrics::test_reset();
949        let result = session.analyze_paths(std::slice::from_ref(&file), &opts);
950        assert!(result.issues.is_empty());
951
952        let dump = crate::metrics::dump().expect("metrics enabled in tests");
953        assert!(
954            dump.contains("whole-file walks     : 1"),
955            "expected session mutation to invalidate replay, got:\n{dump}"
956        );
957    }
958}