1use std::sync::Arc;
2
3use super::*;
4
5impl AnalysisSession {
6 pub fn analyze_file_diagnostics(&mut self, file: &str, source: &str) -> crate::FileAnalysis {
13 let file: Arc<str> = Arc::from(file);
14 self.ingest_file(file.clone(), Arc::from(source));
15
16 let (mut issues, parsed) = {
19 let view = self.db_view();
20 let db = view.db();
21 let Some(sf) = db.lookup_source_file(file.as_ref()) else {
22 return crate::FileAnalysis {
23 issues: Vec::new(),
24 symbols: Vec::new(),
25 };
26 };
27 let defs = crate::db::collect_file_definitions(db, sf);
28 let prepared = crate::db::prepare_analysis_file(db, sf);
29 let parsed = (!prepared.has_hard_parse_errors)
30 .then(|| (prepared.text.clone(), prepared.parsed.0.clone()));
31 (Arc::unwrap_or_clone(defs.issues.clone()), parsed)
32 };
33
34 if let Some((text, parsed)) = parsed {
35 let analysis = crate::FileAnalyzer::new(self).analyze_diagnostics_only(
36 file.clone(),
37 text.as_ref(),
38 &parsed.program,
39 &parsed.source_map,
40 );
41 issues.extend(analysis.issues);
42 }
43
44 self.apply_suppressions_and_emit_unused(&mut issues, std::slice::from_ref(&file));
45 crate::FileAnalysis {
46 issues,
47 symbols: Vec::new(),
48 }
49 }
50
51 pub fn name_at(&mut self, file: &str, byte_offset: u32) -> Option<crate::Name> {
57 crate::FileAnalyzer::new(self).name_at(Arc::from(file), byte_offset)
58 }
59
60 pub fn symbol_at(&mut self, file: &str, byte_offset: u32) -> Option<crate::ResolvedSymbol> {
69 crate::FileAnalyzer::new(self).symbol_at(Arc::from(file), byte_offset)
70 }
71
72 pub fn definition_of(
85 &mut self,
86 symbol: &crate::Name,
87 ) -> Result<mir_types::Location, crate::SymbolLookupError> {
88 self.load_symbol_owner(symbol);
89 self.definition_of_cached(symbol)
90 }
91
92 fn load_symbol_owner(&mut self, symbol: &crate::Name) {
95 match symbol {
96 crate::Name::Class(fqn) | crate::Name::Function(fqn) => {
97 let _ = self.load_class(fqn.as_ref());
98 }
99 crate::Name::Method { class, .. }
100 | crate::Name::Property { class, .. }
101 | crate::Name::ClassConstant { class, .. } => {
102 let _ = self.load_class(class.as_ref());
103 }
104 crate::Name::GlobalConstant(_) => {}
105 }
106 }
107
108 pub fn definition_of_cached(
112 &self,
113 symbol: &crate::Name,
114 ) -> Result<mir_types::Location, crate::SymbolLookupError> {
115 self.query_snapshot(|snap| snap.definition_of_cached(symbol))
116 }
117
118 #[doc(hidden)]
122 pub fn reference_locations(&self, symbol: &str) -> Vec<(Arc<str>, u32, u16, u16)> {
123 use crate::db::MirDatabase;
124 let db = self.snapshot_db();
125 db.reference_locations(symbol)
126 }
127
128 pub fn subtype_files(&mut self, class_fqn: &str) -> Vec<Arc<str>> {
139 self.prepare_for_query(None);
140 self.query_snapshot(|snap| snap.subtype_files(class_fqn))
141 }
142
143 pub fn indexed_use_import_locations(
148 &mut self,
149 symbol: &crate::Name,
150 files: &[Arc<str>],
151 ) -> Vec<(Arc<str>, crate::Range)> {
152 self.indexed_references_to(
153 symbol,
154 files,
155 false,
156 crate::ReferenceIncludes::UseImports,
157 &|| false,
158 )
159 .unwrap_or_default()
160 }
161
162 pub fn indexed_references_to(
170 &mut self,
171 symbol: &crate::Name,
172 files: &[Arc<str>],
173 include_declaration: bool,
174 includes: crate::ReferenceIncludes,
175 should_cancel: &(dyn Fn() -> bool + Sync),
176 ) -> Option<Vec<(Arc<str>, crate::Range)>> {
177 if self.db.salsa.needs_index_settle()
181 && !self.settle_workspace_index_cancellable(should_cancel)
182 {
183 return None;
184 }
185 let key = {
189 let snap = self.db_view();
190 let key = snap.reference_query_key(symbol, files, include_declaration, includes);
191 if let Some(hit) = self.index.ref_queries.get(&key) {
192 return Some(hit);
193 }
194 key
195 };
196 if should_cancel() {
197 return None;
198 }
199 let stale = self.db_view().stale_reference_candidates(symbol, files);
200
201 if !stale.is_empty() {
202 {
205 let mut session = self.defer_revision_bumps();
206 for path in &stale {
207 if !session.prepare_file_for_analysis_cancellable(path, should_cancel) {
208 return None;
209 }
210 }
211 }
212 if should_cancel() {
213 return None;
214 }
215 self.query_snapshot(|snap| snap.commit_reference_candidates(&stale));
216 }
217
218 if include_declaration {
219 self.load_symbol_owner(symbol);
220 }
221 let snap = self.db_view();
222 let out = snap.read_references(symbol, files, include_declaration, includes);
223 snap.memoize_references(key, &out);
224 Some(out)
225 }
226
227 pub fn declaration_name_range(
231 &mut self,
232 symbol: &crate::Name,
233 ) -> Option<(Arc<str>, crate::Range)> {
234 self.load_symbol_owner(symbol);
235 self.db_view().declaration_name_range(symbol)
236 }
237
238 pub fn indexed_subtype_classes(
240 &mut self,
241 class_fqn: &str,
242 files: &[Arc<str>],
243 include_trait_users: bool,
244 ) -> Vec<SubtypeClassSite> {
245 self.prepare_for_query(None);
246 self.query_snapshot(|snap| {
247 snap.indexed_subtype_classes(class_fqn, files, include_trait_users)
248 })
249 }
250
251 pub fn indexed_method_implementations(
253 &mut self,
254 class_fqn: &str,
255 method: &str,
256 files: &[Arc<str>],
257 ) -> Vec<(Arc<str>, Arc<str>, crate::Range)> {
258 self.prepare_for_query(None);
259 self.query_snapshot(|snap| snap.indexed_method_implementations(class_fqn, method, files))
260 }
261
262 pub fn class_issues(&mut self, files: &[Arc<str>]) -> Vec<crate::Issue> {
266 self.prepare_for_query(None);
267 self.query_snapshot(|snap| snap.class_issues(files))
268 }
269
270 pub fn collector_issues(&self, files: &[Arc<str>]) -> Vec<crate::Issue> {
274 self.query_snapshot(|snap| snap.collector_issues(files))
275 }
276
277 pub fn document_symbols(&self, file: &str) -> Vec<crate::symbol::DocumentSymbol> {
283 use crate::symbol::{DeclarationKind, DocumentSymbol};
284
285 let db = self.snapshot_db();
286 let Some(sf) = db.lookup_source_file(file) else {
287 return Vec::new();
288 };
289 let defs = crate::db::collect_file_definitions(&db, sf);
290 let mut out: Vec<DocumentSymbol> = Vec::new();
291
292 let class_children = |methods: &mir_codebase::definitions::MemberMap<
293 Arc<mir_codebase::definitions::MethodDef>,
294 >,
295 props: Option<
296 &mir_codebase::definitions::MemberMap<mir_codebase::definitions::PropertyDef>,
297 >,
298 consts: &mir_codebase::definitions::MemberMap<
299 mir_codebase::definitions::ConstantDef,
300 >,
301 is_enum: bool|
302 -> Vec<DocumentSymbol> {
303 let mut out: Vec<DocumentSymbol> = Vec::new();
304 for (_, m) in methods.iter() {
305 out.push(DocumentSymbol {
306 name: m.name.clone(),
307 kind: DeclarationKind::Method,
308 location: m.location.clone(),
309 children: Vec::new(),
310 });
311 }
312 if let Some(props) = props {
313 for (_, p) in props.iter() {
314 out.push(DocumentSymbol {
315 name: p.name.clone(),
316 kind: DeclarationKind::Property,
317 location: p.location.clone(),
318 children: Vec::new(),
319 });
320 }
321 }
322 let const_kind = if is_enum {
323 DeclarationKind::EnumCase
324 } else {
325 DeclarationKind::Constant
326 };
327 for (_, c) in consts.iter() {
328 out.push(DocumentSymbol {
329 name: c.name.clone(),
330 kind: const_kind,
331 location: c.location.clone(),
332 children: Vec::new(),
333 });
334 }
335 out
336 };
337
338 for c in defs.slice.classes.iter() {
339 out.push(DocumentSymbol {
340 name: c.fqcn.clone(),
341 kind: DeclarationKind::Class,
342 location: c.location.clone(),
343 children: class_children(
344 &c.own_methods,
345 Some(&c.own_properties),
346 &c.own_constants,
347 false,
348 ),
349 });
350 }
351 for i in defs.slice.interfaces.iter() {
352 out.push(DocumentSymbol {
353 name: i.fqcn.clone(),
354 kind: DeclarationKind::Interface,
355 location: i.location.clone(),
356 children: class_children(&i.own_methods, None, &i.own_constants, false),
357 });
358 }
359 for t in defs.slice.traits.iter() {
360 out.push(DocumentSymbol {
361 name: t.fqcn.clone(),
362 kind: DeclarationKind::Trait,
363 location: t.location.clone(),
364 children: class_children(
365 &t.own_methods,
366 Some(&t.own_properties),
367 &t.own_constants,
368 false,
369 ),
370 });
371 }
372 for e in defs.slice.enums.iter() {
373 let mut children = class_children(&e.own_methods, None, &e.own_constants, true);
374 for (_, case) in e.cases.iter() {
375 children.push(DocumentSymbol {
376 name: case.name.clone(),
377 kind: DeclarationKind::EnumCase,
378 location: case.location.clone(),
379 children: Vec::new(),
380 });
381 }
382 out.push(DocumentSymbol {
383 name: e.fqcn.clone(),
384 kind: DeclarationKind::Enum,
385 location: e.location.clone(),
386 children,
387 });
388 }
389 for f in defs.slice.functions.iter() {
390 out.push(DocumentSymbol {
391 name: f.fqn.clone(),
392 kind: DeclarationKind::Function,
393 location: f.location.clone(),
394 children: Vec::new(),
395 });
396 }
397 for (name, _) in defs.slice.constants.iter() {
398 out.push(DocumentSymbol {
399 name: name.clone(),
400 kind: DeclarationKind::Constant,
401 location: None,
402 children: Vec::new(),
403 });
404 }
405 out
406 }
407}
408
409#[derive(Debug, Clone)]
412pub struct SubtypeClassSite {
413 pub fqcn: Arc<str>,
415 pub kind: crate::db::ClassLikeKind,
416 pub is_abstract: bool,
417 pub file: Arc<str>,
418 pub range: crate::Range,
420}
421
422pub(super) fn span_range(line: u32, col_start: u32, col_end: u32) -> crate::Range {
425 crate::Range {
426 start: crate::Position {
427 line,
428 column: col_start,
429 },
430 end: crate::Position {
431 line,
432 column: col_end,
433 },
434 }
435}
436
437pub(super) fn identifier_char_col(
441 line: &str,
442 needle: &str,
443 min_col: usize,
444 case_insensitive: bool,
445) -> Option<u32> {
446 if needle.is_empty() {
447 return None;
448 }
449 let is_ident = |c: char| c.is_ascii_alphanumeric() || c == '_';
450 let chars: Vec<char> = line.chars().collect();
451 let needle_chars: Vec<char> = needle.chars().collect();
452 let n = needle_chars.len();
453 if chars.len() < n {
454 return None;
455 }
456 for start in min_col..=chars.len().saturating_sub(n) {
457 let matches = chars[start..start + n]
458 .iter()
459 .zip(needle_chars.iter())
460 .all(|(a, b)| {
461 if case_insensitive {
462 a.eq_ignore_ascii_case(b)
463 } else {
464 a == b
465 }
466 });
467 if !matches {
468 continue;
469 }
470 let before_ok = start == 0 || !is_ident(chars[start - 1]);
471 let after = start + n;
472 let after_ok = after >= chars.len() || !is_ident(chars[after]);
473 if before_ok && after_ok {
474 return Some(start as u32);
475 }
476 }
477 None
478}
479
480#[cfg(test)]
491fn mentions_identifier(hay: &str, needle: &str) -> bool {
492 let hay = hay.as_bytes();
493 let needle = needle.as_bytes();
494 let n = needle.len();
495 if n == 0 || hay.len() < n {
496 return false;
497 }
498 let is_ident = |b: u8| b.is_ascii_alphanumeric() || b == b'_';
499 let first = needle[0].to_ascii_lowercase();
500 for i in 0..=(hay.len() - n) {
501 if hay[i].to_ascii_lowercase() != first || !hay[i..i + n].eq_ignore_ascii_case(needle) {
502 continue;
503 }
504 if (i == 0 || !is_ident(hay[i - 1])) && (i + n == hay.len() || !is_ident(hay[i + n])) {
505 return true;
506 }
507 }
508 false
509}
510
511fn short(fqn: &str) -> &str {
512 fqn.rsplit('\\').next().unwrap_or(fqn)
513}
514
515pub(super) struct ReferenceGate {
523 pub(super) idents: Vec<String>,
524 pub(super) raw: Vec<String>,
525}
526
527impl ReferenceGate {
528 pub(super) fn for_symbol(db: &MirDbStorage, symbol: &crate::Name) -> Self {
554 if let crate::Name::Method { class, name } = symbol {
555 if name.as_ref() == "__construct" && !class.is_empty() {
556 return Self {
557 idents: reference_gate_needles(symbol),
558 raw: vec!["->__construct".to_string(), "::__construct".to_string()],
559 };
560 }
561 if name.as_ref() != "__construct" && name.as_ref() != "__invoke" && !class.is_empty() {
562 let here = crate::db::Fqcn::from_str(db, class.as_ref());
563 let is_static = crate::db::find_method_in_chain(db, here, name)
564 .map(|(_, m)| m.is_static)
565 .unwrap_or(false);
566 if is_static || crate::db::class_exists(db, class.as_ref()) {
567 return Self {
568 idents: vec![name.to_string()],
569 raw: Vec::new(),
570 };
571 }
572 }
573 }
574 Self {
575 idents: reference_gate_needles(symbol),
576 raw: Vec::new(),
577 }
578 }
579}
580
581fn reference_gate_needles(symbol: &crate::Name) -> Vec<String> {
587 let mut needles = match symbol {
588 crate::Name::Class(f) | crate::Name::Function(f) | crate::Name::GlobalConstant(f) => {
589 vec![short(f).to_string()]
590 }
591 crate::Name::Method { class, name } if name.as_ref() == "__construct" => {
603 if class.is_empty() {
604 vec![name.to_string()]
607 } else {
608 vec![short(class).to_string()]
609 }
610 }
611 crate::Name::Method { class, name }
612 | crate::Name::Property { class, name }
613 | crate::Name::ClassConstant { class, name } => {
614 let mut v = vec![name.to_string()];
615 if !class.is_empty() {
616 v.push(short(class).to_string());
617 }
618 v
619 }
620 };
621 needles.retain(|n| !n.is_empty());
624 needles
625}
626
627#[cfg(test)]
628mod tests {
629 use super::*;
630
631 #[test]
632 fn mentions_identifier_is_case_insensitive_and_word_bounded() {
633 assert!(mentions_identifier("$this->save();", "save"));
634 assert!(mentions_identifier("new COLOR()", "Color"));
635 assert!(mentions_identifier("use App\\Color as Paint;", "color"));
636 assert!(!mentions_identifier("$this->saveAll();", "save"));
637 assert!(!mentions_identifier("return $unsaved;", "save"));
638 assert!(!mentions_identifier("no occurrence", "save"));
639 assert!(!mentions_identifier("anything", ""));
640 assert!(!mentions_identifier("function xÉclairFoo() {}", "Éclair"));
643 assert!(mentions_identifier("implements Éclair {}", "Éclair"));
644 }
645
646 #[test]
647 fn mention_scanner_membership_equals_per_needle_scans() {
648 use crate::db::MentionScanner;
653 use std::sync::Arc;
654 let universe = ["Color", "save", "ColorPicker", "Éclair", "C1", "_Wrap"];
655 let names: Vec<(mir_types::Name, bool)> = universe
656 .iter()
657 .map(|s| (mir_types::Name::new(s).ascii_lowercase(), false))
658 .collect();
659 let scanner = Arc::new(MentionScanner::build(1, names).unwrap());
660 let hays = [
661 "$this->save();",
662 "new COLOR()",
663 "use App\\Color as Paint;",
664 "$this->saveAll();",
665 "return $unsaved;",
666 "new ColorPicker(); Color::save();",
667 "function xÉclairFoo() {}",
668 "implements Éclair {}",
669 "colorsave savecolor color_save",
670 "class C1 extends _Wrap {}",
671 "",
672 ];
673 for hay in hays {
674 let scanned = scanner.scan(hay);
675 for needle in universe {
676 let expected = mentions_identifier(hay, needle);
677 let name = mir_types::Name::new(needle).ascii_lowercase();
678 assert_eq!(
679 scanned.binary_search(&name).is_ok(),
680 expected,
681 "needle {needle:?} on {hay:?}"
682 );
683 }
684 }
685 }
686
687 #[test]
688 fn gate_needles_cover_member_and_owner_class() {
689 let n = reference_gate_needles(&crate::Name::method("App\\Job", "run"));
692 assert!(n.contains(&"run".to_string()) && n.contains(&"Job".to_string()));
693 let n = reference_gate_needles(&crate::Name::class("App\\Ui\\Color"));
694 assert_eq!(n, vec!["Color".to_string()]);
695 let n = reference_gate_needles(&crate::Name::method("", "run"));
697 assert_eq!(n, vec!["run".to_string()]);
698 }
699
700 #[test]
701 fn gate_needles_for_constructor_scope_to_owner_class_only() {
702 let n = reference_gate_needles(&crate::Name::method("App\\Job", "__construct"));
707 assert_eq!(n, vec!["Job".to_string()]);
708 let n = reference_gate_needles(&crate::Name::method("", "__construct"));
710 assert_eq!(n, vec!["__construct".to_string()]);
711 }
712
713 fn session_with(files: &[(&str, &str)]) -> crate::AnalysisSession {
714 let mut session = crate::AnalysisSession::new(crate::PhpVersion::LATEST);
715 for (path, text) in files {
716 session.set_file_text(Arc::from(*path), Arc::from(*text));
717 }
718 session
719 }
720
721 #[test]
722 fn gate_static_method_is_member_name_only() {
723 let session = session_with(&[
728 (
729 "owner.php",
730 "<?php\nclass Owner { public static function m(): void {} }\n",
731 ),
732 ("sub.php", "<?php\nclass Sub extends Owner {}\n"),
733 ]);
734 let gate = session
735 .snapshot()
736 .reference_gate(&crate::Name::method("Owner", "m"));
737 assert_eq!(gate.idents, vec!["m".to_string()]);
738 assert!(gate.raw.is_empty());
739 }
740
741 #[test]
742 fn gate_instance_method_is_member_name_only() {
743 let session = session_with(&[(
744 "owner.php",
745 "<?php\nclass Owner { public function m(): void {} }\n",
746 )]);
747 let gate = session
748 .snapshot()
749 .reference_gate(&crate::Name::method("Owner", "m"));
750 assert_eq!(gate.idents, vec!["m".to_string()]);
751 assert!(gate.raw.is_empty());
752 }
753
754 #[test]
755 fn gate_invoke_keeps_owner_needle() {
756 let session = session_with(&[(
757 "owner.php",
758 "<?php\nclass Owner { public function __invoke(): void {} }\n",
759 )]);
760 let gate = session
761 .snapshot()
762 .reference_gate(&crate::Name::method("Owner", "__invoke"));
763 assert_eq!(
764 gate.idents,
765 reference_gate_needles(&crate::Name::method("Owner", "__invoke"))
766 );
767 assert!(gate.raw.is_empty());
768 }
769
770 #[test]
771 fn gate_constructor_adds_raw_call_tokens() {
772 let session = session_with(&[(
777 "owner.php",
778 "<?php\nclass Owner { public function __construct() {} }\n",
779 )]);
780 let gate = session
781 .snapshot()
782 .reference_gate(&crate::Name::method("Owner", "__construct"));
783 assert_eq!(
784 gate.idents,
785 reference_gate_needles(&crate::Name::method("Owner", "__construct"))
786 );
787 assert_eq!(
788 gate.raw,
789 vec!["->__construct".to_string(), "::__construct".to_string()]
790 );
791 }
792
793 #[test]
794 fn gate_unresolvable_owner_falls_back_to_general_needles() {
795 let session = session_with(&[(
796 "owner.php",
797 "<?php\nclass Owner { public static function m(): void {} }\n",
798 )]);
799 let gate = session
800 .snapshot()
801 .reference_gate(&crate::Name::method("Nonexistent\\Missing", "m"));
802 assert_eq!(
803 gate.idents,
804 reference_gate_needles(&crate::Name::method("Nonexistent\\Missing", "m"))
805 );
806 assert!(gate.raw.is_empty());
807 }
808}