Skip to main content

mir_analyzer/batch/
mod.rs

1//! Batch-oriented project analysis on [`AnalysisSession`].
2//!
3//! This module hosts the multi-file orchestration that used to live on the
4//! retired `ProjectAnalyzer`: parallel definition collection, lazy class loading, dead-code
5//! sweep, reverse-dependency index, and the [`AnalysisResult`] return type.
6//! Per-file (LSP) entry points stay on `AnalysisSession` itself in
7//! `session.rs`.
8//!
9//! All methods are `impl AnalysisSession`; configuration that's only
10//! meaningful for batch runs (issue suppressions, progress callback, optional
11//! PHP version override) is grouped in [`BatchOptions`] and passed in rather
12//! than stored on the session.
13
14use std::path::{Path, PathBuf};
15use std::sync::Arc;
16
17use rayon::prelude::*;
18use rustc_hash::{FxHashMap as HashMap, FxHashSet as HashSet};
19
20use mir_issues::Issue;
21use mir_types::{Atomic, Type};
22
23use crate::body_analysis::BodyAnalyzer;
24use crate::cache::{hash_content, surface_fingerprint};
25use crate::db::{
26    collect_file_definitions, FileDefinitions, MirDatabase, MirDbStorage, RefLoc, SourceFile,
27};
28use crate::php_version::PhpVersion;
29use crate::session::AnalysisSession;
30use crate::stub_cache::{hash_source, prepare_for_ingest};
31
32/// Issue kinds emitted by [`crate::dead_code::DeadCodeAnalyzer`].
33///
34/// The dead-code pass is just an error group — these names participate in
35/// [`BatchOptions::suppressed_issue_kinds`] like any other `IssueKind`. If
36/// every kind listed here is suppressed, the dead-code pass is skipped
37/// entirely.
38pub fn dead_code_issue_kinds() -> &'static [&'static str] {
39    &[
40        "UnusedMethod",
41        "UnusedProperty",
42        "UnusedFunction",
43        "UnusedClass",
44    ]
45}
46
47/// Per-batch options for [`AnalysisSession::analyze_paths`] and friends.
48///
49/// Configuration that only makes sense for full-project (batch) analysis
50/// lives here instead of on [`AnalysisSession`], so the per-file LSP API
51/// isn't bloated with state nothing else reads.
52#[derive(Clone, Default)]
53pub struct BatchOptions {
54    /// Names of `IssueKind` variants to drop from the final result, e.g.
55    /// `["MissingThrowsDocblock", "UnusedMethod"]`. Applied as a final
56    /// post-filter so analyzer internals don't need to know which
57    /// diagnostics the consumer cares about. Empty by default.
58    pub suppressed_issue_kinds: HashSet<String>,
59    /// Called once after each file completes body analysis (progress reporting).
60    pub on_file_done: Option<Arc<dyn Fn() + Send + Sync>>,
61    /// Override the session's configured PHP version for this run. `None`
62    /// uses the session's version.
63    pub php_version_override: Option<PhpVersion>,
64    /// Skip collecting per-expression [`crate::symbol::ResolvedSymbol`]s
65    /// into the [`AnalysisResult`]. Defaults to `false` (symbols collected)
66    /// so existing consumers — LSP servers using
67    /// [`AnalysisResult::symbol_at`] for hover/go-to-definition — are
68    /// unaffected. Diagnostics-only consumers (the CLI) opt out: a
69    /// Laravel-scale batch retains ~600k symbols nothing reads.
70    pub skip_symbols: bool,
71}
72
73impl BatchOptions {
74    pub fn new() -> Self {
75        Self::default()
76    }
77
78    pub fn with_suppressed<I, S>(mut self, kinds: I) -> Self
79    where
80        I: IntoIterator<Item = S>,
81        S: Into<String>,
82    {
83        self.suppressed_issue_kinds = kinds.into_iter().map(Into::into).collect();
84        self
85    }
86
87    pub fn with_progress_callback(mut self, callback: Arc<dyn Fn() + Send + Sync>) -> Self {
88        self.on_file_done = Some(callback);
89        self
90    }
91
92    pub fn with_php_version(mut self, version: PhpVersion) -> Self {
93        self.php_version_override = Some(version);
94        self
95    }
96
97    /// Don't collect per-expression symbols into the result (see
98    /// [`Self::skip_symbols`]). For diagnostics-only consumers;
99    /// [`AnalysisResult::symbol_at`] will find nothing on the batch result.
100    pub fn without_symbols(mut self) -> Self {
101        self.skip_symbols = true;
102        self
103    }
104
105    /// True iff at least one dead-code [`IssueKind`] would be emitted (i.e.
106    /// not all of them are suppressed).
107    fn should_run_dead_code(&self) -> bool {
108        dead_code_issue_kinds()
109            .iter()
110            .any(|k| !self.suppressed_issue_kinds.contains(*k))
111    }
112
113    /// Drop issues whose [`IssueKind::name()`] is listed in
114    /// [`Self::suppressed_issue_kinds`].
115    fn apply(&self, issues: &mut Vec<Issue>) {
116        if self.suppressed_issue_kinds.is_empty() {
117            return;
118        }
119        issues.retain(|i| !self.suppressed_issue_kinds.contains(i.kind.name()));
120    }
121}
122
123struct ParsedProjectFile {
124    file: Arc<str>,
125    source: Arc<str>,
126    parsed: php_rs_parser::ParseResult,
127}
128
129impl ParsedProjectFile {
130    fn new(file: Arc<str>, source: Arc<str>) -> Self {
131        let parsed = php_rs_parser::parse(source.as_ref());
132        Self {
133            file,
134            source,
135            parsed,
136        }
137    }
138
139    fn source(&self) -> &str {
140        self.source.as_ref()
141    }
142
143    fn source_map(&self) -> &php_rs_parser::source_map::SourceMap {
144        &self.parsed.source_map
145    }
146
147    fn errors(&self) -> &[php_rs_parser::diagnostics::ParseError] {
148        &self.parsed.errors
149    }
150
151    fn owned(&self) -> &php_ast::owned::Program {
152        &self.parsed.program
153    }
154}
155
156impl AnalysisSession {
157    /// Cumulative hit / miss counts on the persistent definition cache attached
158    /// to this session. `(0, 0)` when no cache is configured.
159    #[doc(hidden)]
160    pub fn stub_cache_stats(&self) -> (u64, u64) {
161        match self.db.stub_cache.as_deref() {
162            Some(c) => (c.hits(), c.misses()),
163            None => (0, 0),
164        }
165    }
166
167    fn batch_php_version(&self, opts: &BatchOptions) -> PhpVersion {
168        opts.php_version_override.unwrap_or(self.php_version)
169    }
170
171    /// Mark issues silenced by inline suppression comments
172    /// (`@mir-ignore`, `@psalm-suppress`, `@phpstan-ignore*`, …) as suppressed.
173    ///
174    /// Runs as a final post-filter over the merged issue list so it applies
175    /// uniformly to every emitting pass — body analysis, the collector, class
176    /// checks and dead-code detection — including diagnostics the per-statement
177    /// `@psalm-suppress` path in `stmt/mod.rs` structurally cannot reach.
178    ///
179    /// Issues are *marked* rather than dropped, mirroring that per-statement
180    /// path and the kind-level `mir.xml` suppress handler; every consumer (CLI,
181    /// WASM, the test harness) already skips [`Issue::suppressed`].
182    /// Apply inline suppressions and then emit `UnusedSuppress` issues for
183    /// any named `@suppress`/`@psalm-suppress` annotations that matched nothing.
184    ///
185    /// `analyzed_files` must list every file that was analyzed in this batch so
186    /// that files with *zero* existing issues still have their suppression maps
187    /// inspected for unused annotations.
188    fn apply_suppressions_and_emit_unused(
189        &self,
190        issues: &mut Vec<Issue>,
191        analyzed_files: &[Arc<str>],
192    ) {
193        use crate::suppression::SuppressionMap;
194        let db = self.snapshot_db();
195        let mut cache: HashMap<Arc<str>, Option<SuppressionMap>> = HashMap::default();
196        for issue in issues.iter_mut() {
197            if issue.suppressed {
198                continue;
199            }
200            let map = cache.entry(issue.location.file.clone()).or_insert_with(|| {
201                db.lookup_source_file(&issue.location.file)
202                    .map(|sf| SuppressionMap::from_source(&sf.text(&db)))
203            });
204            if let Some(map) = map.as_ref() {
205                if map.is_suppressed(issue.location.line, issue.kind.name(), issue.kind.code()) {
206                    issue.suppressed = true;
207                }
208            }
209        }
210        // Ensure suppression maps are built for every analyzed file, not just
211        // those that already have at least one issue (files with no issues would
212        // otherwise be skipped and their unused suppressions never detected).
213        for file in analyzed_files {
214            cache.entry(file.clone()).or_insert_with(|| {
215                db.lookup_source_file(file)
216                    .map(|sf| SuppressionMap::from_source(&sf.text(&db)))
217            });
218        }
219        // Now emit UnusedSuppress for each file that has named suppressions.
220        let files: Vec<Arc<str>> = cache
221            .iter()
222            .filter_map(|(f, m)| m.as_ref().map(|_| f.clone()))
223            .collect();
224        // Bucket issue refs by file once — a per-file scan of the global
225        // issue list would be O(files × issues), with clones on top.
226        let mut issues_by_file: HashMap<&str, Vec<&Issue>> = HashMap::default();
227        for issue in issues.iter() {
228            issues_by_file
229                .entry(issue.location.file.as_ref())
230                .or_default()
231                .push(issue);
232        }
233        let mut new_issues: Vec<Issue> = Vec::new();
234        for file in files {
235            if let Some(Some(map)) = cache.get(&file) {
236                if map.named_suppressions.is_empty() {
237                    continue;
238                }
239                let file_issues: &[&Issue] = issues_by_file
240                    .get(file.as_ref())
241                    .map(Vec::as_slice)
242                    .unwrap_or(&[]);
243                // Pre-suppressed issues arrived with suppressed=true from the
244                // IssueBuffer mechanism (collector / body analysis). They may be
245                // at a different line than the SuppressionMap target and need
246                // special handling in unused_named.
247                let pre_suppressed: Vec<&Issue> = file_issues
248                    .iter()
249                    .filter(|i| i.suppressed)
250                    .copied()
251                    .collect();
252                // Issues newly suppressed by the SuppressionMap in this pass
253                // arrived with suppressed=false; after the marking loop they
254                // also have suppressed=true. Pass all file issues for exact-line
255                // matching; pre_suppressed enables the docblock-range fallback.
256                let unused = map.unused_named(file_issues, &pre_suppressed);
257                for (line, kind) in unused {
258                    let loc = mir_types::Location::new(file.clone(), line, line, 0, 0);
259                    let mut issue = Issue::new(mir_issues::IssueKind::UnusedSuppress { kind }, loc);
260                    if map.is_suppressed(line, issue.kind.name(), issue.kind.code()) {
261                        issue.suppressed = true;
262                    }
263                    new_issues.push(issue);
264                }
265            }
266        }
267        issues.extend(new_issues);
268    }
269
270    fn type_exists(&self, fqcn: &str) -> bool {
271        let db = self.snapshot_db();
272        crate::db::class_exists(&db, fqcn)
273    }
274
275    fn collect_and_ingest_source(
276        &self,
277        file: Arc<str>,
278        src: &str,
279        php_version: PhpVersion,
280    ) -> FileDefinitions {
281        self.db.collect_and_ingest_file(file, src, php_version)
282    }
283
284    /// Rebuild the workspace symbol index singleton from every registered source
285    /// file. Required in the batch path because `workspace_index` reads the
286    /// maintained singleton, and that singleton is built from vendor *before*
287    /// `analyze_paths` registers project files (and before `lazy_load_*` faults
288    /// in referenced classes). Without refreshing it, `find_class_like` /
289    /// `class_exists` miss every project and lazy-loaded class, yielding false
290    /// `UndefinedClass`. Cheap after the definition caches are warm (no parsing).
291    fn refresh_workspace_index(&self) {
292        let mut guard = self.db.salsa.write();
293        guard.rebuild_workspace_symbol_index();
294    }
295
296    /// Load the configured PHP version + built-in stubs + user stubs into
297    /// the shared db. Called by [`Self::analyze_paths`] and
298    /// [`Self::collect_definitions`].
299    fn load_batch_stubs(&self, php_version: PhpVersion) {
300        // Wire the PHP version into the db before any SourceFile inputs are
301        // registered — collect_file_definitions reads it for @since/@removed filtering.
302        {
303            let version_str = Arc::from(php_version.to_string().as_str());
304            self.db.salsa.write().set_php_version(version_str);
305        }
306
307        // Built-in stubs for the configured PHP version.
308        let paths: Vec<&'static str> = crate::stubs::stub_files().iter().map(|&(p, _)| p).collect();
309        self.db.ingest_stub_paths(&paths, php_version);
310
311        // User-configured stubs.
312        self.db
313            .ingest_user_stubs(&self.user_stub_files, &self.user_stub_dirs);
314
315        // Ensure a resolver is configured so pull-path lookups can map
316        // built-in FQCNs to the stub VFS paths registered above.
317        let mut guard = self.db.salsa.write();
318        if guard.current_resolver().is_none() {
319            let resolver: Arc<dyn crate::ClassResolver> = Arc::new(crate::StubClassResolver);
320            guard.set_resolver(Some(resolver));
321        }
322    }
323}
324
325mod lazy;
326mod run;
327
328/// Analyze a PHP source string without a real file path. Useful for tests
329/// and single-file LSP mode. Allocates a throwaway db; doesn't touch any
330/// existing session.
331pub fn analyze_source(source: &str) -> AnalysisResult {
332    let php_version = PhpVersion::LATEST;
333    let file: Arc<str> = Arc::from("<source>");
334    let mut db = MirDbStorage::default();
335    db.set_php_version(Arc::from(php_version.to_string().as_str()));
336    crate::stubs::load_stubs_for_version(&mut db, php_version);
337    // Register the file through the workspace registry (not a bare
338    // `SourceFile::new`) so it lands in `all_source_files()` and the
339    // workspace symbol index. Without this, body analysis can't look up the
340    // file's own functions/methods/classes and degrades every parameter to
341    // `mixed` via the `ast_derived_fn_params` fallback.
342    let salsa_file = db.upsert_source_file(file.clone(), Arc::from(source));
343    let file_defs = collect_file_definitions(&db, salsa_file);
344    let suppressions = crate::suppression::SuppressionMap::from_source(source);
345    let mut all_issues = Arc::unwrap_or_clone(file_defs.issues);
346    if all_issues.iter().any(|issue| {
347        matches!(issue.kind, mir_issues::IssueKind::ParseError { .. })
348            && issue.severity == mir_issues::Severity::Error
349    }) {
350        mark_suppressed(&mut all_issues, &suppressions);
351        return AnalysisResult::build(all_issues, rustc_hash::FxHashMap::default(), Vec::new());
352    }
353    let mut type_envs = rustc_hash::FxHashMap::default();
354    let mut all_symbols = Vec::new();
355    let result = php_rs_parser::parse(source);
356
357    let driver = BodyAnalyzer::new(&db, php_version);
358    all_issues.extend(driver.analyze_bodies_typed(
359        &result.program,
360        file.clone(),
361        source,
362        &result.source_map,
363        &mut type_envs,
364        &mut all_symbols,
365    ));
366    mark_suppressed(&mut all_issues, &suppressions);
367    emit_unused_suppressions(&mut all_issues, &suppressions, &file);
368    AnalysisResult::build(all_issues, type_envs, all_symbols)
369}
370
371/// Mark issues silenced by a single file's [`SuppressionMap`]. Shared by the
372/// in-memory [`analyze_source`] entry point, which has the source in hand and
373/// does not go through the db-backed batch post-filter.
374fn mark_suppressed(issues: &mut [Issue], suppressions: &crate::suppression::SuppressionMap) {
375    if suppressions.is_empty() {
376        return;
377    }
378    for issue in issues.iter_mut() {
379        if !issue.suppressed
380            && suppressions.is_suppressed(issue.location.line, issue.kind.name(), issue.kind.code())
381        {
382            issue.suppressed = true;
383        }
384    }
385}
386
387/// Append `UnusedSuppress` issues for any named `@suppress`/`@psalm-suppress`
388/// annotations that did not match any issue in `all_issues`. The new issues are
389/// themselves subject to suppression (so `@suppress UnusedSuppress` works).
390fn emit_unused_suppressions(
391    all_issues: &mut Vec<Issue>,
392    suppressions: &crate::suppression::SuppressionMap,
393    file: &std::sync::Arc<str>,
394) {
395    let all_refs: Vec<&Issue> = all_issues.iter().collect();
396    let pre_suppressed: Vec<&Issue> = all_refs.iter().filter(|i| i.suppressed).copied().collect();
397    let unused = suppressions.unused_named(&all_refs, &pre_suppressed);
398    for (line, kind) in unused {
399        let loc = mir_types::Location::new(file.clone(), line, line, 0, 0);
400        let mut issue = Issue::new(mir_issues::IssueKind::UnusedSuppress { kind }, loc);
401        if suppressions.is_suppressed(line, issue.kind.name(), issue.kind.code()) {
402            issue.suppressed = true;
403        }
404        all_issues.push(issue);
405    }
406}
407
408/// Discover all `.php` files under a directory, recursively.
409pub fn discover_files(root: &Path) -> Vec<PathBuf> {
410    if root.is_file() {
411        return vec![root.to_path_buf()];
412    }
413    let mut files = Vec::new();
414    collect_php_files(root, &mut files);
415    files
416}
417
418pub(crate) fn collect_php_files(dir: &Path, out: &mut Vec<PathBuf>) {
419    if let Ok(entries) = std::fs::read_dir(dir) {
420        for entry in entries.flatten() {
421            if entry.file_type().map(|ft| ft.is_symlink()).unwrap_or(false) {
422                continue;
423            }
424            let path = entry.path();
425            if path.is_dir() {
426                let name = path.file_name().and_then(|n| n.to_str()).unwrap_or("");
427                if matches!(
428                    name,
429                    "vendor" | ".git" | "node_modules" | ".cache" | ".pnpm-store"
430                ) {
431                    continue;
432                }
433                collect_php_files(&path, out);
434            } else if path.extension().and_then(|e| e.to_str()) == Some("php") {
435                out.push(path);
436            }
437        }
438    }
439}
440
441// ---------------------------------------------------------------------------
442// FQCN reference walk — collects every class-name reference reachable from a
443// ClassLike's signature surface. Used by lazy_load_missing_classes to chase
444// transitive vendor types.
445// ---------------------------------------------------------------------------
446
447pub(crate) fn collect_class_referenced_fqcns(class: &crate::db::ClassLike, out: &mut Vec<String>) {
448    if let Some(p) = class.parent() {
449        out.push(p.to_string());
450    }
451    for i in class.interfaces() {
452        out.push(i.to_string());
453    }
454    for e in class.extends() {
455        out.push(e.to_string());
456    }
457    for t in class.class_traits() {
458        out.push(t.to_string());
459    }
460    for m in class.mixins() {
461        out.push(m.to_string());
462    }
463    for u in class.extends_type_args() {
464        collect_fqcns_in_union(u, out);
465    }
466    for (iface, args) in class.implements_type_args() {
467        out.push(iface.to_string());
468        for u in args {
469            collect_fqcns_in_union(u, out);
470        }
471    }
472    for (_, m) in class.own_methods().iter() {
473        for p in m.params.iter() {
474            if let Some(t) = &p.ty {
475                collect_fqcns_in_union(t, out);
476            }
477        }
478        if let Some(t) = &m.return_type {
479            collect_fqcns_in_union(t, out);
480        }
481        for thrown in m.throws.iter() {
482            out.push(thrown.to_string());
483        }
484    }
485    if let Some(props) = class.own_properties() {
486        for (_, p) in props.iter() {
487            if let Some(t) = &p.ty {
488                collect_fqcns_in_union(t, out);
489            }
490        }
491    }
492    for (_, c) in class.own_constants().iter() {
493        collect_fqcns_in_union(&c.ty, out);
494    }
495}
496
497pub(crate) fn collect_fqcns_in_union(u: &Type, out: &mut Vec<String>) {
498    for atom in u.types.iter() {
499        collect_fqcns_in_atomic(atom, out);
500    }
501}
502
503fn collect_fqcns_in_simple(t: &mir_types::compact::SimpleType, out: &mut Vec<String>) {
504    if let mir_types::compact::SimpleType::Complex(u) = t {
505        collect_fqcns_in_union(u, out);
506    }
507}
508
509pub(crate) fn collect_fqcns_in_atomic(a: &Atomic, out: &mut Vec<String>) {
510    match a {
511        Atomic::TNamedObject { fqcn, type_params } => {
512            out.push(fqcn.to_string());
513            for tp in type_params.iter() {
514                collect_fqcns_in_union(tp, out);
515            }
516        }
517        Atomic::TStaticObject { fqcn } | Atomic::TSelf { fqcn } | Atomic::TParent { fqcn } => {
518            out.push(fqcn.to_string());
519        }
520        Atomic::TLiteralEnumCase { enum_fqcn, .. } => {
521            out.push(enum_fqcn.to_string());
522        }
523        Atomic::TClassString(Some(s)) | Atomic::TInterfaceString(Some(s)) => {
524            out.push(s.to_string());
525        }
526        Atomic::TArray { key, value } | Atomic::TNonEmptyArray { key, value } => {
527            collect_fqcns_in_union(key, out);
528            collect_fqcns_in_union(value, out);
529        }
530        Atomic::TList { value } | Atomic::TNonEmptyList { value } => {
531            collect_fqcns_in_union(value, out);
532        }
533        Atomic::TKeyedArray { properties, .. } => {
534            for (_, kp) in properties.iter() {
535                collect_fqcns_in_union(&kp.ty, out);
536            }
537        }
538        Atomic::TClosure { data } => {
539            for p in data.params.iter() {
540                if let Some(t) = &p.ty {
541                    collect_fqcns_in_simple(t, out);
542                }
543            }
544            collect_fqcns_in_union(&data.return_type, out);
545            if let Some(t) = &data.this_type {
546                collect_fqcns_in_union(t, out);
547            }
548        }
549        Atomic::TCallable {
550            params,
551            return_type,
552        } => {
553            if let Some(ps) = params {
554                for p in ps {
555                    if let Some(t) = &p.ty {
556                        collect_fqcns_in_simple(t, out);
557                    }
558                }
559            }
560            if let Some(rt) = return_type {
561                collect_fqcns_in_union(rt, out);
562            }
563        }
564        Atomic::TIntersection { parts } => {
565            for p in parts.iter() {
566                collect_fqcns_in_union(p, out);
567            }
568        }
569        Atomic::TConditional { data } => {
570            collect_fqcns_in_union(&data.subject, out);
571            collect_fqcns_in_union(&data.if_true, out);
572            collect_fqcns_in_union(&data.if_false, out);
573        }
574        Atomic::TTemplateParam { as_type, .. } => {
575            collect_fqcns_in_union(as_type, out);
576        }
577        _ => {}
578    }
579}
580
581fn build_reverse_deps(db: &dyn crate::db::MirDatabase) -> HashMap<String, HashSet<String>> {
582    let mut reverse: HashMap<String, HashSet<String>> = HashMap::default();
583
584    let mut add_edge = |symbol: &str, dependent_file: &str| {
585        if let Some(defining_file) = db.symbol_defining_file(symbol) {
586            let def = defining_file.as_ref().to_string();
587            if def != dependent_file {
588                reverse
589                    .entry(def)
590                    .or_default()
591                    .insert(dependent_file.to_string());
592            }
593        }
594    };
595
596    for (file, imports) in db.file_import_snapshots() {
597        let file = file.as_ref().to_string();
598        for fqcn in imports.values() {
599            add_edge(fqcn.as_str(), &file);
600        }
601    }
602
603    let extract_named_objects = |union: &mir_types::Type| {
604        union
605            .types
606            .iter()
607            .filter_map(|atomic| match atomic {
608                mir_types::atomic::Atomic::TNamedObject { fqcn, .. } => Some(*fqcn),
609                _ => None,
610            })
611            .collect::<Vec<_>>()
612    };
613
614    for fqcn in crate::db::workspace_classes(db).iter() {
615        let here = crate::db::Fqcn::from_str(db, fqcn.as_ref());
616        let Some(class) = crate::db::find_class_like(db, here) else {
617            continue;
618        };
619        if class.is_interface() || class.is_trait() || class.is_enum() {
620            continue;
621        }
622        let Some(file) = db
623            .symbol_defining_file(fqcn.as_ref())
624            .map(|f| f.as_ref().to_string())
625            .or_else(|| class.location().map(|l| l.file.as_ref().to_string()))
626        else {
627            continue;
628        };
629
630        if let Some(parent) = class.parent() {
631            add_edge(parent.as_ref(), &file);
632        }
633        for iface in class.interfaces().iter() {
634            add_edge(iface.as_ref(), &file);
635        }
636        for tr in class.class_traits().iter() {
637            add_edge(tr.as_ref(), &file);
638        }
639        if let Some(props) = class.own_properties() {
640            for (_, p) in props.iter() {
641                if let Some(ty) = &p.ty {
642                    for named in extract_named_objects(ty) {
643                        add_edge(named.as_ref(), &file);
644                    }
645                }
646            }
647        }
648        for (_, method) in class.own_methods().iter() {
649            for param in method.params.iter() {
650                if let Some(ty) = &param.ty {
651                    for named in extract_named_objects(ty.as_ref()) {
652                        add_edge(named.as_ref(), &file);
653                    }
654                }
655            }
656            if let Some(rt) = method.return_type.as_deref() {
657                for named in extract_named_objects(rt) {
658                    add_edge(named.as_ref(), &file);
659                }
660            }
661        }
662    }
663
664    for fqn in crate::db::workspace_functions(db).iter() {
665        let here = crate::db::Fqcn::from_str(db, fqn.as_ref());
666        let Some(f) = crate::db::find_function(db, here) else {
667            continue;
668        };
669        let Some(file) = db
670            .symbol_defining_file(fqn.as_ref())
671            .map(|f| f.as_ref().to_string())
672            .or_else(|| f.location.as_ref().map(|l| l.file.as_ref().to_string()))
673        else {
674            continue;
675        };
676
677        for param in f.params.iter() {
678            if let Some(ty) = &param.ty {
679                for named in extract_named_objects(ty.as_ref()) {
680                    add_edge(named.as_ref(), &file);
681                }
682            }
683        }
684        if let Some(rt) = f.return_type.as_deref() {
685            for named in extract_named_objects(rt) {
686                add_edge(named.as_ref(), &file);
687            }
688        }
689    }
690
691    for (ref_file, symbol_key) in db.all_reference_location_pairs() {
692        let file_str = ref_file.as_ref().to_string();
693        let lookup = crate::defining_file_lookup_key(&symbol_key);
694        add_edge(lookup, &file_str);
695    }
696
697    reverse
698}
699
700fn extract_reference_locations(
701    db: &dyn crate::db::MirDatabase,
702    file: &Arc<str>,
703) -> Arc<[crate::cache::CachedRefLoc]> {
704    db.extract_file_reference_locations(file.as_ref()).into()
705}
706
707pub struct AnalysisResult {
708    pub issues: Vec<Issue>,
709    #[doc(hidden)]
710    pub type_envs: rustc_hash::FxHashMap<crate::type_env::ScopeId, crate::type_env::TypeEnv>,
711    /// Per-expression resolved symbols from body analysis, sorted by file path.
712    pub symbols: Vec<crate::symbol::ResolvedSymbol>,
713    /// Maps each file path to the contiguous range within `symbols` that
714    /// belongs to it.
715    symbols_by_file: HashMap<Arc<str>, std::ops::Range<usize>>,
716}
717
718impl AnalysisResult {
719    fn build(
720        issues: Vec<Issue>,
721        type_envs: rustc_hash::FxHashMap<crate::type_env::ScopeId, crate::type_env::TypeEnv>,
722        mut symbols: Vec<crate::symbol::ResolvedSymbol>,
723    ) -> Self {
724        symbols.sort_unstable_by(|a, b| a.file.as_ref().cmp(b.file.as_ref()));
725        let mut symbols_by_file: HashMap<Arc<str>, std::ops::Range<usize>> = HashMap::default();
726        let mut i = 0;
727        while i < symbols.len() {
728            let file = Arc::clone(&symbols[i].file);
729            let start = i;
730            while i < symbols.len() && symbols[i].file == file {
731                i += 1;
732            }
733            symbols_by_file.insert(file, start..i);
734        }
735        Self {
736            issues,
737            type_envs,
738            symbols,
739            symbols_by_file,
740        }
741    }
742
743    pub fn error_count(&self) -> usize {
744        self.issues
745            .iter()
746            .filter(|i| i.severity == mir_issues::Severity::Error)
747            .count()
748    }
749
750    pub fn warning_count(&self) -> usize {
751        self.issues
752            .iter()
753            .filter(|i| i.severity == mir_issues::Severity::Warning)
754            .count()
755    }
756
757    pub fn issues_by_file(&self) -> HashMap<Arc<str>, Vec<&Issue>> {
758        let mut map: HashMap<Arc<str>, Vec<&Issue>> = HashMap::default();
759        for issue in &self.issues {
760            map.entry(issue.location.file.clone())
761                .or_default()
762                .push(issue);
763        }
764        map
765    }
766
767    pub fn count_by_severity(&self) -> Vec<(mir_issues::Severity, usize)> {
768        let mut counts: std::collections::BTreeMap<mir_issues::Severity, usize> =
769            std::collections::BTreeMap::new();
770        for issue in &self.issues {
771            *counts.entry(issue.severity).or_insert(0) += 1;
772        }
773        counts.into_iter().collect()
774    }
775
776    pub fn total_issue_count(&self) -> usize {
777        self.issues.len()
778    }
779
780    pub fn filter_issues<'a, F>(&'a self, predicate: F) -> impl Iterator<Item = &'a Issue>
781    where
782        F: Fn(&Issue) -> bool + 'a,
783    {
784        self.issues.iter().filter(move |i| predicate(i))
785    }
786
787    pub fn symbol_at(
788        &self,
789        file: &str,
790        byte_offset: u32,
791    ) -> Option<&crate::symbol::ResolvedSymbol> {
792        let range = self.symbols_by_file.get(file)?;
793        let symbols = &self.symbols[range.clone()];
794
795        // Primary: cursor is on an identifier token.
796        if let Some(sym) = symbols
797            .iter()
798            .filter(|s| s.span.start <= byte_offset && byte_offset < s.span.end)
799            .min_by_key(|s| s.span.end - s.span.start)
800        {
801            return Some(sym);
802        }
803
804        // Fallback: cursor is in a call-expression gap (e.g. the whitespace or
805        // argument list between two chained method calls).  Match against the
806        // full expression span recorded for call-like symbols and return the
807        // innermost (smallest) enclosing call, mirroring what an AST-walk to
808        // the innermost containing call expression would produce.
809        symbols
810            .iter()
811            .filter(|s| {
812                s.expr_span
813                    .is_some_and(|es| es.start <= byte_offset && byte_offset < es.end)
814            })
815            .min_by_key(|s| {
816                let es = s.expr_span.unwrap();
817                es.end - es.start
818            })
819    }
820}