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        // Mirror-only workspace files may be waiting in the pending index
576        // set. Reconcile them before the content-hash fast path; otherwise a
577        // cached result computed against a partial workspace could be replayed
578        // before `settle_workspace_index()` gets a chance to invalidate it.
579        self.settle_workspace_index();
580
581        // Fast path: content unchanged and cache has a valid entry.
582        if let Some(cache) = &self.cache {
583            let h = hash_content(new_content);
584            if let Some((cached_issues, ref_locs)) = cache.get(file_path, &h) {
585                let mut issues = cached_issues.to_vec();
586                let file: Arc<str> = Arc::from(file_path);
587                // Replace semantics: the cached set is the file's complete
588                // reference set, so stale entries from a prior version are
589                // cleared rather than appended over.
590                let locs: Vec<RefLoc> = ref_locs
591                    .iter()
592                    .map(|(symbol, line, col_start, col_end)| RefLoc {
593                        symbol_key: Arc::clone(symbol),
594                        file: file.clone(),
595                        line: *line,
596                        col_start: *col_start,
597                        col_end: *col_end,
598                    })
599                    .collect();
600                let guard = self.db.salsa.read();
601                guard.set_file_reference_locations(file_path, locs);
602                drop(guard);
603                opts.apply(&mut issues);
604                self.apply_suppressions_and_emit_unused(&mut issues, std::slice::from_ref(&file));
605                return AnalysisResult::build(issues, HashMap::default(), Vec::new());
606            }
607        }
608
609        let file: Arc<str> = Arc::from(file_path);
610
611        {
612            let mut guard = self.db.salsa.write();
613            guard.remove_file_definitions(file_path);
614        }
615
616        let collected =
617            self.db
618                .collect_and_ingest_file_with_parsed(file.clone(), new_content, php_version);
619        let file_defs = collected.file_defs;
620
621        let mut all_issues: Vec<Issue> = Arc::unwrap_or_clone(file_defs.issues.clone());
622
623        {
624            let mut guard = self.db.salsa.write();
625            if guard.workspace_symbol_index_singleton().is_some() {
626                if let Some(sf) = guard.lookup_source_file(file.as_ref()) {
627                    if guard.file_declarations_changed(sf) {
628                        guard.rebuild_workspace_symbol_index();
629                    }
630                }
631            }
632        }
633
634        let (symbols, surface_hash) = {
635            let guard = self.db.salsa.write();
636            let parsed = collected
637                .parsed
638                .unwrap_or_else(|| php_rs_parser::parse(new_content));
639            let surface_hash = surface_fingerprint(new_content, &parsed.program);
640
641            let has_hard_errors = parsed.errors.iter().any(crate::parser::is_hard_parse_error);
642            let symbols = if !has_hard_errors {
643                let db_ref: &dyn MirDatabase = &**guard;
644                let mut driver = BodyAnalyzer::new(db_ref, php_version);
645                driver.collect_symbols = !opts.skip_symbols;
646                let (body_issues, symbols) = driver.analyze_bodies(
647                    &parsed.program,
648                    file.clone(),
649                    new_content,
650                    &parsed.source_map,
651                );
652                all_issues.extend(body_issues);
653                let pending = guard.take_pending_ref_locs();
654                guard.set_file_reference_locations(file.as_ref(), pending);
655                if opts.skip_symbols {
656                    Vec::new()
657                } else {
658                    symbols
659                }
660            } else {
661                Vec::new()
662            };
663            (symbols, surface_hash)
664        };
665
666        // Bake inline-suppression marks in *before* caching: suppression is a
667        // pure function of file content (and the cache key hashes content), so
668        // the cached issues should already carry their marks. The cache-hit
669        // branch above replays this file's source without re-registering the
670        // `SourceFile` input, so the db-backed post-filter cannot recompute
671        // marks there — caching the canonical result is what keeps a fresh
672        // process honoring `@mir-ignore` on an unchanged file.
673        mark_suppressed(
674            &mut all_issues,
675            &crate::suppression::SuppressionMap::from_source(new_content),
676        );
677
678        if let Some(cache) = &self.cache {
679            let h = hash_content(new_content);
680            // Cascade to dependents only when this file's cross-file surface
681            // changed; a body-only edit to a declared-return callable leaves
682            // their results valid. Unknown (absent/empty) stored surface cascades.
683            let surface_changed = match cache.surface_hash(file_path) {
684                Some(stored) if !stored.is_empty() => stored != surface_hash,
685                _ => true,
686            };
687            if surface_changed {
688                cache.evict_with_dependents(&[file_path.to_string()]);
689            }
690            let db = self.snapshot_db();
691            let ref_locs = extract_reference_locations(&db, &file);
692            cache.put(
693                file_path,
694                h,
695                surface_hash,
696                all_issues.as_slice().into(),
697                ref_locs,
698            );
699        }
700
701        opts.apply(&mut all_issues);
702        // Emit `UnusedSuppress` for named suppressions that matched nothing —
703        // present on the cache-hit branch above and on `analyze_paths`, but
704        // missing here, so every non-cached re-analysis (the actual
705        // incremental/LSP-edit pipeline) silently dropped this diagnostic.
706        // `mark_suppressed` above already baked suppression marks into what
707        // gets cached; this only adds the (uncached, always-fresh) unused-
708        // suppression pass on top, mirroring the cache-hit branch's order.
709        self.apply_suppressions_and_emit_unused(&mut all_issues, std::slice::from_ref(&file));
710        AnalysisResult::build(all_issues, HashMap::default(), symbols)
711    }
712
713    /// Collect type definitions only from `paths` into the codebase
714    /// without analyzing method bodies or emitting issues. Used to load
715    /// vendor types.
716    ///
717    /// When a disk-backed cache is attached, per-file `StubSlice` results
718    /// from previous runs are reused on a content-hash match, eliminating
719    /// the parse + definition-collection step. Cache misses run the normal
720    /// pipeline and write back so subsequent runs hit.
721    pub fn collect_definitions(&self, paths: &[PathBuf]) {
722        self.clear_transient_batch_replay();
723        let _timing = std::env::var("MIR_TIMING").is_ok();
724        let _t0 = std::time::Instant::now();
725
726        let php_v = self.php_version.cache_byte();
727
728        struct FileEntry {
729            file: Arc<str>,
730            src: Arc<str>,
731            hash: [u8; 32],
732            cached: Option<mir_codebase::definitions::StubSlice>,
733        }
734        let entries: Vec<FileEntry> = paths
735            .par_iter()
736            .filter_map(|path| {
737                let src = std::fs::read_to_string(path).ok()?;
738                let file: Arc<str> = Arc::from(path.to_string_lossy().as_ref());
739                let src: Arc<str> = Arc::from(src);
740                let hash = hash_source(&src);
741                let cached = self.db.stub_cache.as_ref().and_then(|c| {
742                    let (mut slice, _issues) = c.get(&file, &hash, php_v)?;
743                    prepare_for_ingest(&mut slice);
744                    Some(slice)
745                });
746                Some(FileEntry {
747                    file,
748                    src,
749                    hash,
750                    cached,
751                })
752            })
753            .collect();
754        let _t_read = _t0.elapsed();
755
756        let source_files: Vec<SourceFile> = {
757            let mut guard = self.db.salsa.write();
758            entries
759                .iter()
760                .map(|e| {
761                    guard.upsert_source_file_with_durability(
762                        e.file.clone(),
763                        e.src.clone(),
764                        salsa::Durability::HIGH,
765                    )
766                })
767                .collect()
768        };
769        let _t_reg = _t0.elapsed();
770
771        let db_pass1 = {
772            let guard = self.db.salsa.read();
773            (**guard).clone()
774        };
775        let stub_cache = self.db.stub_cache.clone();
776        let prepared: Vec<(Arc<str>, mir_codebase::definitions::StubSlice)> = entries
777            .into_par_iter()
778            .zip(source_files.into_par_iter())
779            .map_with(db_pass1, |db, (mut entry, salsa_file)| {
780                if let Some(slice) = entry.cached.take() {
781                    let slice_arc = Arc::new(slice);
782                    db.parse_cache().insert(
783                        entry.hash,
784                        php_v,
785                        Arc::clone(&slice_arc),
786                        Arc::new(Vec::new()),
787                    );
788                    return (entry.file.clone(), (*slice_arc).clone());
789                }
790                let defs = collect_file_definitions(&*db, salsa_file);
791                if let Some(cache) = stub_cache.as_ref() {
792                    cache.put(&entry.file, &entry.hash, php_v, &defs.slice, &defs.issues);
793                }
794                (entry.file.clone(), (*defs.slice).clone())
795            })
796            .collect();
797        let _t_collect = _t0.elapsed();
798        // Commit subtype-index class edges for the vendor tree: without this,
799        // goto-implementation can't surface implementors that live only in
800        // vendor/ (index_batch's project-file warm sweep has the same gap for
801        // project files, but no StubSlice is cheaply available there — see
802        // the persistence work tracked separately).
803        {
804            let guard = self.db.salsa.read();
805            for (file, slice) in &prepared {
806                let entries = crate::db::subtype_index::entries_from_slice(slice);
807                guard.set_file_class_edges(file, entries);
808            }
809        }
810        drop(prepared);
811        let _t_ingest = _t0.elapsed();
812
813        if _timing {
814            let (hits, misses) = self.stub_cache_stats();
815            eprintln!(
816                "[vendor] read={:.0}ms reg={:.0}ms collect={:.0}ms ingest={:.0}ms total={:.0}ms (cache hits={hits} misses={misses})",
817                _t_read.as_secs_f64() * 1000.0,
818                (_t_reg - _t_read).as_secs_f64() * 1000.0,
819                (_t_collect - _t_reg).as_secs_f64() * 1000.0,
820                (_t_ingest - _t_collect).as_secs_f64() * 1000.0,
821                _t_ingest.as_secs_f64() * 1000.0,
822            );
823        }
824
825        {
826            let mut guard = self.db.salsa.write();
827            guard.rebuild_workspace_symbol_index();
828        }
829
830        crate::collector::print_collector_stats();
831    }
832}
833
834#[cfg(test)]
835mod tests {
836    use rustc_hash::FxHashMap as HashMap;
837    use std::fs;
838    use std::sync::{Arc, Mutex, OnceLock};
839
840    use crate::{AnalysisSession, BatchOptions, PhpVersion};
841
842    fn metrics_test_lock() -> &'static Mutex<()> {
843        static LOCK: OnceLock<Mutex<()>> = OnceLock::new();
844        LOCK.get_or_init(|| Mutex::new(()))
845    }
846
847    fn write_php(dir: &tempfile::TempDir, name: &str, contents: &str) -> std::path::PathBuf {
848        let path = dir.path().join(name);
849        fs::write(&path, contents).expect("write fixture");
850        path
851    }
852
853    #[test]
854    fn identical_batch_rerun_replays_without_symbols() {
855        let _guard = metrics_test_lock().lock().expect("metrics test lock");
856        let dir = tempfile::tempdir().expect("tempdir");
857        let file = write_php(
858            &dir,
859            "Example.php",
860            "<?php\nclass Example {\n    public function answer(): int { return 42; }\n}\n(new Example())->answer();\n",
861        );
862        let session = AnalysisSession::new(PhpVersion::LATEST);
863        let opts = BatchOptions::new().without_symbols();
864        let hash = crate::cache::hash_content(
865            "<?php\nclass Example {\n    public function answer(): int { return 42; }\n}\n(new Example())->answer();\n",
866        );
867        let hashes = HashMap::from_iter([(Arc::from(file.to_string_lossy().as_ref()), hash)]);
868
869        let first = session.analyze_paths(std::slice::from_ref(&file), &opts);
870        assert!(first.issues.is_empty());
871        assert!(
872            session
873                .transient_batch_replay(PhpVersion::LATEST.cache_byte(), true, &hashes)
874                .is_some(),
875            "expected first run to populate transient replay"
876        );
877
878        crate::metrics::test_reset();
879        let second = session.analyze_paths(std::slice::from_ref(&file), &opts);
880        assert!(second.issues.is_empty());
881        assert!(second.symbols.is_empty());
882
883        let dump = crate::metrics::dump().expect("metrics enabled in tests");
884        assert!(
885            dump.contains("whole-file walks     : 0"),
886            "expected replay to skip body walks, got:\n{dump}"
887        );
888        assert!(
889            dump.contains("symbols allocated    : 0"),
890            "expected diagnostics-only replay to avoid symbol allocation, got:\n{dump}"
891        );
892    }
893
894    #[test]
895    fn identical_batch_rerun_replays_with_symbols() {
896        let _guard = metrics_test_lock().lock().expect("metrics test lock");
897        let dir = tempfile::tempdir().expect("tempdir");
898        let file = write_php(
899            &dir,
900            "Example.php",
901            "<?php\nclass Example {\n    public function answer(): int { return 42; }\n}\n(new Example())->answer();\n",
902        );
903        let session = AnalysisSession::new(PhpVersion::LATEST);
904        let opts = BatchOptions::new();
905        let hash = crate::cache::hash_content(
906            "<?php\nclass Example {\n    public function answer(): int { return 42; }\n}\n(new Example())->answer();\n",
907        );
908        let hashes = HashMap::from_iter([(Arc::from(file.to_string_lossy().as_ref()), hash)]);
909
910        let first = session.analyze_paths(std::slice::from_ref(&file), &opts);
911        assert!(
912            !first.symbols.is_empty(),
913            "expected first run to collect symbols"
914        );
915        assert!(
916            session
917                .transient_batch_replay(PhpVersion::LATEST.cache_byte(), false, &hashes)
918                .is_some(),
919            "expected first run to populate transient replay"
920        );
921
922        crate::metrics::test_reset();
923        let second = session.analyze_paths(std::slice::from_ref(&file), &opts);
924        assert_eq!(second.symbols.len(), first.symbols.len());
925
926        let dump = crate::metrics::dump().expect("metrics enabled in tests");
927        assert!(
928            dump.contains("whole-file walks     : 0"),
929            "expected replay to skip body walks, got:\n{dump}"
930        );
931    }
932
933    #[test]
934    fn session_mutation_clears_batch_replay() {
935        let _guard = metrics_test_lock().lock().expect("metrics test lock");
936        let dir = tempfile::tempdir().expect("tempdir");
937        let file = write_php(
938            &dir,
939            "Example.php",
940            "<?php\nclass Example {\n    public function answer(): int { return 42; }\n}\n(new Example())->answer();\n",
941        );
942        let file_arc: Arc<str> = Arc::from(file.to_string_lossy().as_ref());
943        let session = AnalysisSession::new(PhpVersion::LATEST);
944        let opts = BatchOptions::new().without_symbols();
945
946        let _ = session.analyze_paths(std::slice::from_ref(&file), &opts);
947        session.ingest_file(
948            Arc::clone(&file_arc),
949            Arc::from(
950                "<?php\nclass Example {\n    public function answer(): string { return 'forty two'; }\n}\n(new Example())->answer();\n",
951            ),
952        );
953
954        crate::metrics::test_reset();
955        let result = session.analyze_paths(std::slice::from_ref(&file), &opts);
956        assert!(result.issues.is_empty());
957
958        let dump = crate::metrics::dump().expect("metrics enabled in tests");
959        assert!(
960            dump.contains("whole-file walks     : 1"),
961            "expected session mutation to invalidate replay, got:\n{dump}"
962        );
963    }
964}