mir-analyzer 0.20.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
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
//! Session-based analysis API for incremental, per-file analysis.
//!
//! [`AnalysisSession`] owns the salsa database and per-session caches for a
//! long-running analysis context shared across many per-file analyses. Reads
//! clone the database under a brief lock, then run lock-free; writes hold the
//! lock briefly to mutate canonical state. `MirDb::clone()` is cheap
//! (Arc-wrapped registries), so this pattern gives parallel readers without
//! blocking on concurrent writes for longer than the clone itself.
//!
//! See [`crate::file_analyzer::FileAnalyzer`] for the per-file Pass 2 entry
//! point that operates against a session.

use std::collections::{HashMap, HashSet};
use std::path::PathBuf;
use std::sync::{Arc, Mutex};

use rayon::prelude::*;
use salsa::Setter as _;

use crate::cache::AnalysisCache;
use crate::composer::Psr4Map;
use crate::db::{collect_file_definitions, FileDefinitions, MirDatabase, MirDb, SourceFile};
use crate::php_version::PhpVersion;

/// Long-lived analysis context. Owns the salsa database and tracks which
/// stubs have been loaded.
///
/// Cheap to clone the inner db for parallel reads; writes funnel through
/// [`Self::ingest_file`], [`Self::invalidate_file`], and the crate-internal
/// [`Self::with_db_mut`].
pub struct AnalysisSession {
    salsa: Mutex<(MirDb, HashMap<Arc<str>, SourceFile>)>,
    cache: Option<Arc<AnalysisCache>>,
    psr4: Option<Arc<Psr4Map>>,
    /// Set of stub virtual paths that have already been ingested. Replaces an
    /// older `AtomicBool stubs_loaded` flag — tracking individual paths lets
    /// us lazy-load extension stubs on demand without re-ingesting essentials.
    loaded_stubs: Mutex<HashSet<&'static str>>,
    /// True once user stubs (configured via [`Self::with_user_stubs`]) have
    /// been ingested. They are loaded together with the essential set on the
    /// first call to a stubs-loading method.
    user_stubs_loaded: Mutex<bool>,
    php_version: PhpVersion,
    user_stub_files: Vec<PathBuf>,
    user_stub_dirs: Vec<PathBuf>,
}

impl AnalysisSession {
    /// Create a session targeting the given PHP language version.
    pub fn new(php_version: PhpVersion) -> Self {
        Self {
            salsa: Mutex::new((MirDb::default(), HashMap::new())),
            cache: None,
            psr4: None,
            loaded_stubs: Mutex::new(HashSet::new()),
            user_stubs_loaded: Mutex::new(false),
            php_version,
            user_stub_files: Vec::new(),
            user_stub_dirs: Vec::new(),
        }
    }

    pub fn with_cache(mut self, cache: Arc<AnalysisCache>) -> Self {
        self.cache = Some(cache);
        self
    }

    pub fn with_psr4(mut self, map: Arc<Psr4Map>) -> Self {
        self.psr4 = Some(map);
        self
    }

    pub fn with_user_stubs(mut self, files: Vec<PathBuf>, dirs: Vec<PathBuf>) -> Self {
        self.user_stub_files = files;
        self.user_stub_dirs = dirs;
        self
    }

    pub fn php_version(&self) -> PhpVersion {
        self.php_version
    }

    pub fn cache(&self) -> Option<&AnalysisCache> {
        self.cache.as_deref()
    }

    pub fn psr4(&self) -> Option<&Psr4Map> {
        self.psr4.as_deref()
    }

    /// Load every PHP built-in stub plus any configured user stubs.
    /// Idempotent. Equivalent to the legacy "load everything" behavior; use
    /// [`Self::ensure_essential_stubs_loaded`] in incremental scenarios where
    /// cold-start latency matters more than comprehensive stub coverage.
    pub fn ensure_stubs_loaded(&self) {
        self.ensure_all_stubs_loaded();
    }

    /// Load only the curated set of essential stubs (Core, standard, SPL,
    /// date) plus any configured user stubs. About 25 of 120 stub files;
    /// covers types and functions used by virtually all PHP code.
    ///
    /// Other extension stubs (Reflection, gd, openssl, …) can be brought in
    /// on demand via [`Self::ensure_stubs_for_symbol`] when user code
    /// references them. Idempotent — already-loaded stubs are skipped.
    pub fn ensure_essential_stubs_loaded(&self) {
        self.ingest_stub_paths(crate::stubs::ESSENTIAL_STUB_PATHS);
        self.ensure_user_stubs_loaded();
    }

