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
56pub(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#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
102pub struct Position {
103 pub line: u32,
104 pub column: u32,
105}
106
107#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
109pub struct Range {
110 pub start: Position,
111 pub end: Position,
112}
113
114#[derive(Debug, Clone, PartialEq, Eq, Hash)]
121pub enum Name {
122 Class(std::sync::Arc<str>),
124 Function(std::sync::Arc<str>),
126 Method {
128 class: std::sync::Arc<str>,
129 name: std::sync::Arc<str>,
130 },
131 Property {
133 class: std::sync::Arc<str>,
134 name: std::sync::Arc<str>,
135 },
136 ClassConstant {
138 class: std::sync::Arc<str>,
139 name: std::sync::Arc<str>,
140 },
141 GlobalConstant(std::sync::Arc<str>),
143}
144
145impl Name {
146 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 pub fn class(fqcn: impl Into<std::sync::Arc<str>>) -> Self {
157 Name::Class(fqcn.into())
158 }
159
160 pub fn function(fqn: impl Into<std::sync::Arc<str>>) -> Self {
162 Name::Function(fqn.into())
163 }
164
165 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 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 pub fn global_constant(fqn: impl Into<std::sync::Arc<str>>) -> Self {
189 Name::GlobalConstant(fqn.into())
190 }
191
192 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
213pub(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#[derive(Debug, Clone, PartialEq, Eq)]
237pub enum SymbolLookupError {
238 NotFound,
240 NoSourceLocation,
243}
244
245#[derive(Debug, Clone, Copy, PartialEq, Eq)]
247pub enum LoadOutcome {
248 AlreadyLoaded,
250 Loaded,
253 NotResolvable,
257}
258
259impl LoadOutcome {
260 pub fn is_loaded(self) -> bool {
263 !matches!(self, LoadOutcome::NotResolvable)
264 }
265}
266
267pub trait ClassResolver: Send + Sync {
275 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#[derive(Debug, Clone)]
300pub struct HoverInfo {
301 pub ty: Type,
303 pub docstring: Option<String>,
305 pub definition: Option<mir_types::Location>,
307}
308
309#[derive(Debug)]
312pub struct DependencyGraph {
313 files: Vec<Arc<str>>,
314 file_ids: FxHashMap<Arc<str>, u32>,
315 dependencies: Vec<Vec<u32>>,
317 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 pub fn file_count(&self) -> usize {
355 self.files.len()
356 }
357
358 pub fn dependency_edge_count(&self) -> usize {
360 self.dependencies.iter().map(Vec::len).sum()
361 }
362
363 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 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 pub fn dependent_paths_of(&self, file: &str) -> Vec<Arc<str>> {
410 self.direct_arcs(file, &self.dependents).cloned().collect()
411 }
412
413 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 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 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 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
567pub 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;