1use 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
32pub fn dead_code_issue_kinds() -> &'static [&'static str] {
39 &[
40 "UnusedMethod",
41 "UnusedProperty",
42 "UnusedFunction",
43 "UnusedClass",
44 ]
45}
46
47#[derive(Clone, Default)]
53pub struct BatchOptions {
54 pub suppressed_issue_kinds: HashSet<String>,
59 pub on_file_done: Option<Arc<dyn Fn() + Send + Sync>>,
61 pub php_version_override: Option<PhpVersion>,
64 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 pub fn without_symbols(mut self) -> Self {
101 self.skip_symbols = true;
102 self
103 }
104
105 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 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 #[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 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 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 let files: Vec<Arc<str>> = cache
221 .iter()
222 .filter_map(|(f, m)| m.as_ref().map(|_| f.clone()))
223 .collect();
224 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 let pre_suppressed: Vec<&Issue> = file_issues
248 .iter()
249 .filter(|i| i.suppressed)
250 .copied()
251 .collect();
252 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 fn refresh_workspace_index(&self) {
292 let mut guard = self.db.salsa.write();
293 guard.rebuild_workspace_symbol_index();
294 }
295
296 fn load_batch_stubs(&self, php_version: PhpVersion) {
300 {
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 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 self.db
313 .ingest_user_stubs(&self.user_stub_files, &self.user_stub_dirs);
314
315 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
328pub 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 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.clone());
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
371fn 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
387fn 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
408pub 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
441pub(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) = ¶m.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) = ¶m.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 pub symbols: Vec<crate::symbol::ResolvedSymbol>,
713 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 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 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}