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