1use rustc_hash::{FxHashMap as HashMap, FxHashSet as HashSet};
18use std::ops::ControlFlow;
19use std::path::{Path, PathBuf};
20use std::sync::{Arc, LazyLock};
21
22use mir_codebase::definitions::StubSlice;
23use php_ast::owned::visitor::{walk_owned_expr, walk_owned_program, OwnedVisitor};
24use php_ast::owned::ExprKind;
25use php_lexer::TokenKind;
26use rayon::prelude::*;
27
28use crate::db::MirDbStorage;
29use crate::php_version::PhpVersion;
30
31include!(concat!(env!("OUT_DIR"), "/stub_files.rs"));
33
34include!(concat!(env!("OUT_DIR"), "/phpstorm_builtin_fns.rs"));
37
38pub(crate) fn stub_content_for_path(path: &str) -> Option<&'static str> {
42 STUB_FILES
43 .iter()
44 .find_map(|&(p, c)| if p == path { Some(c) } else { None })
45}
46
47pub(crate) fn stub_path_for_function(name: &str) -> Option<&'static str> {
51 let lower = name.to_ascii_lowercase();
52 STUB_FN_INDEX
53 .binary_search_by(|(k, _)| (*k).cmp(lower.as_str()))
54 .ok()
55 .map(|i| STUB_FN_INDEX[i].1)
56}
57
58pub fn stub_path_for_class(fqcn: &str) -> Option<&'static str> {
67 let trimmed = fqcn.strip_prefix('\\').unwrap_or(fqcn);
68 let lower = trimmed.to_ascii_lowercase();
69 STUB_CLASS_INDEX
70 .binary_search_by(|(k, _)| (*k).cmp(lower.as_str()))
71 .ok()
72 .map(|i| STUB_CLASS_INDEX[i].1)
73}
74
75pub(crate) fn stub_path_for_constant(name: &str) -> Option<&'static str> {
78 let trimmed = name.strip_prefix('\\').unwrap_or(name);
79 STUB_CONST_INDEX
80 .binary_search_by(|(k, _)| (*k).cmp(trimmed))
81 .ok()
82 .map(|i| STUB_CONST_INDEX[i].1)
83}
84
85pub(crate) fn collect_referenced_builtin_paths(source: &str) -> Vec<&'static str> {
95 use php_lexer::lex_all;
96
97 let mut tokens: HashSet<&str> = HashSet::default();
98 let (lexed, _errors) = lex_all(source);
99
100 let mut i = 0;
101 while i < lexed.len() {
102 let token = &lexed[i];
103 if token.kind == TokenKind::Identifier {
104 let start = token.span.start as usize;
105 let end = token.span.end as usize;
106 if let Some(mut text) = source.get(start..end) {
107 let mut j = i + 1;
109 while j + 1 < lexed.len()
110 && lexed[j].kind == TokenKind::Backslash
111 && lexed[j + 1].kind == TokenKind::Identifier
112 {
113 j += 2;
114 if let Some(part) = source.get(start..(lexed[j - 1].span.end as usize)) {
115 text = part;
116 }
117 }
118 tokens.insert(text);
119 i = j;
120 } else {
121 i += 1;
122 }
123 } else {
124 i += 1;
125 }
126 }
127
128 let mut paths: HashSet<&'static str> = HashSet::default();
129 for token in tokens {
130 if let Some(p) = stub_path_for_function(token) {
131 paths.insert(p);
132 }
133 if let Some(p) = stub_path_for_class(token) {
134 paths.insert(p);
135 }
136 if let Some(p) = stub_path_for_constant(token) {
137 paths.insert(p);
138 }
139 }
140 paths.into_iter().collect()
141}
142
143pub(crate) fn collect_referenced_builtin_paths_from_ast(
152 program: &php_ast::owned::Program,
153) -> Vec<&'static str> {
154 let mut visitor = BuiltinRefVisitor {
155 paths: HashSet::default(),
156 };
157 let _ = walk_owned_program(&mut visitor, program);
158 visitor.paths.into_iter().collect()
159}
160
161struct BuiltinRefVisitor {
163 paths: HashSet<&'static str>,
164}
165
166impl OwnedVisitor for BuiltinRefVisitor {
167 fn visit_expr(&mut self, expr: &php_ast::owned::Expr) -> ControlFlow<()> {
168 match &expr.kind {
169 ExprKind::FunctionCall(call) => {
170 if let ExprKind::Identifier(name) = &call.name.kind {
171 if let Some(p) = stub_path_for_function(name.as_ref()) {
172 self.paths.insert(p);
173 }
174 }
175 }
176 ExprKind::New(new_expr) => {
177 if let ExprKind::Identifier(name) = &new_expr.class.kind {
178 if let Some(p) = stub_path_for_class(name.as_ref()) {
179 self.paths.insert(p);
180 }
181 }
182 }
183 ExprKind::StaticMethodCall(call) => {
184 if let ExprKind::Identifier(name) = &call.class.kind {
185 if let Some(p) = stub_path_for_class(name.as_ref()) {
186 self.paths.insert(p);
187 }
188 }
189 }
190 ExprKind::ClassConstAccess(access) => {
191 if let ExprKind::Identifier(name) = &access.class.kind {
192 if let Some(p) = stub_path_for_class(name.as_ref()) {
193 self.paths.insert(p);
194 }
195 }
196 }
197 ExprKind::Identifier(name) => {
198 if let Some(p) = stub_path_for_constant(name.as_ref()) {
199 self.paths.insert(p);
200 }
201 }
202 _ => {}
203 }
204 walk_owned_expr(self, expr)
205 }
206}
207
208pub fn stub_files() -> &'static [(&'static str, &'static str)] {
216 STUB_FILES
217}
218
219#[allow(dead_code)]
227pub(crate) fn load_stubs(db: &mut MirDbStorage) {
228 load_stubs_for_version(db, PhpVersion::LATEST);
229}
230
231pub(crate) fn load_stubs_for_version(db: &mut MirDbStorage, php_version: PhpVersion) {
236 db.set_php_version(Arc::from(php_version.to_string().as_str()));
239 for (filename, content) in STUB_FILES {
243 let arc_path: Arc<str> = Arc::from(*filename);
244 let arc_content: Arc<str> = Arc::from(*content);
245 db.upsert_source_file(arc_path, arc_content);
246 }
247 let resolver: Arc<dyn crate::ClassResolver> = Arc::new(crate::StubClassResolver);
248 db.set_resolver(Some(resolver));
249}
250
251pub(crate) fn builtin_stub_slices_for_version(php_version: PhpVersion) -> Vec<StubSlice> {
252 STUB_FILES
253 .par_iter()
254 .map(|(filename, content)| stub_slice_from_source(filename, content, Some(php_version)))
255 .collect()
256}
257
258pub(crate) fn stub_slice_from_source(
259 filename: &str,
260 content: &str,
261 php_version: Option<PhpVersion>,
262) -> StubSlice {
263 let result = php_rs_parser::parse(content);
264 let file: Arc<str> = Arc::from(filename);
265 let collector =
266 crate::collector::DefinitionCollector::new_for_slice(file, content, &result.source_map);
267 let collector = match php_version {
268 Some(version) => collector.with_php_version(version),
269 None => collector,
270 };
271 let (mut slice, _) = collector.collect_slice(&result.program);
272 mir_codebase::definitions::deduplicate_params_in_slice(&mut slice);
273 slice
274}
275
276pub(crate) fn collect_stub_dir_paths(dir: &Path, paths: &mut Vec<PathBuf>) {
277 let entries = match std::fs::read_dir(dir) {
278 Ok(e) => e,
279 Err(e) => {
280 eprintln!("mir: cannot read stub directory {}: {}", dir.display(), e);
281 return;
282 }
283 };
284 let mut dir_entries: Vec<PathBuf> = entries.filter_map(|e| e.ok().map(|e| e.path())).collect();
285 dir_entries.sort_unstable();
286 for path in dir_entries {
287 if path.is_dir() {
288 collect_stub_dir_paths(&path, paths);
289 } else if path.extension().is_some_and(|e| e == "php") {
290 paths.push(path);
291 }
292 }
293}
294
295pub(crate) fn user_stub_fingerprint(files: &[PathBuf], dirs: &[PathBuf]) -> u64 {
301 if files.is_empty() && dirs.is_empty() {
302 return 0;
303 }
304 let mut all_paths: Vec<PathBuf> = files.to_vec();
305 for dir in dirs {
306 collect_stub_dir_paths(dir, &mut all_paths);
307 }
308 all_paths.sort_unstable();
310 let mut hasher = blake3::Hasher::new();
311 for path in &all_paths {
312 hasher.update(path.to_string_lossy().as_bytes());
313 hasher.update(&[0]);
314 if let Ok(src) = std::fs::read(path) {
317 hasher.update(&src);
318 }
319 hasher.update(&[0]);
320 }
321 let bytes = hasher.finalize();
322 u64::from_le_bytes(bytes.as_bytes()[..8].try_into().unwrap())
323}
324
325pub struct StubVfs {
346 files: HashMap<&'static str, &'static str>,
347}
348
349impl StubVfs {
350 pub fn new() -> Self {
352 let files = STUB_FILES.iter().map(|&(p, c)| (p, c)).collect();
353 Self { files }
354 }
355
356 pub fn get(&self, path: &str) -> Option<&'static str> {
358 self.files.get(path).copied()
359 }
360
361 pub fn is_stub_file(&self, path: &str) -> bool {
363 self.files.contains_key(path)
364 }
365}
366
367impl Default for StubVfs {
368 fn default() -> Self {
369 Self::new()
370 }
371}
372
373pub struct StubClassResolver;
388
389impl crate::ClassResolver for StubClassResolver {
390 fn resolve(&self, fqcn: &str) -> Option<std::path::PathBuf> {
391 stub_path_for_class(fqcn)
395 .or_else(|| stub_path_for_function(fqcn))
396 .or_else(|| stub_path_for_constant(fqcn))
397 .map(std::path::PathBuf::from)
398 }
399}
400
401pub struct ChainedClassResolver {
410 primary: Arc<dyn crate::ClassResolver>,
411 fallback: Arc<dyn crate::ClassResolver>,
412}
413
414impl ChainedClassResolver {
415 pub fn new(
416 primary: Arc<dyn crate::ClassResolver>,
417 fallback: Arc<dyn crate::ClassResolver>,
418 ) -> Self {
419 Self { primary, fallback }
420 }
421}
422
423impl crate::ClassResolver for ChainedClassResolver {
424 fn resolve(&self, fqcn: &str) -> Option<std::path::PathBuf> {
425 self.primary
426 .resolve(fqcn)
427 .or_else(|| self.fallback.resolve(fqcn))
428 }
429}
430
431pub fn is_builtin_function(name: &str) -> bool {
449 if !BUILTIN_FN_NAMES.is_empty() {
450 return BUILTIN_FN_NAMES.binary_search(&name).is_ok();
451 }
452 static FALLBACK: LazyLock<HashSet<Arc<str>>> = LazyLock::new(|| {
453 builtin_stub_slices_for_version(PhpVersion::LATEST)
454 .into_iter()
455 .flat_map(|slice| slice.functions.into_iter().map(|func| func.fqn.clone()))
456 .collect()
457 });
458 FALLBACK.contains(name)
459}
460
461pub fn is_builtin_constant(name: &str) -> bool {
479 stub_path_for_constant(name).is_some()
480}
481
482#[cfg(test)]
487mod tests {
488 use super::*;
489 use crate::db::{class_exists, constant_exists, function_exists, MirDatabase, MirDbStorage};
490
491 fn stubs_codebase() -> MirDbStorage {
492 let mut db = MirDbStorage::default();
493 load_stubs(&mut db);
494 db
495 }
496
497 fn stubs_codebase_for(version: PhpVersion) -> MirDbStorage {
498 let mut db = MirDbStorage::default();
499 load_stubs_for_version(&mut db, version);
500 db
501 }
502
503 fn stub_function_for(
504 version: PhpVersion,
505 name: &str,
506 ) -> Option<std::sync::Arc<mir_codebase::FunctionDef>> {
507 builtin_stub_slices_for_version(version)
508 .into_iter()
509 .flat_map(|slice| slice.functions.into_iter())
510 .find(|func| func.fqn.as_ref() == name)
511 }
512
513 fn stub_class_for(
514 version: PhpVersion,
515 name: &str,
516 ) -> Option<std::sync::Arc<mir_codebase::ClassDef>> {
517 builtin_stub_slices_for_version(version)
518 .into_iter()
519 .flat_map(|slice| slice.classes.into_iter())
520 .find(|cls| cls.fqcn.as_ref() == name)
521 }
522
523 #[test]
524 fn since_filter_applies_to_methods() {
525 let cls = stub_class_for(PhpVersion::new(7, 4), "DateTimeImmutable")
528 .expect("DateTimeImmutable must exist");
529 assert!(
530 !cls.own_methods.contains_key("createfrominterface"),
531 "createFromInterface should be absent on PHP 7.4"
532 );
533
534 let cls_new = stub_class_for(PhpVersion::new(8, 0), "DateTimeImmutable")
535 .expect("DateTimeImmutable must exist");
536 assert!(
537 cls_new.own_methods.contains_key("createfrominterface"),
538 "createFromInterface should be present on PHP 8.0"
539 );
540 }
541
542 #[test]
543 fn since_tag_excludes_function_below_target() {
544 let cb = stubs_codebase_for(PhpVersion::new(7, 4));
545 assert!(
546 !function_exists(&cb, "str_contains"),
547 "str_contains (@since 8.0) must be absent on PHP 7.4"
548 );
549 assert!(
550 !function_exists(&cb, "str_starts_with"),
551 "str_starts_with (@since 8.0) must be absent on PHP 7.4"
552 );
553 assert!(
554 !function_exists(&cb, "array_is_list"),
555 "array_is_list (@since 8.1) must be absent on PHP 7.4"
556 );
557
558 let cb80 = stubs_codebase_for(PhpVersion::new(8, 0));
559 assert!(
560 function_exists(&cb80, "str_contains"),
561 "str_contains must be present on PHP 8.0"
562 );
563 assert!(
564 !function_exists(&cb80, "array_is_list"),
565 "array_is_list (@since 8.1) must be absent on PHP 8.0"
566 );
567
568 let cb81 = stubs_codebase_for(PhpVersion::new(8, 1));
569 assert!(
570 function_exists(&cb81, "array_is_list"),
571 "array_is_list must be present on PHP 8.1"
572 );
573 }
574
575 #[test]
576 fn removed_tag_excludes_function_at_or_after_target() {
577 let cb74 = stubs_codebase_for(PhpVersion::new(7, 4));
579 assert!(
580 function_exists(&cb74, "hebrevc"),
581 "hebrevc must be present on PHP 7.4"
582 );
583
584 let cb80 = stubs_codebase_for(PhpVersion::new(8, 0));
585 assert!(
586 !function_exists(&cb80, "hebrevc"),
587 "hebrevc (@removed 8.0) must be absent on PHP 8.0"
588 );
589 }
590
591 fn assert_fn(cb: &MirDbStorage, name: &str) {
592 assert!(
593 function_exists(cb, name),
594 "expected stub for `{name}` to be registered"
595 );
596 }
597
598 #[test]
599 fn sscanf_vars_param_is_byref_and_variadic() {
600 let func = stub_function_for(PhpVersion::LATEST, "sscanf").expect("sscanf must be defined");
601 let vars = func.params.get(2).expect("sscanf must have a 3rd param");
602 assert!(vars.is_byref, "sscanf vars param must be by-ref");
603 assert!(vars.is_variadic, "sscanf vars param must be variadic");
604 }
605
606 #[test]
607 fn sscanf_output_vars_not_undefined() {
608 use crate::batch::BatchOptions;
609 use crate::session::AnalysisSession;
610 use crate::PhpVersion;
611 use mir_issues::IssueKind;
612
613 let src = "<?php\nfunction test($str) {\n sscanf($str, \"%d %d\", $row, $col);\n return $row + $col;\n}\n";
614 let tmp = std::env::temp_dir().join("mir_test_sscanf_undefined.php");
615 std::fs::write(&tmp, src).unwrap();
616 let session = AnalysisSession::new(PhpVersion::LATEST);
617 let result = session.analyze_paths(std::slice::from_ref(&tmp), &BatchOptions::new());
618 std::fs::remove_file(tmp).ok();
619 let undef: Vec<_> = result.issues.iter()
620 .filter(|i| matches!(&i.kind, IssueKind::UndefinedVariable { name } if name == "row" || name == "col"))
621 .collect();
622 assert!(
623 undef.is_empty(),
624 "sscanf output vars must not be reported as UndefinedVariable; got: {undef:?}"
625 );
626 }
627
628 #[test]
629 fn stream_functions_are_defined() {
630 let cb = stubs_codebase();
631 assert_fn(&cb, "stream_isatty");
632 assert_fn(&cb, "stream_select");
633 assert_fn(&cb, "stream_get_meta_data");
634 assert_fn(&cb, "stream_set_blocking");
635 assert_fn(&cb, "stream_copy_to_stream");
636 }
637
638 #[test]
639 fn preg_grep_is_defined() {
640 let cb = stubs_codebase();
641 assert_fn(&cb, "preg_grep");
642 }
643
644 #[test]
645 fn standard_missing_functions_are_defined() {
646 let cb = stubs_codebase();
647 assert_fn(&cb, "get_resource_type");
648 assert_fn(&cb, "ftruncate");
649 assert_fn(&cb, "umask");
650 assert_fn(&cb, "date_default_timezone_set");
651 assert_fn(&cb, "date_default_timezone_get");
652 }
653
654 #[test]
655 fn mb_missing_functions_are_defined() {
656 let cb = stubs_codebase();
657 assert_fn(&cb, "mb_strwidth");
658 assert_fn(&cb, "mb_convert_variables");
659 }
660
661 #[test]
662 fn pcntl_functions_are_defined() {
663 let cb = stubs_codebase();
664 assert_fn(&cb, "pcntl_signal");
665 assert_fn(&cb, "pcntl_async_signals");
666 assert_fn(&cb, "pcntl_signal_get_handler");
667 assert_fn(&cb, "pcntl_alarm");
668 }
669
670 #[test]
671 fn posix_functions_are_defined() {
672 let cb = stubs_codebase();
673 assert_fn(&cb, "posix_kill");
674 assert_fn(&cb, "posix_getpid");
675 }
676
677 #[test]
678 fn sapi_windows_functions_are_defined() {
679 let cb = stubs_codebase();
680 assert_fn(&cb, "sapi_windows_vt100_support");
681 assert_fn(&cb, "sapi_windows_cp_set");
682 assert_fn(&cb, "sapi_windows_cp_get");
683 assert_fn(&cb, "sapi_windows_cp_conv");
684 }
685
686 #[test]
687 fn cli_functions_are_defined() {
688 let cb = stubs_codebase();
689 assert_fn(&cb, "cli_set_process_title");
690 assert_fn(&cb, "cli_get_process_title");
691 }
692
693 #[test]
694 fn builtin_fn_names_has_sufficient_entries() {
695 if BUILTIN_FN_NAMES.is_empty() {
698 return;
699 }
700 assert!(
701 BUILTIN_FN_NAMES.len() >= 500,
702 "BUILTIN_FN_NAMES has only {} entries — \
703 build.rs may have failed to parse PhpStormStubsMap.php correctly",
704 BUILTIN_FN_NAMES.len()
705 );
706 }
707
708 #[test]
709 fn preg_match_matches_param_is_byref_with_type() {
710 let func = stub_function_for(PhpVersion::LATEST, "preg_match")
711 .expect("preg_match should exist in stubs");
712 let matches_param = func
713 .params
714 .iter()
715 .find(|p| p.name.as_ref() == "matches")
716 .expect("preg_match should have a $matches param");
717 assert!(matches_param.is_byref, "$matches should be byref");
718 assert!(
719 matches_param.ty.is_some(),
720 "$matches should have a type annotation (string[] from PHPDoc)"
721 );
722 }
723
724 #[test]
725 fn is_builtin_function_returns_true_for_known_builtins() {
726 assert!(is_builtin_function("strlen"), "strlen should be a builtin");
727 assert!(
728 is_builtin_function("array_map"),
729 "array_map should be a builtin"
730 );
731 assert!(
732 is_builtin_function("json_encode"),
733 "json_encode should be a builtin"
734 );
735 assert!(
736 is_builtin_function("preg_match"),
737 "preg_match should be a builtin"
738 );
739 }
740
741 #[test]
742 fn is_builtin_function_covers_stdlib_functions() {
743 assert!(is_builtin_function("bcadd"), "bcadd should be a builtin");
744 assert!(
745 is_builtin_function("sodium_crypto_secretbox"),
746 "sodium_crypto_secretbox should be a builtin"
747 );
748 }
749
750 #[test]
751 fn is_builtin_function_returns_false_for_unknown_names() {
752 assert!(
753 !is_builtin_function("my_custom_function"),
754 "my_custom_function should not be a builtin"
755 );
756 assert!(
757 !is_builtin_function(""),
758 "empty string should not be a builtin"
759 );
760 assert!(
761 !is_builtin_function("gearman_bugreport"),
762 "extension function with no vendored stub dir should not be a builtin"
763 );
764 }
765
766 #[test]
767 fn is_builtin_constant_returns_true_for_known_constants() {
768 assert!(
769 is_builtin_constant("PHP_EOL"),
770 "PHP_EOL should be a builtin"
771 );
772 assert!(
773 is_builtin_constant("PHP_VERSION"),
774 "PHP_VERSION should be a builtin"
775 );
776 }
777
778 #[test]
779 fn is_builtin_constant_is_case_sensitive() {
780 assert!(
781 !is_builtin_constant("php_eol"),
782 "PHP constant lookup is exact-case, unlike class names"
783 );
784 }
785
786 #[test]
787 fn is_builtin_constant_strips_leading_backslash() {
788 assert!(
789 is_builtin_constant("\\PHP_EOL"),
790 "a global-namespace-escaped constant should still resolve"
791 );
792 }
793
794 #[test]
795 fn is_builtin_constant_returns_false_for_unknown_names() {
796 assert!(
797 !is_builtin_constant("MY_CUSTOM_CONST"),
798 "MY_CUSTOM_CONST should not be a builtin"
799 );
800 assert!(
801 !is_builtin_constant(""),
802 "empty string should not be a builtin"
803 );
804 }
805
806 fn assert_cls(cb: &MirDbStorage, name: &str) {
809 assert!(
810 class_exists(cb, name),
811 "expected stub class `{name}` to be registered"
812 );
813 }
814
815 fn assert_iface(cb: &MirDbStorage, name: &str) {
816 assert!(
817 class_exists(cb, name),
818 "expected stub interface `{name}` to be registered"
819 );
820 }
821
822 fn assert_const(cb: &MirDbStorage, name: &str) {
823 assert!(
824 constant_exists(cb, name),
825 "expected stub constant `{name}` to be registered"
826 );
827 }
828
829 #[test]
830 fn stubs_coverage_counts() {
831 let mut fn_count = 0usize;
832 let mut type_count = 0usize;
833 let mut const_count = 0usize;
834 for slice in builtin_stub_slices_for_version(PhpVersion::LATEST) {
835 fn_count += slice.functions.len();
836 type_count += slice.classes.len()
837 + slice.interfaces.len()
838 + slice.traits.len()
839 + slice.enums.len();
840 const_count += slice.constants.len();
841 }
842 assert!(fn_count > 500, "expected >500 functions, got {fn_count}");
843 assert!(type_count > 120, "expected >120 types, got {type_count}");
844 assert!(
845 const_count > 200,
846 "expected >200 constants, got {const_count}"
847 );
848 }
849
850 #[test]
851 fn curl_multi_exec_still_running_is_byref() {
852 let func = stub_function_for(PhpVersion::LATEST, "curl_multi_exec")
853 .expect("curl_multi_exec must be defined");
854 let still_running = func
855 .params
856 .iter()
857 .find(|p| p.name.as_ref() == "still_running")
858 .expect("curl_multi_exec must have a still_running param");
859 assert!(
860 still_running.is_byref,
861 "curl_multi_exec $still_running must be by-ref (generated from PHP stub)"
862 );
863 }
864
865 #[test]
868 fn stub_files_are_non_empty() {
869 assert!(
872 !STUB_FILES.is_empty(),
873 "STUB_FILES must not be empty — check build.rs find_workspace_root()"
874 );
875 }
876
877 #[test]
878 fn stub_vfs_resolves_all_paths() {
879 let vfs = StubVfs::new();
880 for &(path, expected_content) in STUB_FILES {
881 let got = vfs
882 .get(path)
883 .unwrap_or_else(|| panic!("StubVfs::get({path:?}) returned None"));
884 assert_eq!(got, expected_content, "StubVfs content mismatch for {path}");
885 assert!(
886 vfs.is_stub_file(path),
887 "StubVfs::is_stub_file({path:?}) returned false"
888 );
889 }
890 }
891
892 #[test]
893 fn stub_vfs_rejects_user_file_paths() {
894 let vfs = StubVfs::new();
895 assert!(!vfs.is_stub_file("/tmp/user_code.php"));
896 assert!(!vfs.is_stub_file("src/MyClass.php"));
897 assert!(!vfs.is_stub_file(""));
898 }
899
900 #[test]
901 fn symbol_to_file_paths_are_resolvable_via_stub_vfs() {
902 let mut db = MirDbStorage::default();
903 db.init_workspace_revision();
904 load_stubs(&mut db);
905 let vfs = StubVfs::new();
906
907 let functions = crate::db::workspace_functions(&db);
908 for symbol in functions.iter() {
909 let Some(path) = db.symbol_defining_file(symbol.as_str()) else {
910 continue;
911 };
912 assert!(
913 vfs.get(path.as_ref()).is_some(),
914 "symbol '{}' points to '{}' which StubVfs cannot resolve — \
915 go-to-definition would silently break for this symbol",
916 symbol.as_str(),
917 path
918 );
919 }
920 }
921
922 #[test]
923 fn function_lookup_is_case_insensitive() {
924 let cb = stubs_codebase();
929 assert!(function_exists(&cb, "strlen"));
930 assert!(function_exists(&cb, "STRLEN"));
931 assert!(function_exists(&cb, "StrLen"));
932 assert!(function_exists(&cb, "Restore_Error_Handler"));
933 assert!(function_exists(&cb, "RESTORE_ERROR_HANDLER"));
934 }
935
936 #[test]
937 fn class_lookup_is_case_insensitive() {
938 let cb = stubs_codebase();
942 assert!(class_exists(&cb, "ArrayObject"));
943 assert!(class_exists(&cb, "arrayobject"));
944 assert!(class_exists(&cb, "ARRAYOBJECT"));
945 assert!(class_exists(&cb, "ArrayOBJECT"));
946 }
947
948 #[test]
949 fn constant_lookup_stays_case_sensitive() {
950 let cb = stubs_codebase();
954 assert!(constant_exists(&cb, "PHP_INT_MAX"));
955 assert!(!constant_exists(&cb, "php_int_max"));
956 assert!(!constant_exists(&cb, "Php_Int_Max"));
957 }
958
959 #[test]
960 fn stdlib_symbols_are_loaded() {
961 let cb = stubs_codebase();
962
963 assert_fn(&cb, "bcadd");
964 assert_fn(&cb, "bcsub");
965 assert_fn(&cb, "bcmul");
966 assert_fn(&cb, "bcdiv");
967 assert_fn(&cb, "sodium_crypto_secretbox");
968 assert_fn(&cb, "sodium_randombytes_buf");
969
970 assert_cls(&cb, "SplObjectStorage");
971 assert_cls(&cb, "SplHeap");
972 assert_cls(&cb, "IteratorIterator");
973 assert_cls(&cb, "FilterIterator");
974 assert_cls(&cb, "LimitIterator");
975 assert_cls(&cb, "CallbackFilterIterator");
976 assert_cls(&cb, "RegexIterator");
977 assert_cls(&cb, "AppendIterator");
978 assert_cls(&cb, "GlobIterator");
979 assert_cls(&cb, "ReflectionObject");
980 assert_cls(&cb, "Attribute");
981
982 assert_iface(&cb, "SeekableIterator");
983 assert_iface(&cb, "SplObserver");
984 assert_iface(&cb, "SplSubject");
985
986 assert_const(&cb, "PHP_INT_MAX");
987 assert_const(&cb, "PHP_INT_MIN");
988 assert_const(&cb, "PHP_EOL");
989 assert_const(&cb, "SORT_REGULAR");
990 assert_const(&cb, "JSON_THROW_ON_ERROR");
991 assert_const(&cb, "FILTER_VALIDATE_EMAIL");
992 assert_const(&cb, "PREG_OFFSET_CAPTURE");
993 assert_const(&cb, "M_PI");
994 assert_const(&cb, "PASSWORD_DEFAULT");
995 }
996}