mir-analyzer 0.9.0

Analysis engine for the mir PHP static analyzer
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
/// PHP built-in stubs — registered into the `Codebase` before user-code analysis.
///
/// Stubs are loaded in two layers:
///
/// 1. **phpstorm-stubs** (authoritative) — the JetBrains community stub set,
///    embedded at compile time via `build.rs`.  Covers the full PHP standard
///    library with accurate types.
///
/// 2. **Custom PHP stubs** (`stubs/{ext}/*.php`) — precise type overrides,
///    embedded at compile time via `build.rs`.  Each file gets a stable virtual
///    path (e.g. `"stubs/standard/basic.php"`) so symbols are source-attributed
///    and go-to-definition works for them.
///
/// # `StubVfs`
///
/// [`StubVfs`] maps every embedded stub file path to its `&'static str` content.
/// LSP consumers use it to serve stub file content for go-to-definition on
/// built-in PHP symbols:
///
/// ```ignore
/// let file = codebase.symbol_to_file.get("strlen"); // → "standard/standard_0.php"
/// let src  = stub_vfs.get(&file).unwrap();           // → &'static str PHP source
/// ```
use std::collections::{HashMap, HashSet};
use std::sync::{Arc, LazyLock};

use mir_codebase::Codebase;

// Generated by build.rs: `static PHPSTORM_STUB_FILES: &[(&str, &str)]`
include!(concat!(env!("OUT_DIR"), "/phpstorm_stubs.rs"));

// Generated by build.rs: `static BUILTIN_FN_NAMES: &[&str]`
include!(concat!(env!("OUT_DIR"), "/phpstorm_builtin_fns.rs"));

// Generated by build.rs: `static CUSTOM_STUB_FILES: &[(&str, &str)]`
include!(concat!(env!("OUT_DIR"), "/custom_stub_files.rs"));

// ---------------------------------------------------------------------------
// Public accessors for embedded stub data
// ---------------------------------------------------------------------------

/// Every phpstorm-stubs PHP file embedded at compile time as `(path, content)`.
///
/// Path is relative to the `phpstorm-stubs/` submodule root (e.g.
/// `"standard/standard_0.php"`).  Empty when the submodule is not initialized.
///
/// LSP consumers can use this together with [`custom_stub_files`] to build a
/// [`StubVfs`] or their own content index without going through
/// [`ProjectAnalyzer`].
pub fn phpstorm_stub_files() -> &'static [(&'static str, &'static str)] {
    PHPSTORM_STUB_FILES
}

/// Every custom PHP stub file from `stubs/{ext}/` embedded at compile time as
/// `(path, content)`.
///
/// Path is workspace-relative (e.g. `"stubs/standard/basic.php"`).
pub fn custom_stub_files() -> &'static [(&'static str, &'static str)] {
    CUSTOM_STUB_FILES
}

// ---------------------------------------------------------------------------
// Public entry point
// ---------------------------------------------------------------------------

pub fn load_stubs(codebase: &Codebase) {
    // Layer 1: parse phpstorm-stubs for comprehensive built-in coverage.
    load_phpstorm_stubs(codebase);
    // Layer 2: custom PHP stubs from stubs/{ext}/*.php — precise type overrides.
    load_custom_stubs(codebase);
}

// ---------------------------------------------------------------------------
// phpstorm-stubs loader
// ---------------------------------------------------------------------------

/// Parse every embedded phpstorm-stub file through the standard PHP parser and
/// `DefinitionCollector`, populating `codebase` with PHP built-in definitions.
fn load_phpstorm_stubs(codebase: &Codebase) {
    for (filename, content) in PHPSTORM_STUB_FILES {
        let arena = bumpalo::Bump::new();
        let result = php_rs_parser::parse(&arena, content);
        let file: Arc<str> = Arc::from(*filename);
        let collector =
            crate::collector::DefinitionCollector::new(codebase, file, content, &result.source_map);
        // Ignore stub parse issues — they don't affect user code analysis.
        let _ = collector.collect(&result.program);
    }
}

// ---------------------------------------------------------------------------
// Custom stub loader
// ---------------------------------------------------------------------------

/// Parse every embedded custom stub file through the standard PHP parser and
/// `DefinitionCollector`, overriding phpstorm-stubs definitions with more
/// precise types where needed.
///
/// Each file receives a workspace-relative virtual path (e.g.
/// `"stubs/standard/basic.php"`) so its symbols appear in
/// `Codebase::symbol_to_file` and are navigable via go-to-definition.
fn load_custom_stubs(codebase: &Codebase) {
    for (filename, content) in CUSTOM_STUB_FILES {
        let arena = bumpalo::Bump::new();
        let result = php_rs_parser::parse(&arena, content);
        let file: Arc<str> = Arc::from(*filename);
        let collector =
            crate::collector::DefinitionCollector::new(codebase, file, content, &result.source_map);
        let _ = collector.collect(&result.program);
    }
}