    /// Load every embedded PHP stub plus any configured user stubs.
    /// Use for batch tools (CLI, full project analysis) where comprehensive
    /// symbol coverage matters more than cold-start latency.
    pub fn ensure_all_stubs_loaded(&self) {
        let paths: Vec<&'static str> = crate::stubs::stub_files().iter().map(|&(p, _)| p).collect();
        self.ingest_stub_paths(&paths);
        self.ensure_user_stubs_loaded();
    }

    /// Ensure the embedded stub that defines `name` (a function) is ingested.
    /// Returns `true` when a matching stub exists (whether or not it was
    /// already loaded), `false` when `name` isn't a known PHP built-in.
    pub fn ensure_stub_for_function(&self, name: &str) -> bool {
        match crate::stubs::stub_path_for_function(name) {
            Some(path) => {
                self.ingest_stub_paths(&[path]);
                true
            }
            None => false,
        }
    }

    /// Ensure the embedded stub that defines `fqcn` (a class / interface /
    /// trait / enum) is ingested. Case-insensitive lookup with optional
    /// leading backslash.
    pub fn ensure_stub_for_class(&self, fqcn: &str) -> bool {
        match crate::stubs::stub_path_for_class(fqcn) {
            Some(path) => {
                self.ingest_stub_paths(&[path]);
                true
            }
            None => false,
        }
    }

    /// Ensure the embedded stub that defines `name` (a constant) is ingested.
    pub fn ensure_stub_for_constant(&self, name: &str) -> bool {
        match crate::stubs::stub_path_for_constant(name) {
            Some(path) => {
                self.ingest_stub_paths(&[path]);
                true
            }
            None => false,
        }
    }

    /// Number of distinct embedded stubs currently ingested into the session.
    /// Useful for diagnostics and bench reporting.
    pub fn loaded_stub_count(&self) -> usize {
        self.loaded_stubs.lock().expect("loaded_stubs lock").len()
    }

    /// Auto-discover and ingest the embedded stubs needed to cover every
    /// built-in PHP function / class / constant referenced by `source`.
    ///
    /// Used by [`crate::FileAnalyzer::analyze`] to keep essentials-only mode
    /// correct without forcing callers to enumerate which stubs they need.
    /// Idempotent — already-loaded stubs are skipped via [`Self::loaded_stubs`].
    ///
    /// The discovery scan is a coarse identifier sweep (see
    /// [`crate::stubs::collect_referenced_builtin_paths`]) — it may pull in
    /// a slightly larger set than the file strictly needs, but never misses
    /// a referenced built-in. Cost is sub-millisecond per file.
    ///
    /// Fast path: if every embedded stub is already loaded (e.g. after a
    /// batch tool called [`Self::ensure_all_stubs_loaded`]), the source scan
    /// is skipped entirely.
    pub fn ensure_stubs_for_source(&self, source: &str) {
        // Cheap check first: skip the scan entirely when we already know we
        // have everything. Avoids a ~50-500µs source walk on every analyze
        // call in batch / warm-session scenarios.
        {
            let loaded = self.loaded_stubs.lock().expect("loaded_stubs lock");
            if loaded.len() >= crate::stubs::stub_files().len() {
                return;
            }
        }
        let paths = crate::stubs::collect_referenced_builtin_paths(source);
        if paths.is_empty() {
            return;
        }
        self.ingest_stub_paths(&paths);
    }

