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
61pub(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#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
108pub struct Position {
109 pub line: u32,
110 pub column: u32,
111}
112
113#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
115pub struct Range {
116 pub start: Position,
117 pub end: Position,
118}
119
120#[derive(Debug, Clone, PartialEq, Eq, Hash)]
127pub enum Name {
128 Class(std::sync::Arc<str>),
130 Function(std::sync::Arc<str>),
132 Method {
134 class: std::sync::Arc<str>,
135 name: std::sync::Arc<str>,
136 },
137 Property {
139 class: std::sync::Arc<str>,
140 name: std::sync::Arc<str>,
141 },
142 ClassConstant {
144 class: std::sync::Arc<str>,
145 name: std::sync::Arc<str>,
146 },
147 GlobalConstant(std::sync::Arc<str>),
149}
150
151impl Name {
152 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 pub fn class(fqcn: impl Into<std::sync::Arc<str>>) -> Self {
163 Name::Class(fqcn.into())
164 }
165
166 pub fn function(fqn: impl Into<std::sync::Arc<str>>) -> Self {
168 Name::Function(fqn.into())
169 }
170
171 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 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 pub fn global_constant(fqn: impl Into<std::sync::Arc<str>>) -> Self {
195 Name::GlobalConstant(fqn.into())
196 }
197
198 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
219pub(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#[derive(Debug, Clone, PartialEq, Eq)]
243pub enum SymbolLookupError {
244 NotFound,
246 NoSourceLocation,
249}
250
251#[derive(Debug, Clone, Copy, PartialEq, Eq)]
253pub enum LoadOutcome {
254 AlreadyLoaded,
256 Loaded,
259 NotResolvable,
263}
264
265impl LoadOutcome {
266 pub fn is_loaded(self) -> bool {
269 !matches!(self, LoadOutcome::NotResolvable)
270 }
271}
272
273pub trait ClassResolver: Send + Sync {
281 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#[derive(Debug)]
306pub struct DependencyGraph {
307 files: Vec<Arc<str>>,
308 file_ids: FxHashMap<Arc<str>, u32>,
309 dependencies: Vec<Vec<u32>>,
311 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 pub fn file_count(&self) -> usize {
349 self.files.len()
350 }
351
352 pub fn dependency_edge_count(&self) -> usize {
354 self.dependencies.iter().map(Vec::len).sum()
355 }
356
357 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 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 pub fn dependent_paths_of(&self, file: &str) -> Vec<Arc<str>> {
404 self.direct_arcs(file, &self.dependents).cloned().collect()
405 }
406
407 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 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 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 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
561pub 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;