// ---------------------------------------------------------------------------
// StubVfs — virtual file system for stub content
// ---------------------------------------------------------------------------

/// A read-only map from stub file path to its embedded PHP source content.
///
/// Covers both phpstorm-stubs files and custom `stubs/{ext}/` files.  LSP
/// consumers use this to serve stub source for go-to-definition on built-in
/// PHP symbols without requiring the phpstorm-stubs submodule to be present
/// on the user's machine.
///
/// # Example
///
/// ```ignore
/// let vfs = StubVfs::new();
/// // After analysis:
/// if let Some(path) = codebase.symbol_to_file.get("strlen") {
///     if let Some(src) = vfs.get(&path) {
///         // serve `src` as a read-only virtual document to the LSP client
///     }
/// }
/// ```
pub struct StubVfs {
    files: HashMap<&'static str, &'static str>,
}

impl StubVfs {
    /// Build the VFS from both embedded stub sets.
    pub fn new() -> Self {
        let mut files = HashMap::new();
        for &(path, content) in PHPSTORM_STUB_FILES {
            files.insert(path, content);
        }
        for &(path, content) in CUSTOM_STUB_FILES {
            files.insert(path, content);
        }
        Self { files }
    }

    /// Return the PHP source for `path`, or `None` if it is not a stub file.
    pub fn get(&self, path: &str) -> Option<&'static str> {
        self.files.get(path).copied()
    }

    /// Return `true` if `path` is a known stub file path.
    pub fn is_stub_file(&self, path: &str) -> bool {
        self.files.contains_key(path)
    }
}

impl Default for StubVfs {
    fn default() -> Self {
        Self::new()
    }
}

// ---------------------------------------------------------------------------
// Builtin-function query
// ---------------------------------------------------------------------------