    /// Internal: parse + ingest each path in `paths` that hasn't already been
    /// ingested. Holds the salsa write lock per file (brief), and the
    /// `loaded_stubs` set lock briefly to record paths.
    fn ingest_stub_paths(&self, paths: &[&'static str]) {
        // Pick out the not-yet-loaded paths first to avoid redundant parsing.
        let needed: Vec<&'static str> = {
            let loaded = self.loaded_stubs.lock().expect("loaded_stubs lock");
            paths
                .iter()
                .copied()
                .filter(|p| !loaded.contains(p))
                .collect()
        };
        if needed.is_empty() {
            return;
        }

        let php_version = self.php_version;
        // Parse in parallel; ingest serially under the salsa write lock.
        let slices: Vec<(&'static str, mir_codebase::storage::StubSlice)> = needed
            .par_iter()
            .filter_map(|&path| {
                crate::stubs::stub_content_for_path(path).map(|content| {
                    let slice =
                        crate::stubs::stub_slice_from_source(path, content, Some(php_version));
                    (path, slice)
                })
            })
            .collect();

        let mut guard = self.salsa.lock().expect("salsa lock poisoned");
        let mut loaded = self.loaded_stubs.lock().expect("loaded_stubs lock");
        for (path, slice) in slices {
            if loaded.insert(path) {
                guard.0.ingest_stub_slice(&slice);
            }
        }
    }

    fn ensure_user_stubs_loaded(&self) {
        if self.user_stub_files.is_empty() && self.user_stub_dirs.is_empty() {
            return;
        }
        let mut guard = self.user_stubs_loaded.lock().expect("user_stubs lock");
        if *guard {
            return;
        }
        let slices = crate::stubs::user_stub_slices(&self.user_stub_files, &self.user_stub_dirs);
        let mut salsa = self.salsa.lock().expect("salsa lock poisoned");
        for slice in slices {
            salsa.0.ingest_stub_slice(&slice);
        }
        *guard = true;
    }

    /// Cheap clone of the salsa db for a read-only query. The lock is held
    /// only for the duration of the clone, so concurrent readers never
    /// serialize on each other or on writes for longer than the clone itself.
    pub fn snapshot_db(&self) -> MirDb {
        let guard = self.salsa.lock().expect("salsa lock poisoned");
        guard.0.clone()
    }

    /// Run a closure with read access to a database snapshot. The snapshot is
    /// taken under a brief lock, then the closure runs without holding it.
    pub fn read<R>(&self, f: impl FnOnce(&dyn MirDatabase) -> R) -> R {
        let db = self.snapshot_db();
        f(&db)
    }

    /// Pass 1 ingestion. Updates the file's source text in the salsa db,
    /// runs definition collection, and ingests the resulting stub slice.
    /// Triggers stub loading on first call. Also updates the cache's reverse-
    /// dependency graph for `file` so cross-file invalidation stays correct
    /// across incremental edits — without rebuilding the graph from scratch.
    ///
    /// If `file` was previously ingested, its old definitions and reference
    /// locations are removed first so renames / deletions don't leave stale
    /// state in the codebase. (Without this, long-running sessions would
    /// accumulate dead reference-location entries indefinitely.)
    pub fn ingest_file(&self, file: Arc<str>, source: Arc<str>) -> FileDefinitions {
        self.ensure_stubs_loaded();
        let file_defs = {
            let mut guard = self.salsa.lock().expect("salsa lock poisoned");
            let (ref mut db, ref mut files) = *guard;
            let salsa_file = match files.get(&file) {
                Some(&sf) => {
                    // Re-ingestion: drop old definitions + reference locations
                    // before collecting fresh ones. Mirrors what
                    // ProjectAnalyzer::re_analyze_file does.
                    db.remove_file_definitions(file.as_ref());
                    if sf.text(db).as_ref() != source.as_ref() {
                        sf.set_text(db).to(source.clone());
                    }
                    sf
                }
                None => {
                    let sf = SourceFile::new(db, file.clone(), source.clone());
                    files.insert(file.clone(), sf);
                    sf
                }
            };
            collect_file_definitions(db, salsa_file)
        };
        {
            let mut guard = self.salsa.lock().expect("salsa lock poisoned");
            guard.0.ingest_stub_slice(&file_defs.slice);
        }
        self.update_reverse_deps_for(&file);
        file_defs
    }

    /// Drop a file's contribution to the session: codebase definitions,
    /// reference locations, salsa input handle, cache entry, and outgoing
    /// reverse-dependency edges. Cache entries of *dependent* files are
    /// also evicted (cross-file invalidation).
    ///
    /// Use this when a file is closed by the consumer, or before a re-ingest
    /// of substantially changed content. (Plain re-ingest via
    /// [`Self::ingest_file`] also drops old definitions, but does not
    /// remove the salsa input handle — call this for full cleanup.)
    pub fn invalidate_file(&self, file: &str) {
        {
            let mut guard = self.salsa.lock().expect("salsa lock poisoned");
            let (ref mut db, ref mut files) = *guard;
            db.remove_file_definitions(file);
            files.remove(file);
        }
        if let Some(cache) = &self.cache {
            cache.update_reverse_deps_for_file(file, &HashSet::new());
            cache.evict_with_dependents(&[file.to_string()]);
        }
    }

    /// Number of files currently tracked in this session's salsa input set.
    /// Stable across reads; useful for diagnostics and memory bounds checks.
    pub fn tracked_file_count(&self) -> usize {
        let guard = self.salsa.lock().expect("salsa lock poisoned");
        guard.1.len()
    }

    // -----------------------------------------------------------------------
    // Read-only codebase queries
    //
    // All take a brief lock to clone the db, then run the lookup against the
    // owned snapshot — concurrent edits proceed without blocking.
    // -----------------------------------------------------------------------

    /// Resolve `symbol` (a class FQCN or function FQN) to its declaration
    /// location. Powers go-to-definition for top-level symbols. Returns
    /// `None` if the symbol isn't known to the codebase or has no recorded
    /// source span (e.g. some stub-only declarations).
    pub fn definition_of(&self, symbol: &str) -> Option<mir_codebase::storage::Location> {
        let db = self.snapshot_db();
        db.lookup_class_node(symbol)
            .filter(|n| n.active(&db))
            .and_then(|n| n.location(&db))
            .or_else(|| {
                db.lookup_function_node(symbol)
                    .filter(|n| n.active(&db))
                    .and_then(|n| n.location(&db))
            })
    }

    /// Resolve a class member (method / property / class constant / enum case)
    /// to its declaration location, walking the inheritance chain.
    pub fn member_definition(
        &self,
        fqcn: &str,
        member_name: &str,
    ) -> Option<mir_codebase::storage::Location> {
        let db = self.snapshot_db();
        crate::db::member_location_via_db(&db, fqcn, member_name)
    }

    /// Every recorded reference to `symbol` (as `(file, line, col_start,
    /// col_end)`). Use [`crate::symbol::ResolvedSymbol::codebase_key`] to
    /// build the lookup key from a `ResolvedSymbol` returned by
    /// [`crate::FileAnalysis::symbol_at`].
    pub fn references_to(&self, symbol: &str) -> Vec<(Arc<str>, u32, u16, u16)> {
        let db = self.snapshot_db();
        db.reference_locations(symbol)
    }

    /// All declarations defined in `file` (classes, interfaces, traits, enums,
    /// functions, constants). Powers outline / document-symbols views and any
    /// other consumer that needs the file's top-level symbol set. Returns an
    /// empty Vec if `file` hasn't been ingested.
    pub fn document_symbols(&self, file: &str) -> Vec<crate::symbol::DocumentSymbol> {
        use crate::symbol::{DocumentSymbol, DocumentSymbolKind};

        let db = self.snapshot_db();
        let mut out = Vec::new();
        for symbol in db.symbols_defined_in_file(file) {
            // Try class side first — covers Class / Interface / Trait / Enum.
            if let Some(class_node) = db.lookup_class_node(symbol.as_ref()) {
                if !class_node.active(&db) {
                    continue;
                }
                let kind = crate::db::class_kind_via_db(&db, symbol.as_ref())
                    .map(|k| {
                        if k.is_interface {
                            DocumentSymbolKind::Interface
                        } else if k.is_trait {
                            DocumentSymbolKind::Trait
                        } else if k.is_enum {
                            DocumentSymbolKind::Enum
                        } else {
                            DocumentSymbolKind::Class
                        }
                    })
                    .unwrap_or(DocumentSymbolKind::Class);
                out.push(DocumentSymbol {
                    name: symbol.clone(),
                    kind,
                    location: class_node.location(&db),
                });
                continue;
            }
            if let Some(fn_node) = db.lookup_function_node(symbol.as_ref()) {
                if !fn_node.active(&db) {
                    continue;
                }
                out.push(DocumentSymbol {
                    name: symbol.clone(),
                    kind: DocumentSymbolKind::Function,
                    location: fn_node.location(&db),
                });
                continue;
            }
            // Constants and other top-level declarations: emit with no
            // location info; consumers can still surface them in an outline.
            out.push(DocumentSymbol {
                name: symbol,
                kind: DocumentSymbolKind::Constant,
                location: None,
            });
        }
        out
    }

    /// Compute `file`'s outgoing dependency edges and update the cache's
    /// reverse-dep graph in place. No-op if no cache is configured.
    fn update_reverse_deps_for(&self, file: &str) {
        let Some(cache) = self.cache.as_deref() else {
            return;
        };
        let db = self.snapshot_db();
        let targets = file_outgoing_dependencies(&db, file);
        cache.update_reverse_deps_for_file(file, &targets);
    }

    /// Cross-file inference sweep. For each `(file, source)` pair, runs the
    /// Pass 2 inference-only mode on a cloned db (parallel via rayon), then
    /// commits the collected inferred return types to the canonical db.
    ///
    /// Call this on idle / save / explicit user request, **not** on every
    /// keystroke — [`crate::FileAnalyzer::analyze`] deliberately skips
    /// inference sweep on the hot path. Files whose source contains parse
    /// errors are silently skipped.
    pub fn run_inference_sweep(&self, files: &[(Arc<str>, Arc<str>)]) {
        self.ensure_stubs_loaded();

        // The priming db lives only inside `gather_inferred_types`. After it
        // returns, all rayon-clone references to the salsa storage are dropped
        // — required so that the subsequent `commit_inferred_return_types`
        // call (which calls salsa's `cancel_others`) doesn't deadlock waiting
        // for outstanding db references.
        let (functions, methods) =
            gather_inferred_types(self.snapshot_db(), files, self.php_version);

        let mut guard = self.salsa.lock().expect("salsa lock poisoned");
        guard.0.commit_inferred_return_types(functions, methods);
    }
}

/// Drive Pass 2 inference-only mode in parallel across `files`, accumulating
/// inferred function and method return types. The `db_priming` MirDb is
/// consumed (cloned per spawned task and dropped on return), so the caller's
/// canonical db can subsequently take exclusive access without deadlock.
///
/// Crate-internal so [`crate::project::ProjectAnalyzer`] can use the same
/// deadlock-safe helper for its lazy-load reanalysis sweep.
#[allow(clippy::type_complexity)]
pub(crate) fn gather_inferred_types(
    db_priming: MirDb,
    files: &[(Arc<str>, Arc<str>)],
    php_version: PhpVersion,
) -> (
    Vec<(Arc<str>, mir_types::Union)>,
    Vec<(Arc<str>, Arc<str>, mir_types::Union)>,
) {
    use crate::pass2::Pass2Driver;
    use mir_types::Union;
    use std::sync::Mutex as StdMutex;

    type Functions = Vec<(Arc<str>, Union)>;
    type Methods = Vec<(Arc<str>, Arc<str>, Union)>;
    let functions: Arc<StdMutex<Functions>> = Arc::new(StdMutex::new(Vec::new()));
    let methods: Arc<StdMutex<Methods>> = Arc::new(StdMutex::new(Vec::new()));

    rayon::in_place_scope(|s| {
        for (file, source) in files {
            let db = db_priming.clone();
            let functions = Arc::clone(&functions);
            let methods = Arc::clone(&methods);
            let file = file.clone();
            let source = source.clone();

            s.spawn(move |_| {
                let arena = bumpalo::Bump::new();
                let parsed = php_rs_parser::parse(&arena, source.as_ref());
                if !parsed.errors.is_empty() {
                    return;
                }
                let driver = Pass2Driver::new_inference_only(&db as &dyn MirDatabase, php_version);
                driver.analyze_bodies(&parsed.program, file, source.as_ref(), &parsed.source_map);
                let inferred = driver.take_inferred_types();
                if let Ok(mut f) = functions.lock() {
                    f.extend(inferred.functions);
                }
                if let Ok(mut m) = methods.lock() {
                    m.extend(inferred.methods);
                }
            });
        }
    });

    let functions = Arc::try_unwrap(functions)
        .map(|m| m.into_inner().unwrap_or_default())
        .unwrap_or_else(|arc| arc.lock().unwrap().clone());
    let methods = Arc::try_unwrap(methods)
        .map(|m| m.into_inner().unwrap_or_default())
        .unwrap_or_else(|arc| arc.lock().unwrap().clone());

    (functions, methods)
}

/// Compute the set of files `file` depends on: defining files of its imports,
/// plus parent / interfaces / traits' defining files for any classes declared
/// in `file`. Self-edges are excluded.
fn file_outgoing_dependencies(db: &dyn MirDatabase, file: &str) -> HashSet<String> {
    let mut targets: HashSet<String> = HashSet::new();

    let mut add_target = |symbol: &str| {
        if let Some(defining_file) = db.symbol_defining_file(symbol) {
            let def = defining_file.as_ref().to_string();
            if def != file {
                targets.insert(def);
            }
        }
    };

    let imports = db.file_imports(file);
    for fqcn in imports.values() {
        add_target(fqcn);
    }

    for fqcn in db.symbols_defined_in_file(file) {
        let Some(node) = db.lookup_class_node(fqcn.as_ref()) else {
            continue;
        };
        if let Some(parent) = node.parent(db) {
            add_target(parent.as_ref());
        }
        for iface in node.interfaces(db).iter() {
            add_target(iface.as_ref());
        }
        for tr in node.traits(db).iter() {
            add_target(tr.as_ref());
        }
    }

    targets
}