Skip to main content

mir_analyzer/
stubs.rs

1/// PHP built-in stubs — registered into the salsa db before user-code analysis.
2///
3/// Stubs are embedded at compile time from the `stubs/{ext}/` workspace directory via
4/// `build.rs`.  Each file gets a stable virtual path (e.g. `"stubs/standard/standard_9.php"`)
5/// so symbols are source-attributed and go-to-definition works for them.
6///
7/// # `StubVfs`
8///
9/// [`StubVfs`] maps every embedded stub file path to its `&'static str` content.
10/// Consumers use it to serve stub file content for go-to-definition on
11/// built-in PHP symbols:
12///
13/// ```ignore
14/// let file = db.symbol_defining_file("strlen"); // → "stubs/standard/standard_0.php"
15/// let src  = stub_vfs.get(&file).unwrap();           // → &'static str PHP source
16/// ```
17use 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
31// Generated by build.rs: `static STUB_FILES: &[(&str, &str)]`
32include!(concat!(env!("OUT_DIR"), "/stub_files.rs"));
33
34// Generated by build.rs: `BUILTIN_FN_NAMES`, `STUB_FN_INDEX`,
35// `STUB_CLASS_INDEX`, `STUB_CONST_INDEX`. See build.rs for details.
36include!(concat!(env!("OUT_DIR"), "/phpstorm_builtin_fns.rs"));
37
38/// Look up the embedded stub file content for a virtual path (e.g.
39/// `"stubs/standard/standard_0.php"`). Returns `None` if the path isn't part
40/// of the embedded set.
41pub(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
47/// Look up the stub virtual path that defines a built-in PHP function.
48/// Lookup is case-insensitive (PHP function names are case-insensitive).
49/// Returns `None` if the function isn't a known built-in.
50pub(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
58/// Look up the stub virtual path that defines a built-in PHP class / interface
59/// / trait / enum. Lookup is case-insensitive. Strips a single leading
60/// backslash if present. Returns `None` if not a known built-in type.
61///
62/// Public so the [`StubClassResolver`] in this crate (used by
63/// `AnalysisSession` to make `find_class_like` aware of PHP built-ins)
64/// can reach it, and so LSP consumers building their own chained
65/// resolvers can compose it explicitly.
66pub 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
75/// Look up the stub virtual path that defines a built-in PHP constant.
76/// PHP constants are case-sensitive, so this lookup is exact.
77pub(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
85/// Scan PHP `source` for identifiers that match known built-in functions /
86/// classes / constants, and return the deduplicated list of stub virtual
87/// paths needed to cover them.
88///
89/// This is the core of the lazy-stub auto-discovery used by
90/// [`crate::AnalysisSession::ensure_stubs_for_source`]. Uses the PHP lexer
91/// to safely extract identifier tokens, avoiding manual byte-level scanning.
92/// False positives (e.g., `imagecreate` appearing inside a string literal)
93/// cost only one extra stub ingest — cheap and idempotent.
94pub(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                // Handle namespaced identifiers: Foo\Bar\Baz
108                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
143/// Walk the parsed AST to find identifiers that match known built-in functions /
144/// classes / constants, and return the deduplicated list of stub virtual paths.
145///
146/// Unlike [`collect_referenced_builtin_paths`], this walks the real AST instead
147/// of doing a byte-level heuristic scan. This eliminates false positives from
148/// function names appearing inside string literals or comments. Used by
149/// [`crate::AnalysisSession::ensure_stubs_for_ast`] for single-file analysis
150/// where the AST is already available.
151pub(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
161/// Visitor for extracting function/class/constant references from the AST.
162struct 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
208// ---------------------------------------------------------------------------
209// Public accessors for embedded stub data
210// ---------------------------------------------------------------------------
211
212/// Every PHP stub file from `stubs/{ext}/` embedded at compile time as `(path, content)`.
213///
214/// Path is workspace-relative (e.g. `"stubs/standard/standard_9.php"`).
215pub fn stub_files() -> &'static [(&'static str, &'static str)] {
216    STUB_FILES
217}
218
219// ---------------------------------------------------------------------------
220// Public entry point
221// ---------------------------------------------------------------------------
222
223/// Default-version entry point retained for callers (CLI, benches, tests) that
224/// don't track a target PHP version. Equivalent to
225/// [`load_stubs_for_version`] with `PhpVersion::LATEST`.
226#[allow(dead_code)]
227pub(crate) fn load_stubs(db: &mut MirDbStorage) {
228    load_stubs_for_version(db, PhpVersion::LATEST);
229}
230
231/// Load stubs filtered for `php_version`. Symbols whose `@since` post-dates
232/// the target, or whose `@removed` is at or before the target, are skipped —
233/// so multiple declarations of the same name (e.g. `each` on PHP 7 vs.
234/// PHP 8) gated by `@since`/`@removed` collapse to the one matching variant.
235pub(crate) fn load_stubs_for_version(db: &mut MirDbStorage, php_version: PhpVersion) {
236    // Wire the target version before registering any SourceFile inputs so
237    // collect_file_definitions reads the right version for @since/@removed filtering.
238    db.set_php_version(Arc::from(php_version.to_string().as_str()));
239    // Register each stub file's text as a salsa `SourceFile` input.
240    // `find_class_like` / `find_function` resolve built-in PHP symbols by
241    // routing through the `StubClassResolver` we install below.
242    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
295/// Fingerprint the user-configured stub set (paths + contents) for the result
296/// cache epoch. User stubs are resolvable just like bundled ones, so editing,
297/// adding, or removing them changes analysis output for files that reference
298/// those symbols — and the per-file content hash can't see it. Returns 0 when
299/// no user stubs are configured (the common case), so the epoch is unaffected.
300pub(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    // Sort for a path-order-independent fingerprint.
309    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        // Content too, so an in-place edit of a stub flips the fingerprint.
315        // A read failure still contributes the path, so add/remove is caught.
316        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
325// ---------------------------------------------------------------------------
326// StubVfs — virtual file system for stub content
327// ---------------------------------------------------------------------------
328
329/// A read-only map from stub file path to its embedded PHP source content.
330///
331/// Consumers use this to serve stub source for go-to-definition on built-in
332/// PHP symbols.
333///
334/// # Example
335///
336/// ```ignore
337/// let vfs = StubVfs::new();
338/// // After analysis:
339/// if let Some(path) = session.symbol_defining_file("strlen") {
340///     if let Some(src) = vfs.get(path.as_ref()) {
341///         // serve `src` as a read-only virtual document
342///     }
343/// }
344/// ```
345pub struct StubVfs {
346    files: HashMap<&'static str, &'static str>,
347}
348
349impl StubVfs {
350    /// Build the VFS from the embedded stub set.
351    pub fn new() -> Self {
352        let files = STUB_FILES.iter().map(|&(p, c)| (p, c)).collect();
353        Self { files }
354    }
355
356    /// Return the PHP source for `path`, or `None` if it is not a stub file.
357    pub fn get(&self, path: &str) -> Option<&'static str> {
358        self.files.get(path).copied()
359    }
360
361    /// Return `true` if `path` is a known stub file path.
362    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
373// ---------------------------------------------------------------------------
374// StubClassResolver — ClassResolver for bundled PHP built-in stubs
375// ---------------------------------------------------------------------------
376
377/// [`crate::ClassResolver`] that maps PHP built-in class FQCNs
378/// (`ArrayObject`, `Exception`, `ReflectionClass`, …) to the stub virtual
379/// path that defines them. Used by [`crate::ChainedClassResolver`] to
380/// make `find_class_like` aware of PHP built-ins in addition to the
381/// user's PSR-4 / classmap.
382///
383/// The returned paths are the same virtual paths used by [`StubVfs`] and
384/// matched against `MirDbStorage`'s registered `SourceFile`s when stubs are
385/// loaded (see `load_stubs_for_version`, which calls `upsert_source_file`
386/// for each stub).
387pub struct StubClassResolver;
388
389impl crate::ClassResolver for StubClassResolver {
390    fn resolve(&self, fqcn: &str) -> Option<std::path::PathBuf> {
391        // Try classes first; then functions / constants — built-in FQNs
392        // share a single resolver since they all map to the bundled stub
393        // VFS paths registered as SourceFile inputs.
394        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
401/// [`crate::ClassResolver`] composing a primary resolver (user's PSR-4 /
402/// classmap) with a fallback (typically [`StubClassResolver`]). The
403/// primary is consulted first; if it misses, the fallback is tried.
404///
405/// `AnalysisSession::with_psr4` and `with_class_resolver` automatically
406/// wrap the user-supplied resolver in this chain so PHP built-ins are
407/// resolvable through `resolve_fqcn_to_path` (and therefore
408/// `find_class_like`) without per-consumer setup.
409pub 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
431// ---------------------------------------------------------------------------
432// Builtin-function query
433// ---------------------------------------------------------------------------
434
435/// Returns `true` if `name` is a known PHP built-in function.
436///
437/// Fast path: binary search on `BUILTIN_FN_NAMES`, a sorted compile-time slice
438/// generated from `PhpStormStubsMap.php` by `build.rs`.
439///
440/// Fallback (when `BUILTIN_FN_NAMES` is empty): reads the embedded stub slices and checks
441/// the embedded stubs and checks membership there.
442///
443/// # Example
444/// ```
445/// assert!(mir_analyzer::stubs::is_builtin_function("strlen"));
446/// assert!(!mir_analyzer::stubs::is_builtin_function("my_custom_function"));
447/// ```
448pub 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
461// ---------------------------------------------------------------------------
462// Tests
463// ---------------------------------------------------------------------------
464
465#[cfg(test)]
466mod tests {
467    use super::*;
468    use crate::db::{class_exists, constant_exists, function_exists, MirDatabase, MirDbStorage};
469
470    fn stubs_codebase() -> MirDbStorage {
471        let mut db = MirDbStorage::default();
472        load_stubs(&mut db);
473        db
474    }
475
476    fn stubs_codebase_for(version: PhpVersion) -> MirDbStorage {
477        let mut db = MirDbStorage::default();
478        load_stubs_for_version(&mut db, version);
479        db
480    }
481
482    fn stub_function_for(
483        version: PhpVersion,
484        name: &str,
485    ) -> Option<std::sync::Arc<mir_codebase::FunctionDef>> {
486        builtin_stub_slices_for_version(version)
487            .into_iter()
488            .flat_map(|slice| slice.functions.into_iter())
489            .find(|func| func.fqn.as_ref() == name)
490    }
491
492    fn stub_class_for(
493        version: PhpVersion,
494        name: &str,
495    ) -> Option<std::sync::Arc<mir_codebase::ClassDef>> {
496        builtin_stub_slices_for_version(version)
497            .into_iter()
498            .flat_map(|slice| slice.classes.into_iter())
499            .find(|cls| cls.fqcn.as_ref() == name)
500    }
501
502    #[test]
503    fn since_filter_applies_to_methods() {
504        // Direct stub-slice probe — independent of which path is consulted
505        // for symbol lookup.
506        let cls = stub_class_for(PhpVersion::new(7, 4), "DateTimeImmutable")
507            .expect("DateTimeImmutable must exist");
508        assert!(
509            !cls.own_methods.contains_key("createfrominterface"),
510            "createFromInterface should be absent on PHP 7.4"
511        );
512
513        let cls_new = stub_class_for(PhpVersion::new(8, 0), "DateTimeImmutable")
514            .expect("DateTimeImmutable must exist");
515        assert!(
516            cls_new.own_methods.contains_key("createfrominterface"),
517            "createFromInterface should be present on PHP 8.0"
518        );
519    }
520
521    #[test]
522    fn since_tag_excludes_function_below_target() {
523        let cb = stubs_codebase_for(PhpVersion::new(7, 4));
524        assert!(
525            !function_exists(&cb, "str_contains"),
526            "str_contains (@since 8.0) must be absent on PHP 7.4"
527        );
528        assert!(
529            !function_exists(&cb, "str_starts_with"),
530            "str_starts_with (@since 8.0) must be absent on PHP 7.4"
531        );
532        assert!(
533            !function_exists(&cb, "array_is_list"),
534            "array_is_list (@since 8.1) must be absent on PHP 7.4"
535        );
536
537        let cb80 = stubs_codebase_for(PhpVersion::new(8, 0));
538        assert!(
539            function_exists(&cb80, "str_contains"),
540            "str_contains must be present on PHP 8.0"
541        );
542        assert!(
543            !function_exists(&cb80, "array_is_list"),
544            "array_is_list (@since 8.1) must be absent on PHP 8.0"
545        );
546
547        let cb81 = stubs_codebase_for(PhpVersion::new(8, 1));
548        assert!(
549            function_exists(&cb81, "array_is_list"),
550            "array_is_list must be present on PHP 8.1"
551        );
552    }
553
554    #[test]
555    fn removed_tag_excludes_function_at_or_after_target() {
556        // hebrevc() was removed in PHP 8.0 (@removed 8.0).
557        let cb74 = stubs_codebase_for(PhpVersion::new(7, 4));
558        assert!(
559            function_exists(&cb74, "hebrevc"),
560            "hebrevc must be present on PHP 7.4"
561        );
562
563        let cb80 = stubs_codebase_for(PhpVersion::new(8, 0));
564        assert!(
565            !function_exists(&cb80, "hebrevc"),
566            "hebrevc (@removed 8.0) must be absent on PHP 8.0"
567        );
568    }
569
570    fn assert_fn(cb: &MirDbStorage, name: &str) {
571        assert!(
572            function_exists(cb, name),
573            "expected stub for `{name}` to be registered"
574        );
575    }
576
577    #[test]
578    fn sscanf_vars_param_is_byref_and_variadic() {
579        let func = stub_function_for(PhpVersion::LATEST, "sscanf").expect("sscanf must be defined");
580        let vars = func.params.get(2).expect("sscanf must have a 3rd param");
581        assert!(vars.is_byref, "sscanf vars param must be by-ref");
582        assert!(vars.is_variadic, "sscanf vars param must be variadic");
583    }
584
585    #[test]
586    fn sscanf_output_vars_not_undefined() {
587        use crate::batch::BatchOptions;
588        use crate::session::AnalysisSession;
589        use crate::PhpVersion;
590        use mir_issues::IssueKind;
591
592        let src = "<?php\nfunction test($str) {\n    sscanf($str, \"%d %d\", $row, $col);\n    return $row + $col;\n}\n";
593        let tmp = std::env::temp_dir().join("mir_test_sscanf_undefined.php");
594        std::fs::write(&tmp, src).unwrap();
595        let session = AnalysisSession::new(PhpVersion::LATEST);
596        let result = session.analyze_paths(std::slice::from_ref(&tmp), &BatchOptions::new());
597        std::fs::remove_file(tmp).ok();
598        let undef: Vec<_> = result.issues.iter()
599            .filter(|i| matches!(&i.kind, IssueKind::UndefinedVariable { name } if name == "row" || name == "col"))
600            .collect();
601        assert!(
602            undef.is_empty(),
603            "sscanf output vars must not be reported as UndefinedVariable; got: {undef:?}"
604        );
605    }
606
607    #[test]
608    fn stream_functions_are_defined() {
609        let cb = stubs_codebase();
610        assert_fn(&cb, "stream_isatty");
611        assert_fn(&cb, "stream_select");
612        assert_fn(&cb, "stream_get_meta_data");
613        assert_fn(&cb, "stream_set_blocking");
614        assert_fn(&cb, "stream_copy_to_stream");
615    }
616
617    #[test]
618    fn preg_grep_is_defined() {
619        let cb = stubs_codebase();
620        assert_fn(&cb, "preg_grep");
621    }
622
623    #[test]
624    fn standard_missing_functions_are_defined() {
625        let cb = stubs_codebase();
626        assert_fn(&cb, "get_resource_type");
627        assert_fn(&cb, "ftruncate");
628        assert_fn(&cb, "umask");
629        assert_fn(&cb, "date_default_timezone_set");
630        assert_fn(&cb, "date_default_timezone_get");
631    }
632
633    #[test]
634    fn mb_missing_functions_are_defined() {
635        let cb = stubs_codebase();
636        assert_fn(&cb, "mb_strwidth");
637        assert_fn(&cb, "mb_convert_variables");
638    }
639
640    #[test]
641    fn pcntl_functions_are_defined() {
642        let cb = stubs_codebase();
643        assert_fn(&cb, "pcntl_signal");
644        assert_fn(&cb, "pcntl_async_signals");
645        assert_fn(&cb, "pcntl_signal_get_handler");
646        assert_fn(&cb, "pcntl_alarm");
647    }
648
649    #[test]
650    fn posix_functions_are_defined() {
651        let cb = stubs_codebase();
652        assert_fn(&cb, "posix_kill");
653        assert_fn(&cb, "posix_getpid");
654    }
655
656    #[test]
657    fn sapi_windows_functions_are_defined() {
658        let cb = stubs_codebase();
659        assert_fn(&cb, "sapi_windows_vt100_support");
660        assert_fn(&cb, "sapi_windows_cp_set");
661        assert_fn(&cb, "sapi_windows_cp_get");
662        assert_fn(&cb, "sapi_windows_cp_conv");
663    }
664
665    #[test]
666    fn cli_functions_are_defined() {
667        let cb = stubs_codebase();
668        assert_fn(&cb, "cli_set_process_title");
669        assert_fn(&cb, "cli_get_process_title");
670    }
671
672    #[test]
673    fn builtin_fn_names_has_sufficient_entries() {
674        // Guards against PhpStormStubsMap.php parsing regressions in build.rs.
675        // When the submodule is absent the slice is empty — skip the check in that case.
676        if BUILTIN_FN_NAMES.is_empty() {
677            return;
678        }
679        assert!(
680            BUILTIN_FN_NAMES.len() >= 500,
681            "BUILTIN_FN_NAMES has only {} entries — \
682             build.rs may have failed to parse PhpStormStubsMap.php correctly",
683            BUILTIN_FN_NAMES.len()
684        );
685    }
686
687    #[test]
688    fn preg_match_matches_param_is_byref_with_type() {
689        let func = stub_function_for(PhpVersion::LATEST, "preg_match")
690            .expect("preg_match should exist in stubs");
691        let matches_param = func
692            .params
693            .iter()
694            .find(|p| p.name.as_ref() == "matches")
695            .expect("preg_match should have a $matches param");
696        assert!(matches_param.is_byref, "$matches should be byref");
697        assert!(
698            matches_param.ty.is_some(),
699            "$matches should have a type annotation (string[] from PHPDoc)"
700        );
701    }
702
703    #[test]
704    fn is_builtin_function_returns_true_for_known_builtins() {
705        assert!(is_builtin_function("strlen"), "strlen should be a builtin");
706        assert!(
707            is_builtin_function("array_map"),
708            "array_map should be a builtin"
709        );
710        assert!(
711            is_builtin_function("json_encode"),
712            "json_encode should be a builtin"
713        );
714        assert!(
715            is_builtin_function("preg_match"),
716            "preg_match should be a builtin"
717        );
718    }
719
720    #[test]
721    fn is_builtin_function_covers_stdlib_functions() {
722        assert!(is_builtin_function("bcadd"), "bcadd should be a builtin");
723        assert!(
724            is_builtin_function("sodium_crypto_secretbox"),
725            "sodium_crypto_secretbox should be a builtin"
726        );
727    }
728
729    #[test]
730    fn is_builtin_function_returns_false_for_unknown_names() {
731        assert!(
732            !is_builtin_function("my_custom_function"),
733            "my_custom_function should not be a builtin"
734        );
735        assert!(
736            !is_builtin_function(""),
737            "empty string should not be a builtin"
738        );
739        assert!(
740            !is_builtin_function("ast\\parse_file"),
741            "extension function should not be a builtin"
742        );
743    }
744
745    // --- stub coverage tests ---
746
747    fn assert_cls(cb: &MirDbStorage, name: &str) {
748        assert!(
749            class_exists(cb, name),
750            "expected stub class `{name}` to be registered"
751        );
752    }
753
754    fn assert_iface(cb: &MirDbStorage, name: &str) {
755        assert!(
756            class_exists(cb, name),
757            "expected stub interface `{name}` to be registered"
758        );
759    }
760
761    fn assert_const(cb: &MirDbStorage, name: &str) {
762        assert!(
763            constant_exists(cb, name),
764            "expected stub constant `{name}` to be registered"
765        );
766    }
767
768    #[test]
769    fn stubs_coverage_counts() {
770        let mut fn_count = 0usize;
771        let mut type_count = 0usize;
772        let mut const_count = 0usize;
773        for slice in builtin_stub_slices_for_version(PhpVersion::LATEST) {
774            fn_count += slice.functions.len();
775            type_count += slice.classes.len()
776                + slice.interfaces.len()
777                + slice.traits.len()
778                + slice.enums.len();
779            const_count += slice.constants.len();
780        }
781        assert!(fn_count > 500, "expected >500 functions, got {fn_count}");
782        assert!(type_count > 120, "expected >120 types, got {type_count}");
783        assert!(
784            const_count > 200,
785            "expected >200 constants, got {const_count}"
786        );
787    }
788
789    #[test]
790    fn curl_multi_exec_still_running_is_byref() {
791        let func = stub_function_for(PhpVersion::LATEST, "curl_multi_exec")
792            .expect("curl_multi_exec must be defined");
793        let still_running = func
794            .params
795            .iter()
796            .find(|p| p.name.as_ref() == "still_running")
797            .expect("curl_multi_exec must have a still_running param");
798        assert!(
799            still_running.is_byref,
800            "curl_multi_exec $still_running must be by-ref (generated from PHP stub)"
801        );
802    }
803
804    // --- Stub loading regression tests ---
805
806    #[test]
807    fn stub_files_are_non_empty() {
808        // Regression: STUB_FILES was silently empty when build.rs used
809        // the crate manifest dir instead of the workspace root to locate stubs/.
810        assert!(
811            !STUB_FILES.is_empty(),
812            "STUB_FILES must not be empty — check build.rs find_workspace_root()"
813        );
814    }
815
816    #[test]
817    fn stub_vfs_resolves_all_paths() {
818        let vfs = StubVfs::new();
819        for &(path, expected_content) in STUB_FILES {
820            let got = vfs
821                .get(path)
822                .unwrap_or_else(|| panic!("StubVfs::get({path:?}) returned None"));
823            assert_eq!(got, expected_content, "StubVfs content mismatch for {path}");
824            assert!(
825                vfs.is_stub_file(path),
826                "StubVfs::is_stub_file({path:?}) returned false"
827            );
828        }
829    }
830
831    #[test]
832    fn stub_vfs_rejects_user_file_paths() {
833        let vfs = StubVfs::new();
834        assert!(!vfs.is_stub_file("/tmp/user_code.php"));
835        assert!(!vfs.is_stub_file("src/MyClass.php"));
836        assert!(!vfs.is_stub_file(""));
837    }
838
839    #[test]
840    fn symbol_to_file_paths_are_resolvable_via_stub_vfs() {
841        let mut db = MirDbStorage::default();
842        db.init_workspace_revision();
843        load_stubs(&mut db);
844        let vfs = StubVfs::new();
845
846        let functions = crate::db::workspace_functions(&db);
847        for symbol in functions.iter() {
848            let Some(path) = db.symbol_defining_file(symbol.as_ref()) else {
849                continue;
850            };
851            assert!(
852                vfs.get(path.as_ref()).is_some(),
853                "symbol '{}' points to '{}' which StubVfs cannot resolve — \
854                 go-to-definition would silently break for this symbol",
855                symbol,
856                path
857            );
858        }
859    }
860
861    #[test]
862    fn function_lookup_is_case_insensitive() {
863        // PHP function names are case-insensitive: `STRLEN($x)` must resolve
864        // to the same node as `strlen($x)`. Regression for users seeing
865        // `UndefinedFunction: Function Restore_Error_Handler() is not defined`
866        // on mixed-case calls of built-ins.
867        let cb = stubs_codebase();
868        assert!(function_exists(&cb, "strlen"));
869        assert!(function_exists(&cb, "STRLEN"));
870        assert!(function_exists(&cb, "StrLen"));
871        assert!(function_exists(&cb, "Restore_Error_Handler"));
872        assert!(function_exists(&cb, "RESTORE_ERROR_HANDLER"));
873    }
874
875    #[test]
876    fn class_lookup_is_case_insensitive() {
877        // PHP class names are case-insensitive: `new arrayobject()` must
878        // resolve to `ArrayObject`. Regression for `UndefinedClass` on
879        // lower- or upper-cased built-in class references.
880        let cb = stubs_codebase();
881        assert!(class_exists(&cb, "ArrayObject"));
882        assert!(class_exists(&cb, "arrayobject"));
883        assert!(class_exists(&cb, "ARRAYOBJECT"));
884        assert!(class_exists(&cb, "ArrayOBJECT"));
885    }
886
887    #[test]
888    fn constant_lookup_stays_case_sensitive() {
889        // PHP global constants ARE case-sensitive (except true/false/null).
890        // Make sure the case-insensitivity fix for functions/classes did not
891        // leak into constants.
892        let cb = stubs_codebase();
893        assert!(constant_exists(&cb, "PHP_INT_MAX"));
894        assert!(!constant_exists(&cb, "php_int_max"));
895        assert!(!constant_exists(&cb, "Php_Int_Max"));
896    }
897
898    #[test]
899    fn stdlib_symbols_are_loaded() {
900        let cb = stubs_codebase();
901
902        assert_fn(&cb, "bcadd");
903        assert_fn(&cb, "bcsub");
904        assert_fn(&cb, "bcmul");
905        assert_fn(&cb, "bcdiv");
906        assert_fn(&cb, "sodium_crypto_secretbox");
907        assert_fn(&cb, "sodium_randombytes_buf");
908
909        assert_cls(&cb, "SplObjectStorage");
910        assert_cls(&cb, "SplHeap");
911        assert_cls(&cb, "IteratorIterator");
912        assert_cls(&cb, "FilterIterator");
913        assert_cls(&cb, "LimitIterator");
914        assert_cls(&cb, "CallbackFilterIterator");
915        assert_cls(&cb, "RegexIterator");
916        assert_cls(&cb, "AppendIterator");
917        assert_cls(&cb, "GlobIterator");
918        assert_cls(&cb, "ReflectionObject");
919        assert_cls(&cb, "Attribute");
920
921        assert_iface(&cb, "SeekableIterator");
922        assert_iface(&cb, "SplObserver");
923        assert_iface(&cb, "SplSubject");
924
925        assert_const(&cb, "PHP_INT_MAX");
926        assert_const(&cb, "PHP_INT_MIN");
927        assert_const(&cb, "PHP_EOL");
928        assert_const(&cb, "SORT_REGULAR");
929        assert_const(&cb, "JSON_THROW_ON_ERROR");
930        assert_const(&cb, "FILTER_VALIDATE_EMAIL");
931        assert_const(&cb, "PREG_OFFSET_CAPTURE");
932        assert_const(&cb, "M_PI");
933        assert_const(&cb, "PASSWORD_DEFAULT");
934    }
935}