/// Returns `true` if `name` is a known PHP built-in function.
///
/// Fast path: binary search on `BUILTIN_FN_NAMES`, a sorted compile-time slice
/// generated from `PhpStormStubsMap.php` by `build.rs`.
///
/// Fallback (phpstorm-stubs submodule absent, e.g. CI without submodule init):
/// builds a `Codebase` from hand-written stubs and checks membership there.
///
/// # Example
/// ```
/// assert!(mir_analyzer::stubs::is_builtin_function("strlen"));
/// assert!(!mir_analyzer::stubs::is_builtin_function("my_custom_function"));
/// ```
pub fn is_builtin_function(name: &str) -> bool {
    if !BUILTIN_FN_NAMES.is_empty() {
        return BUILTIN_FN_NAMES.binary_search(&name).is_ok();
    }
    // Fallback when phpstorm-stubs submodule is absent: load hand-written stubs.
    static FALLBACK: LazyLock<HashSet<Arc<str>>> = LazyLock::new(|| {
        let codebase = Codebase::new();
        load_stubs(&codebase);
        codebase.functions.iter().map(|e| e.key().clone()).collect()
    });
    FALLBACK.contains(name)
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;
    use mir_codebase::Codebase;

    fn stubs_codebase() -> Codebase {
        let cb = Codebase::new();
        load_stubs(&cb);
        cb
    }

    fn assert_fn(cb: &Codebase, name: &str) {
        assert!(
            cb.functions.contains_key(name),
            "expected stub for `{name}` to be registered"
        );
    }

    #[test]
    fn sscanf_vars_param_is_byref_and_variadic() {
        let cb = stubs_codebase();
        let func = cb.functions.get("sscanf").expect("sscanf must be defined");
        let vars = func.params.get(2).expect("sscanf must have a 3rd param");
        assert!(vars.is_byref, "sscanf vars param must be by-ref");
        assert!(vars.is_variadic, "sscanf vars param must be variadic");
    }

    #[test]
    fn sscanf_output_vars_not_undefined() {
        use crate::project::ProjectAnalyzer;
        use mir_issues::IssueKind;

        let src = "<?php\nfunction test($str) {\n    sscanf($str, \"%d %d\", $row, $col);\n    return $row + $col;\n}\n";
        let tmp = std::env::temp_dir().join("mir_test_sscanf_undefined.php");
        std::fs::write(&tmp, src).unwrap();
        let result = ProjectAnalyzer::new().analyze(std::slice::from_ref(&tmp));
        std::fs::remove_file(tmp).ok();
        let undef: Vec<_> = result.issues.iter()
            .filter(|i| matches!(&i.kind, IssueKind::UndefinedVariable { name } if name == "row" || name == "col"))
            .collect();
        assert!(
            undef.is_empty(),
            "sscanf output vars must not be reported as UndefinedVariable; got: {undef:?}"
        );
    }

    #[test]
    fn stream_functions_are_defined() {
        let cb = stubs_codebase();
        assert_fn(&cb, "stream_isatty");
        assert_fn(&cb, "stream_select");
        assert_fn(&cb, "stream_get_meta_data");
        assert_fn(&cb, "stream_set_blocking");
        assert_fn(&cb, "stream_copy_to_stream");
    }

    #[test]
    fn preg_grep_is_defined() {
        let cb = stubs_codebase();
        assert_fn(&cb, "preg_grep");
    }

    #[test]
    fn standard_missing_functions_are_defined() {
        let cb = stubs_codebase();
        assert_fn(&cb, "get_resource_type");
        assert_fn(&cb, "ftruncate");
        assert_fn(&cb, "umask");
        assert_fn(&cb, "date_default_timezone_set");
        assert_fn(&cb, "date_default_timezone_get");
    }

    #[test]
    fn mb_missing_functions_are_defined() {
        let cb = stubs_codebase();
        assert_fn(&cb, "mb_strwidth");
        assert_fn(&cb, "mb_convert_variables");
    }

    #[test]
    fn pcntl_functions_are_defined() {
        let cb = stubs_codebase();
        assert_fn(&cb, "pcntl_signal");
        assert_fn(&cb, "pcntl_async_signals");
        assert_fn(&cb, "pcntl_signal_get_handler");
        assert_fn(&cb, "pcntl_alarm");
    }

    #[test]
    fn posix_functions_are_defined() {
        let cb = stubs_codebase();
        assert_fn(&cb, "posix_kill");
        assert_fn(&cb, "posix_getpid");
    }

    #[test]
    fn sapi_windows_functions_are_defined() {
        let cb = stubs_codebase();
        assert_fn(&cb, "sapi_windows_vt100_support");
        assert_fn(&cb, "sapi_windows_cp_set");
        assert_fn(&cb, "sapi_windows_cp_get");
        assert_fn(&cb, "sapi_windows_cp_conv");
    }

    #[test]
    fn cli_functions_are_defined() {
        let cb = stubs_codebase();
        assert_fn(&cb, "cli_set_process_title");
        assert_fn(&cb, "cli_get_process_title");
    }

    #[test]
    fn is_builtin_function_returns_true_for_known_builtins() {
        assert!(is_builtin_function("strlen"), "strlen should be a builtin");
        assert!(
            is_builtin_function("array_map"),
            "array_map should be a builtin"
        );
        assert!(
            is_builtin_function("json_encode"),
            "json_encode should be a builtin"
        );
        assert!(
            is_builtin_function("preg_match"),
            "preg_match should be a builtin"
        );
    }

    #[test]
    fn is_builtin_function_covers_phpstorm_stubs_only_functions() {
        if PHPSTORM_STUB_FILES.is_empty() {
            return; // submodule not initialized — skip
        }
        // These are only in phpstorm-stubs, not in the hand-written set.
        assert!(is_builtin_function("bcadd"), "bcadd should be a builtin");
        assert!(
            is_builtin_function("sodium_crypto_secretbox"),
            "sodium_crypto_secretbox should be a builtin"
        );
    }

    #[test]
    fn is_builtin_function_returns_false_for_unknown_names() {
        assert!(
            !is_builtin_function("my_custom_function"),
            "my_custom_function should not be a builtin"
        );
        assert!(
            !is_builtin_function(""),
            "empty string should not be a builtin"
        );
        assert!(
            !is_builtin_function("ast\\parse_file"),
            "extension function should not be a builtin"
        );
    }

    // --- phpstorm-stubs coverage tests ---

    fn assert_cls(cb: &Codebase, name: &str) {
        assert!(
            cb.classes.contains_key(name),
            "expected phpstorm stub class `{name}` to be registered"
        );
    }

    fn assert_iface(cb: &Codebase, name: &str) {
        assert!(
            cb.interfaces.contains_key(name),
            "expected phpstorm stub interface `{name}` to be registered"
        );
    }

    fn assert_const(cb: &Codebase, name: &str) {
        assert!(
            cb.constants.contains_key(name),
            "expected phpstorm stub constant `{name}` to be registered"
        );
    }

    #[test]
    fn phpstorm_stubs_coverage_counts() {
        if PHPSTORM_STUB_FILES.is_empty() {
            return;
        }
        let cb = stubs_codebase();
        let fn_count = cb.functions.len();
        let cls_count = cb.classes.len();
        let iface_count = cb.interfaces.len();
        let const_count = cb.constants.len();
        // Sanity lower bounds — phpstorm-stubs is comprehensive.
        assert!(fn_count > 500, "expected >500 functions, got {fn_count}");
        assert!(cls_count > 100, "expected >100 classes, got {cls_count}");
        assert!(
            iface_count > 20,
            "expected >20 interfaces, got {iface_count}"
        );
        assert!(
            const_count > 200,
            "expected >200 constants, got {const_count}"
        );
    }

    #[test]
    fn curl_multi_exec_still_running_is_byref() {
        let cb = stubs_codebase();
        let func = cb
            .functions
            .get("curl_multi_exec")
            .expect("curl_multi_exec must be defined");
        let still_running = func
            .params
            .iter()
            .find(|p| p.name.as_ref() == "still_running")
            .expect("curl_multi_exec must have a still_running param");
        assert!(
            still_running.is_byref,
            "curl_multi_exec $still_running must be by-ref (generated from PHP stub)"
        );
    }

    // --- Custom stub loading regression tests ---

    #[test]
    fn custom_stub_files_are_non_empty() {
        // Regression: CUSTOM_STUB_FILES was silently empty when build.rs used
        // the crate manifest dir instead of the workspace root to locate stubs/.
        assert!(
            !CUSTOM_STUB_FILES.is_empty(),
            "CUSTOM_STUB_FILES must not be empty — check build.rs find_workspace_root()"
        );
    }

    #[test]
    fn stub_vfs_resolves_all_custom_paths() {
        let vfs = StubVfs::new();
        for &(path, expected_content) in CUSTOM_STUB_FILES {
            let got = vfs
                .get(path)
                .unwrap_or_else(|| panic!("StubVfs::get({path:?}) returned None"));
            assert_eq!(got, expected_content, "StubVfs content mismatch for {path}");
            assert!(
                vfs.is_stub_file(path),
                "StubVfs::is_stub_file({path:?}) returned false"
            );
        }
    }

    #[test]
    fn stub_vfs_rejects_user_file_paths() {
        let vfs = StubVfs::new();
        assert!(!vfs.is_stub_file("/tmp/user_code.php"));
        assert!(!vfs.is_stub_file("src/MyClass.php"));
        assert!(!vfs.is_stub_file(""));
    }

    #[test]
    fn symbol_to_file_paths_are_resolvable_via_stub_vfs() {
        let cb = Codebase::new();
        load_stubs(&cb);
        let vfs = StubVfs::new();

        for entry in cb.symbol_to_file.iter() {
            let path = entry.value();
            assert!(
                vfs.get(path.as_ref()).is_some(),
                "symbol '{}' points to '{}' which StubVfs cannot resolve — \
                 go-to-definition would silently break for this symbol",
                entry.key(),
                path
            );
        }
    }

    #[test]
    fn phpstorm_stubs_loaded_when_submodule_present() {
        // This test only makes assertions when phpstorm-stubs is available.
        if PHPSTORM_STUB_FILES.is_empty() {
            return; // submodule not initialized — skip
        }
        let cb = stubs_codebase();

        // Previously missing functions now covered by phpstorm-stubs
        assert_fn(&cb, "bcadd");
        assert_fn(&cb, "bcsub");
        assert_fn(&cb, "bcmul");
        assert_fn(&cb, "bcdiv");
        assert_fn(&cb, "sodium_crypto_secretbox");
        assert_fn(&cb, "sodium_randombytes_buf");

        // Previously missing classes now covered by phpstorm-stubs
        assert_cls(&cb, "SplObjectStorage");
        assert_cls(&cb, "SplHeap");
        assert_cls(&cb, "IteratorIterator");
        assert_cls(&cb, "FilterIterator");
        assert_cls(&cb, "LimitIterator");
        assert_cls(&cb, "CallbackFilterIterator");
        assert_cls(&cb, "RegexIterator");
        assert_cls(&cb, "AppendIterator");
        assert_cls(&cb, "GlobIterator");
        assert_cls(&cb, "ReflectionObject");
        assert_cls(&cb, "Attribute");

        // Interfaces
        assert_iface(&cb, "SeekableIterator");
        assert_iface(&cb, "SplObserver");
        assert_iface(&cb, "SplSubject");

        // Constants from define() calls in phpstorm-stubs
        assert_const(&cb, "PHP_INT_MAX");
        assert_const(&cb, "PHP_INT_MIN");
        assert_const(&cb, "PHP_EOL");
        assert_const(&cb, "SORT_REGULAR");
        assert_const(&cb, "JSON_THROW_ON_ERROR");
        assert_const(&cb, "FILTER_VALIDATE_EMAIL");
        assert_const(&cb, "PREG_OFFSET_CAPTURE");
        assert_const(&cb, "M_PI");
        assert_const(&cb, "PASSWORD_DEFAULT");
    }
}