Skip to main content

mir_analyzer/
lib.rs

1use rustc_hash::FxHashMap;
2use std::sync::{Arc, OnceLock};
3
4pub(crate) mod analyzer_db;
5pub(crate) mod attributes;
6pub mod batch;
7pub(crate) mod body_analysis;
8#[doc(hidden)]
9pub mod cache;
10pub(crate) mod call;
11pub(crate) mod class;
12pub(crate) mod collector;
13pub(crate) mod contradiction;
14#[doc(hidden)]
15pub mod db;
16pub(crate) mod dead_code;
17pub(crate) mod diagnostics;
18pub(crate) mod expr;
19pub mod file_analyzer;
20pub(crate) mod flow_state;
21pub(crate) mod generic;
22pub mod indexing;
23#[doc(hidden)]
24pub mod metrics;
25pub(crate) mod narrowing;
26#[doc(hidden)]
27pub mod parse_cache;
28#[doc(hidden)]
29pub mod parser;
30#[doc(hidden)]
31pub mod perf_fixture;
32pub mod php_version;
33pub mod prelude;
34pub(crate) mod reference_key;
35pub mod session;
36pub mod source_provider;
37pub(crate) mod stmt;
38#[doc(hidden)]
39pub mod stub_cache;
40#[doc(hidden)]
41pub mod stubs;
42pub(crate) mod subtype;
43pub mod suppression;
44pub(crate) mod taint;
45mod tmp_suffix;
46pub(crate) mod type_env;
47pub(crate) mod util;
48
49pub use batch::{
50    analyze_source, analyze_source_with_options, dead_code_issue_kinds, discover_files,
51    AnalysisResult, BatchOptions,
52};
53pub use file_analyzer::{FileAnalysis, FileAnalyzer};
54pub use indexing::{IndexBatchOutcome, IndexCancel, IndexParallelism};
55pub use parser::type_from_hint::type_from_hint;
56pub use parser::{DocblockParser, ParsedDocblock};
57pub use php_version::{ParsePhpVersionError, PhpVersion};
58pub use session::{AnalysisSession, AnalysisSnapshot, ReferenceIncludes, SubtypeClassSite};
59pub use source_provider::{FsSourceProvider, SourceProvider};
60
61/// Returns `Some((used, canonical))` when `written` and `canonical` FQCNs differ only in casing.
62/// Uses the short (last-segment) form when only the final segment is wrong and the namespace
63/// prefix is already correct; otherwise returns the full path so the mismatch is visible.
64pub(crate) fn fqcn_case_mismatch(written: &str, canonical: &str) -> Option<(String, String)> {
65    let w = written.trim_start_matches('\\');
66    let c = canonical.trim_start_matches('\\');
67    if w == c || !w.eq_ignore_ascii_case(c) {
68        return None;
69    }
70    let w_last = w.rsplit('\\').next().unwrap_or(w);
71    let c_last = c.rsplit('\\').next().unwrap_or(c);
72    if w_last != c_last {
73        let w_prefix = w.rsplit_once('\\').map_or("", |(p, _)| p);
74        let c_prefix = c.rsplit_once('\\').map_or("", |(p, _)| p);
75        if w_prefix == c_prefix {
76            return Some((w_last.to_string(), c_last.to_string()));
77        }
78    }
79    Some((w.to_string(), c.to_string()))
80}
81pub use stubs::{
82    is_builtin_constant, is_builtin_function, stub_files, stub_path_for_class,
83    ChainedClassResolver, StubClassResolver, StubVfs,
84};
85
86// ============================================================================
87// Analysis entry points
88// ============================================================================
89//
90// `AnalysisSession` is the single analysis engine. It supports two usage modes:
91//
92// - Batch (CLI, CI, bulk analysis): use `analyze_paths` / `BatchOptions` to
93//   run definition collection and body analysis over many files in parallel.
94//
95// - Incremental (LSP, watch mode): ingest files as they change; per-file
96//   diagnostics come from `FileAnalyzer::analyze_diagnostics_only`, and
97//   cursor navigation comes from `AnalysisSession::{symbol_at,name_at}`.
98//   Builder-style configuration (`with_cache`, `with_psr4`, …).
99//
100// The two phases of analysis are:
101//   1. Definition collection — discovers classes, functions, constants in a
102//      file and registers them in the salsa database.
103//   2. Body analysis (`BodyAnalyzer`) — walks function/method bodies,
104//      inferring types and emitting issues.
105
106/// A position in source code: 1-based line, 0-based codepoint column.
107#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
108pub struct Position {
109    pub line: u32,
110    pub column: u32,
111}
112
113/// A range in source code: start and end positions.
114#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
115pub struct Range {
116    pub start: Position,
117    pub end: Position,
118}
119
120/// A semantic identifier for a code entity that the analyzer can resolve.
121///
122/// Replaces the previous stringly-typed `&str` keys. Method names are
123/// normalized (lowercased) at construction since PHP method dispatch is
124/// case-insensitive — this prevents a class of correctness bugs where
125/// callers pass mixed-case names and get empty results.
126#[derive(Debug, Clone, PartialEq, Eq, Hash)]
127pub enum Name {
128    /// A class, interface, trait, or enum (FQCN).
129    Class(std::sync::Arc<str>),
130    /// A global function (FQN).
131    Function(std::sync::Arc<str>),
132    /// An instance or static method.
133    Method {
134        class: std::sync::Arc<str>,
135        name: std::sync::Arc<str>,
136    },
137    /// A class property.
138    Property {
139        class: std::sync::Arc<str>,
140        name: std::sync::Arc<str>,
141    },
142    /// A class / interface / enum constant.
143    ClassConstant {
144        class: std::sync::Arc<str>,
145        name: std::sync::Arc<str>,
146    },
147    /// A global constant.
148    GlobalConstant(std::sync::Arc<str>),
149}
150
151impl Name {
152    /// Construct a method symbol. Normalizes `name` to lowercase since PHP
153    /// methods are case-insensitive.
154    pub fn method(class: impl Into<std::sync::Arc<str>>, name: &str) -> Self {
155        Name::Method {
156            class: class.into(),
157            name: std::sync::Arc::from(name.to_ascii_lowercase()),
158        }
159    }
160
161    /// Construct a class symbol.
162    pub fn class(fqcn: impl Into<std::sync::Arc<str>>) -> Self {
163        Name::Class(fqcn.into())
164    }
165
166    /// Construct a function symbol.
167    pub fn function(fqn: impl Into<std::sync::Arc<str>>) -> Self {
168        Name::Function(fqn.into())
169    }
170
171    /// Construct a property symbol.
172    pub fn property(
173        class: impl Into<std::sync::Arc<str>>,
174        name: impl Into<std::sync::Arc<str>>,
175    ) -> Self {
176        Name::Property {
177            class: class.into(),
178            name: name.into(),
179        }
180    }
181
182    /// Construct a class constant symbol.
183    pub fn class_constant(
184        class: impl Into<std::sync::Arc<str>>,
185        name: impl Into<std::sync::Arc<str>>,
186    ) -> Self {
187        Name::ClassConstant {
188            class: class.into(),
189            name: name.into(),
190        }
191    }
192
193    /// Construct a global constant symbol.
194    pub fn global_constant(fqn: impl Into<std::sync::Arc<str>>) -> Self {
195        Name::GlobalConstant(fqn.into())
196    }
197
198    /// The codebase lookup key for this symbol (used internally for the
199    /// reference-locations index). Stable across releases.
200    ///
201    /// Kind-prefixed (`cls:`, `fn:`, `meth:`, `prop:`, `cnst:`, `gcnst:`) so
202    /// that a method, property, and class constant sharing the same class and
203    /// name (e.g. `Foo::bar` as both a property and a method) never collide
204    /// on the same reference-index entry — an unprefixed scheme merged their
205    /// usages, which both scrambled `references_to` results and hid truly
206    /// dead members behind an unrelated same-named symbol's usage.
207    pub fn codebase_key(&self) -> String {
208        match self {
209            Name::Class(fqcn) => format!("cls:{fqcn}"),
210            Name::Function(fqn) => format!("fn:{fqn}"),
211            Name::Method { class, name } => format!("meth:{class}::{name}"),
212            Name::Property { class, name } => format!("prop:{class}::{name}"),
213            Name::ClassConstant { class, name } => format!("cnst:{class}::{name}"),
214            Name::GlobalConstant(fqn) => format!("gcnst:{fqn}"),
215        }
216    }
217}
218
219/// Reduce a reference-index symbol key (as produced by [`Name::codebase_key`])
220/// to the bare class/function/global-constant name that
221/// `MirDatabase::symbol_defining_file` is keyed by.
222///
223/// Strips the kind prefix, then — for member keys (`meth:`/`prop:`/`cnst:`,
224/// shaped `Class::member`) — keeps only the class portion, since a member has
225/// no defining file of its own; only its owning class does.
226pub(crate) fn defining_file_lookup_key(symbol_key: &str) -> &str {
227    let stripped = symbol_key
228        .strip_prefix("meth:")
229        .or_else(|| symbol_key.strip_prefix("prop:"))
230        .or_else(|| symbol_key.strip_prefix("cnst:"))
231        .or_else(|| symbol_key.strip_prefix("cls:"))
232        .or_else(|| symbol_key.strip_prefix("fn:"))
233        .or_else(|| symbol_key.strip_prefix("gcnst:"))
234        .unwrap_or(symbol_key);
235    match stripped.split_once("::") {
236        Some((class, _)) => class,
237        None => stripped,
238    }
239}
240
241/// Reason a symbol lookup did not return a location.
242#[derive(Debug, Clone, PartialEq, Eq)]
243pub enum SymbolLookupError {
244    /// No such symbol exists in the codebase.
245    NotFound,
246    /// The symbol exists but has no recorded source location (e.g. a
247    /// stub-only declaration without a span).
248    NoSourceLocation,
249}
250
251/// Outcome of a [`AnalysisSession::load_class`] attempt.
252#[derive(Debug, Clone, Copy, PartialEq, Eq)]
253pub enum LoadOutcome {
254    /// The symbol was already present in the session; no work performed.
255    AlreadyLoaded,
256    /// The symbol was resolved by the configured [`ClassResolver`] and the
257    /// defining file was ingested.
258    Loaded,
259    /// No resolver is configured, the resolver could not map the FQCN to a
260    /// file, or the resolved file could not be read / did not define the
261    /// requested symbol.
262    NotResolvable,
263}
264
265impl LoadOutcome {
266    /// `true` when the symbol is now present in the session (whether it was
267    /// already there or just freshly loaded).
268    pub fn is_loaded(self) -> bool {
269        !matches!(self, LoadOutcome::NotResolvable)
270    }
271}
272
273/// Pluggable strategy for mapping a fully-qualified class name to the file
274/// that should define it. The analyzer never touches `vendor/` or the
275/// filesystem on its own — it asks a `ClassResolver` when a symbol is needed.
276///
277/// `mir_analyzer::Psr4Map` is the built-in implementation for Composer-based
278/// projects. Consumers with non-Composer conventions (WordPress, Drupal, a
279/// custom autoloader, a workspace-walk index) supply their own.
280pub trait ClassResolver: Send + Sync {
281    /// Resolve `fqcn` to the file that defines it. Returning `None` causes
282    /// the analyzer to fall back to emitting `UndefinedClass`.
283    fn resolve(&self, fqcn: &str) -> Option<std::path::PathBuf>;
284}
285
286impl ClassResolver for composer::Psr4Map {
287    fn resolve(&self, fqcn: &str) -> Option<std::path::PathBuf> {
288        composer::Psr4Map::resolve(self, fqcn)
289    }
290}
291
292impl std::fmt::Display for SymbolLookupError {
293    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
294        match self {
295            SymbolLookupError::NotFound => write!(f, "symbol not found"),
296            SymbolLookupError::NoSourceLocation => write!(f, "symbol has no source location"),
297        }
298    }
299}
300
301impl std::error::Error for SymbolLookupError {}
302
303/// File dependency graph: tracks which files depend on which other files.
304/// Used for incremental invalidation in LSP servers and build systems.
305#[derive(Debug)]
306pub struct DependencyGraph {
307    files: Vec<Arc<str>>,
308    file_ids: FxHashMap<Arc<str>, u32>,
309    /// Direct dependencies: file id → [file ids it depends on]
310    dependencies: Vec<Vec<u32>>,
311    /// Reverse dependencies: file id → [file ids that depend on it]
312    dependents: Vec<Vec<u32>>,
313    legacy_dependencies: OnceLock<FxHashMap<String, Vec<String>>>,
314    legacy_dependents: OnceLock<FxHashMap<String, Vec<String>>>,
315}
316
317impl Clone for DependencyGraph {
318    fn clone(&self) -> Self {
319        Self {
320            files: self.files.clone(),
321            file_ids: self.file_ids.clone(),
322            dependencies: self.dependencies.clone(),
323            dependents: self.dependents.clone(),
324            legacy_dependencies: OnceLock::new(),
325            legacy_dependents: OnceLock::new(),
326        }
327    }
328}
329
330impl DependencyGraph {
331    pub(crate) fn from_compact_parts(
332        files: Vec<Arc<str>>,
333        file_ids: FxHashMap<Arc<str>, u32>,
334        dependencies: Vec<Vec<u32>>,
335        dependents: Vec<Vec<u32>>,
336    ) -> Self {
337        Self {
338            files,
339            file_ids,
340            dependencies,
341            dependents,
342            legacy_dependencies: OnceLock::new(),
343            legacy_dependents: OnceLock::new(),
344        }
345    }
346
347    /// Number of files tracked by this graph.
348    pub fn file_count(&self) -> usize {
349        self.files.len()
350    }
351
352    /// Number of direct dependency edges.
353    pub fn dependency_edge_count(&self) -> usize {
354        self.dependencies.iter().map(Vec::len).sum()
355    }
356
357    /// Number of reverse dependency edges.
358    pub fn dependent_edge_count(&self) -> usize {
359        self.dependents.iter().map(Vec::len).sum()
360    }
361
362    fn file_path(&self, id: u32) -> &Arc<str> {
363        &self.files[id as usize]
364    }
365
366    fn stringify_adjacency(&self, adjacency: &[Vec<u32>]) -> FxHashMap<String, Vec<String>> {
367        adjacency
368            .iter()
369            .enumerate()
370            .filter(|(_, deps)| !deps.is_empty())
371            .map(|(file_id, deps)| {
372                (
373                    self.files[file_id].to_string(),
374                    deps.iter()
375                        .map(|&dep_id| self.file_path(dep_id).to_string())
376                        .collect(),
377                )
378            })
379            .collect()
380    }
381
382    fn direct_arcs<'a>(
383        &'a self,
384        file: &str,
385        adjacency: &'a [Vec<u32>],
386    ) -> impl Iterator<Item = &'a Arc<str>> {
387        self.file_ids
388            .get(file)
389            .and_then(|&id| adjacency.get(id as usize))
390            .into_iter()
391            .flatten()
392            .map(|&id| self.file_path(id))
393    }
394
395    /// Files that `file` directly depends on, as interned paths.
396    pub fn dependency_paths_of(&self, file: &str) -> Vec<Arc<str>> {
397        self.direct_arcs(file, &self.dependencies)
398            .cloned()
399            .collect()
400    }
401
402    /// Files that directly depend on `file`, as interned paths.
403    pub fn dependent_paths_of(&self, file: &str) -> Vec<Arc<str>> {
404        self.direct_arcs(file, &self.dependents).cloned().collect()
405    }
406
407    /// Files that `file` directly depends on (imports, parent classes, interfaces, traits).
408    pub fn dependencies_of(&self, file: &str) -> &[String] {
409        self.legacy_dependencies
410            .get_or_init(|| self.stringify_adjacency(&self.dependencies))
411            .get(file)
412            .map(|v| v.as_slice())
413            .unwrap_or(&[])
414    }
415
416    /// Files that directly depend on `file` (reverse edge).
417    pub fn dependents_of(&self, file: &str) -> &[String] {
418        self.legacy_dependents
419            .get_or_init(|| self.stringify_adjacency(&self.dependents))
420            .get(file)
421            .map(|v| v.as_slice())
422            .unwrap_or(&[])
423    }
424
425    /// All files transitively depended upon by `file` (including indirect).
426    pub fn transitive_dependencies(&self, file: &str) -> Vec<String> {
427        let mut visited = rustc_hash::FxHashSet::default();
428        let Some(&seed) = self.file_ids.get(file) else {
429            return Vec::new();
430        };
431        let mut queue = vec![seed];
432        visited.insert(seed);
433        let mut result = Vec::new();
434
435        while let Some(current) = queue.pop() {
436            for &dep in &self.dependencies[current as usize] {
437                if visited.insert(dep) {
438                    queue.push(dep);
439                    result.push(self.file_path(dep).to_string());
440                }
441            }
442        }
443        result
444    }
445
446    /// All files that transitively depend on `file` (reverse transitive).
447    pub fn transitive_dependents(&self, file: &str) -> Vec<String> {
448        let mut visited = rustc_hash::FxHashSet::default();
449        let Some(&seed) = self.file_ids.get(file) else {
450            return Vec::new();
451        };
452        let mut queue = vec![seed];
453        visited.insert(seed);
454        let mut result = Vec::new();
455
456        while let Some(current) = queue.pop() {
457            for &dep in &self.dependents[current as usize] {
458                if visited.insert(dep) {
459                    queue.push(dep);
460                    result.push(self.file_path(dep).to_string());
461                }
462            }
463        }
464        result
465    }
466}
467
468pub mod symbol;
469pub use mir_codebase::definitions::{DeclaredParam, FunctionDef, TemplateParam, Visibility};
470pub use mir_issues::{Issue, IssueKind, Severity};
471pub use mir_types::Type;
472
473#[cfg(test)]
474mod dependency_graph_tests {
475    use super::*;
476
477    fn graph(edges: &[(&str, &[&str])]) -> DependencyGraph {
478        let mut files: Vec<Arc<str>> = edges
479            .iter()
480            .flat_map(|(from, deps)| {
481                std::iter::once(*from)
482                    .chain(deps.iter().copied())
483                    .map(Arc::<str>::from)
484            })
485            .collect();
486        files.sort();
487        files.dedup();
488
489        let file_ids: FxHashMap<Arc<str>, u32> = files
490            .iter()
491            .enumerate()
492            .map(|(id, file)| (file.clone(), id as u32))
493            .collect();
494        let mut dependencies = vec![Vec::new(); files.len()];
495        let mut dependents = vec![Vec::new(); files.len()];
496
497        for (from, deps) in edges {
498            let from_id = file_ids[*from];
499            for dep in *deps {
500                let dep_id = file_ids[*dep];
501                dependencies[from_id as usize].push(dep_id);
502                dependents[dep_id as usize].push(from_id);
503            }
504        }
505        for adjacency in [&mut dependencies, &mut dependents] {
506            for deps in adjacency {
507                deps.sort();
508                deps.dedup();
509            }
510        }
511
512        DependencyGraph::from_compact_parts(files, file_ids, dependencies, dependents)
513    }
514
515    #[test]
516    fn transitive_traversal_deduplicates_diamond_graphs() {
517        let graph = graph(&[
518            ("a.php", &["b.php", "c.php"]),
519            ("b.php", &["d.php"]),
520            ("c.php", &["d.php"]),
521        ]);
522
523        let deps = graph.transitive_dependencies("a.php");
524        assert_eq!(
525            deps.iter().filter(|path| path.as_str() == "d.php").count(),
526            1
527        );
528        assert_eq!(deps.len(), 3);
529
530        let dependents = graph.transitive_dependents("d.php");
531        assert_eq!(
532            dependents
533                .iter()
534                .filter(|path| path.as_str() == "a.php")
535                .count(),
536            1
537        );
538        assert_eq!(dependents.len(), 3);
539    }
540
541    #[test]
542    fn direct_arc_accessors_do_not_require_legacy_string_maps() {
543        let graph = graph(&[("consumer.php", &["service.php"])]);
544
545        let deps = graph.dependency_paths_of("consumer.php");
546        assert_eq!(deps, vec![Arc::<str>::from("service.php")]);
547        assert!(graph.legacy_dependencies.get().is_none());
548
549        let dependents = graph.dependent_paths_of("service.php");
550        assert_eq!(dependents, vec![Arc::<str>::from("consumer.php")]);
551        assert!(graph.legacy_dependents.get().is_none());
552
553        assert_eq!(
554            graph.dependencies_of("consumer.php"),
555            &["service.php".to_string()]
556        );
557        assert!(graph.legacy_dependencies.get().is_some());
558    }
559}
560
561/// Convert a parser [`php_ast::Span`] (byte-offset range) into a
562/// [`mir_types::Location`] (file path + 1-based line range +
563/// 0-based codepoint columns) using `source` and the parser's `source_map`.
564///
565/// This is the canonical way for consumers to translate body-analysis result spans
566/// (e.g. [`crate::symbol::ResolvedSymbol::span`]) into source locations they
567/// can hand to their own protocol layer. Consumers that need different
568/// position semantics (LSP UTF-16 code units, byte offsets, etc.) translate
569/// from this `Location` rather than re-implementing the column math.
570pub fn location_from_span(
571    span: php_ast::Span,
572    file: std::sync::Arc<str>,
573    source: &str,
574    source_map: &php_rs_parser::source_map::SourceMap,
575) -> mir_types::Location {
576    let (line, col_start) = diagnostics::offset_to_line_col(source, span.start, source_map);
577    let (line_end, col_end) = if span.start < span.end {
578        diagnostics::offset_to_line_col(source, span.end, source_map)
579    } else {
580        (line, col_start)
581    };
582    mir_types::Location {
583        file,
584        line,
585        line_end,
586        col_start,
587        col_end: diagnostics::clamp_col_end(line, line_end, col_start, col_end),
588    }
589}
590pub use symbol::{DeclarationKind, DocumentSymbol, ReferenceKind, ResolvedSymbol};
591
592pub mod composer;
593pub use composer::{ComposerError, Psr4Map};
594pub use type_env::ScopeId;
595
596#[doc(hidden)]
597pub mod test_utils;