Skip to main content

mir_analyzer/session/
mod.rs

1//! Session-based analysis API for incremental, per-file analysis.
2//!
3//! [`AnalysisSession`] owns the salsa database and per-session caches for a
4//! long-running analysis context shared across many per-file analyses. Reads
5//! clone the database under a brief lock, then run lock-free; writes hold the
6//! lock briefly to mutate canonical state. `MirDbStorage::clone()` is cheap
7//! (Arc-wrapped registries), so this pattern gives parallel readers without
8//! blocking on concurrent writes for longer than the clone itself.
9//!
10//! See [`crate::file_analyzer::FileAnalyzer`] for the per-file analysis
11//! entry point that operates against a session.
12
13use rustc_hash::{FxHashMap as HashMap, FxHashSet as HashSet};
14use std::path::PathBuf;
15use std::sync::Arc;
16
17use parking_lot::RwLock;
18
19use crate::analyzer_db::AnalyzerDb;
20use crate::cache::AnalysisCache;
21use crate::composer::Psr4Map;
22use crate::db::{MirDatabase, MirDbStorage, RefLoc};
23use crate::php_version::PhpVersion;
24
25/// Long-lived analysis context. Owns the salsa database and tracks which
26/// stubs have been loaded.
27///
28/// Cheap to clone the inner db for parallel reads; writes funnel through
29/// [`Self::ingest_file`], [`Self::invalidate_file`], and the crate-internal
30/// [`Self::with_db_mut`].
31#[derive(Clone)]
32pub struct AnalysisSession {
33    /// Shared database management (salsa, file registry, stub tracking).
34    pub(crate) db: Arc<AnalyzerDb>,
35    pub(crate) cache: Option<Arc<AnalysisCache>>,
36    /// PSR-4 / Composer autoload map. Retained alongside `resolver` so the
37    /// `psr4()` accessor can still return a typed `Psr4Map` for callers that
38    /// need Composer-specific data (project_files / vendor_files / etc.).
39    pub(crate) psr4: Option<Arc<Psr4Map>>,
40    /// Generic class resolver used for on-demand lazy loading. When `psr4`
41    /// is set via [`Self::with_psr4`], this is populated with the same map
42    /// re-typed as `dyn ClassResolver`. Consumers can also supply their own
43    /// resolver via [`Self::with_class_resolver`] without going through
44    /// Composer.
45    resolver: Option<Arc<dyn crate::ClassResolver>>,
46    pub(crate) php_version: PhpVersion,
47    pub(crate) user_stub_files: Vec<PathBuf>,
48    pub(crate) user_stub_dirs: Vec<PathBuf>,
49    /// Tracks symbols that were previously defined in a file but have since
50    /// been removed (deleted or renamed). When `ingest_file` detects that
51    /// a symbol disappears, it records it here so `dependency_graph()` can
52    /// still produce edges to files that reference the now-gone symbol.
53    ///
54    /// Keyed by the file that used to define the symbols. Symbols are removed
55    /// from the set when re-added to the same file on a subsequent ingest.
56    /// The set may contain symbols with no current referencers; those are
57    /// harmless — the `symbol_referencers_of` lookup returns empty.
58    stale_defined_symbols: Arc<RwLock<HashMap<String, HashSet<Arc<str>>>>>,
59    /// Symbols defined by each file as of its last `ingest_file`. The
60    /// authoritative "old" set for the rename/deletion diff, independent of
61    /// whether the salsa `SourceFile` input was already updated to the new text
62    /// by a host driving the db directly (the LSP convergence path). Without
63    /// this, re-deriving "old" symbols from the (possibly pre-updated) input
64    /// would miss deletions and break cross-file dependency invalidation.
65    last_ingested_symbols: Arc<RwLock<HashMap<String, HashSet<Arc<str>>>>>,
66    /// Negative cache: FQCNs that `load_class` already failed on.
67    /// The value is the resolver-mapped path (when known) so eviction on
68    /// `set_file_text` / `ingest_file` is a path equality check rather than
69    /// re-running the resolver per entry. `None` means the resolver itself
70    /// couldn't map the FQCN; those entries survive file edits (no source
71    /// change makes a never-resolvable name resolvable).
72    /// Bounded to `UNRESOLVABLE_CACHE_CAP`; clears on overflow.
73    unresolvable_fqcns: UnresolvableCache,
74    /// Pluggable source-text provider for lazy-load. Defaults to filesystem
75    /// reads ([`crate::FsSourceProvider`]); LSPs swap in a VFS-backed
76    /// implementation so unsaved buffers override on-disk content.
77    source_provider: Arc<dyn crate::SourceProvider>,
78    /// Vendor `autoload.files` entries not yet indexed. `Some(paths)` means
79    /// pending; `None` means the load has already run (idempotent). Populated
80    /// by [`Self::with_psr4`]; drained by [`Self::ensure_vendor_eager_functions`],
81    /// which is called automatically from [`Self::prepare_ast_for_analysis`].
82    ///
83    /// The mutex is held for the full duration of the load so concurrent callers
84    /// block until indexing is complete rather than proceeding with a stale
85    /// workspace snapshot.
86    pub(crate) pending_eager_function_files: Arc<parking_lot::Mutex<Option<Vec<PathBuf>>>>,
87    /// Warm-up skip set: files whose [`Self::prepare_ast_for_analysis`] has
88    /// already run against their current text. Value is `(text, generation)` —
89    /// the entry is live while the file's input text is pointer-equal to `text`
90    /// (a text edit self-invalidates) and `generation` matches
91    /// [`Self::prepare_generation`]. Lets the per-request Phase-1 warm-up in
92    /// `references_to_in_files` / `reanalyze_dependents` skip the serial
93    /// parse + AST walk for files already faulted in.
94    prepared_files: PreparedFilesCache,
95    /// Bumped whenever previously loaded declarations may have been removed
96    /// (`invalidate_file`, symbol deletions on `ingest_file`, or a host calling
97    /// [`Self::bump_prepare_generation`]) — a prepared file might then need its
98    /// warm-up re-run to lazy-load a replacement (e.g. a vendor class shadowed
99    /// by a since-deleted project class).
100    prepare_generation: Arc<std::sync::atomic::AtomicU64>,
101}
102
103/// FQCN → optional resolver-mapped path. See the field doc on
104/// `AnalysisSession::unresolvable_fqcns`.
105type UnresolvableCache = Arc<RwLock<HashMap<Arc<str>, Option<Arc<str>>>>>;
106
107/// Warm-up skip set keyed by file path. See the field doc on
108/// `AnalysisSession::prepared_files`.
109type PreparedFilesCache = Arc<RwLock<HashMap<Arc<str>, (Arc<str>, u64)>>>;
110
111/// Cap on the negative-resolution cache. Sized to accommodate a large
112/// workspace's worth of genuinely-missing references without unbounded
113/// growth. On overflow the cache is cleared; the cost is a few extra
114/// resolver calls until it re-fills.
115const UNRESOLVABLE_CACHE_CAP: usize = 10_000;
116
117impl AnalysisSession {
118    /// Create a session targeting the given PHP language version.
119    pub fn new(php_version: PhpVersion) -> Self {
120        let db = Arc::new(AnalyzerDb::new());
121        db.salsa
122            .write()
123            .set_php_version(Arc::from(php_version.to_string().as_str()));
124        Self {
125            db,
126            cache: None,
127            psr4: None,
128            resolver: None,
129            php_version,
130            user_stub_files: Vec::new(),
131            user_stub_dirs: Vec::new(),
132            stale_defined_symbols: Arc::new(RwLock::new(HashMap::default())),
133            last_ingested_symbols: Arc::new(RwLock::new(HashMap::default())),
134            unresolvable_fqcns: Arc::new(RwLock::new(HashMap::default())),
135            source_provider: Arc::new(crate::FsSourceProvider),
136            pending_eager_function_files: Arc::new(parking_lot::Mutex::new(Some(Vec::new()))),
137            prepared_files: Arc::new(RwLock::new(HashMap::default())),
138            prepare_generation: Arc::new(std::sync::atomic::AtomicU64::new(0)),
139        }
140    }
141
142    /// Swap in a custom [`crate::SourceProvider`]. LSPs install a VFS-backed
143    /// provider here so the analyzer reads from unsaved editor buffers
144    /// instead of disk.
145    pub fn with_source_provider(mut self, provider: Arc<dyn crate::SourceProvider>) -> Self {
146        self.source_provider = provider;
147        self
148    }
149
150    /// Attach a pre-built [`AnalysisCache`] (the body-analysis issue cache) and
151    /// open a sibling definition [`StubSlice`] cache under the same root, so
152    /// callers using this builder get the same speedup as `with_cache_dir`.
153    ///
154    /// Rebuilds the shared database to attach the definition cache — call
155    /// **before** any file is ingested. A debug assertion catches misuse.
156    ///
157    /// [`StubSlice`]: mir_codebase::storage::StubSlice
158    pub fn with_cache(mut self, cache: Arc<AnalysisCache>) -> Self {
159        debug_assert_eq!(
160            self.db.source_file_count(),
161            0,
162            "AnalysisSession::with_cache must be called before any file is ingested"
163        );
164        let dir = cache.cache_dir().to_path_buf();
165        self.db = Arc::new(AnalyzerDb::new().with_cache_dir(&dir));
166        self.db
167            .salsa
168            .write()
169            .set_php_version(Arc::from(self.php_version.to_string().as_str()));
170        self.cache = Some(cache);
171        self
172    }
173
174    /// Convenience: open a disk-backed cache at `cache_dir` and attach it.
175    ///
176    /// Attaches both the body-analysis issue cache ([`AnalysisCache`]) and the
177    /// definition [`StubSlice`] cache to the shared database. Builds a fresh
178    /// [`AnalyzerDb`] internally — call **before** any file is ingested. A
179    /// debug assertion catches misuse.
180    ///
181    /// [`StubSlice`]: mir_codebase::storage::StubSlice
182    pub fn with_cache_dir(mut self, cache_dir: &std::path::Path) -> Self {
183        debug_assert_eq!(
184            self.db.source_file_count(),
185            0,
186            "AnalysisSession::with_cache_dir must be called before any file is ingested"
187        );
188        self.db = Arc::new(AnalyzerDb::new().with_cache_dir(cache_dir));
189        self.db
190            .salsa
191            .write()
192            .set_php_version(Arc::from(self.php_version.to_string().as_str()));
193        // Fold the user-stub fingerprint into the cache epoch. `with_user_stubs`
194        // must run before this for it to be picked up (it does in `build_session`);
195        // sessions without user stubs get 0, which is correct.
196        let user_stub_fp =
197            crate::stubs::user_stub_fingerprint(&self.user_stub_files, &self.user_stub_dirs);
198        self.cache = Some(Arc::new(AnalysisCache::open(
199            cache_dir,
200            self.php_version.cache_byte(),
201            user_stub_fp,
202        )));
203        self
204    }
205
206    /// Attach a Composer autoload map (PSR-4, PSR-0, classmap, files).
207    /// Sets the same map as the active [`crate::ClassResolver`] so
208    /// [`Self::load_class`] works out of the box.
209    pub fn with_psr4(mut self, map: Arc<Psr4Map>) -> Self {
210        let user_resolver: Arc<dyn crate::ClassResolver> = map.clone();
211        // Wrap with stub awareness so `find_class_like` / `resolve_fqcn_to_path`
212        // can map built-in PHP class FQCNs (`ArrayObject`, `Exception`, …)
213        // to their stub virtual paths.
214        let resolver: Arc<dyn crate::ClassResolver> = Arc::new(crate::ChainedClassResolver::new(
215            user_resolver,
216            Arc::new(crate::StubClassResolver),
217        ));
218        self.psr4 = Some(map.clone());
219        self.resolver = Some(resolver.clone());
220        // Mirror into MirDbStorage so salsa-tracked resolver queries
221        // (`db::resolve_fqcn_to_path`) see the same resolver and are
222        // invalidated on swap.
223        self.db.salsa.write().set_resolver(Some(resolver));
224        // Register vendor autoload.files for lazy loading. They define global
225        // functions and constants that the class resolver cannot discover.
226        // `ensure_vendor_eager_functions` will index them on first analysis call.
227        *self.pending_eager_function_files.lock() = Some(map.vendor_eager_files());
228        self
229    }
230
231    /// Attach a generic class resolver for projects that don't use Composer
232    /// (WordPress, Drupal, custom autoloaders, workspace-walk indexes).
233    /// Replaces any previously-set Composer-backed resolver. Automatically
234    /// wrapped with stub awareness so PHP built-ins remain resolvable.
235    pub fn with_class_resolver(mut self, resolver: Arc<dyn crate::ClassResolver>) -> Self {
236        let wrapped: Arc<dyn crate::ClassResolver> = Arc::new(crate::ChainedClassResolver::new(
237            resolver,
238            Arc::new(crate::StubClassResolver),
239        ));
240        self.db.salsa.write().set_resolver(Some(wrapped.clone()));
241        self.resolver = Some(wrapped);
242        self
243    }
244
245    pub fn with_user_stubs(mut self, files: Vec<PathBuf>, dirs: Vec<PathBuf>) -> Self {
246        self.user_stub_files = files;
247        self.user_stub_dirs = dirs;
248        self
249    }
250
251    pub fn php_version(&self) -> PhpVersion {
252        self.php_version
253    }
254
255    pub fn cache(&self) -> Option<&AnalysisCache> {
256        self.cache.as_deref()
257    }
258
259    pub fn psr4(&self) -> Option<&Psr4Map> {
260        self.psr4.as_deref()
261    }
262}
263
264mod incremental;
265mod ingest;
266mod loading;
267mod queries;
268mod stubs;
269
270/// Compute the full set of files `file` depends on: structural edges from
271/// the memoized [`crate::db::file_structural_deps`] tracked query, plus
272/// bare-FQN references recorded during body analysis (which live in the
273/// reference index and are not visible to salsa). Self-edges are excluded.
274/// Used to persist the disk cache's reverse-dep graph.
275fn file_outgoing_dependencies(db: &dyn MirDatabase, file: &str) -> HashSet<String> {
276    let mut targets: HashSet<String> = HashSet::default();
277
278    if let Some(sf) = db.lookup_source_file(file) {
279        for target in crate::db::file_structural_deps(db, sf).iter() {
280            targets.insert(target.as_ref().to_string());
281        }
282    }
283
284    // Bare-FQN references recorded during body analysis (new \Foo(),
285    // \Foo::method(), \foo()) that do not appear in use-import statements.
286    for symbol_key in db.file_referenced_symbols(file) {
287        let lookup: &str = match symbol_key.split_once("::") {
288            Some((class, _)) => class,
289            None => &symbol_key,
290        };
291        if let Some(defining_file) = db.symbol_defining_file(lookup) {
292            if defining_file.as_ref() != file {
293                targets.insert(defining_file.as_ref().to_string());
294            }
295        }
296    }
297
298    targets
299}
300
301/// AST visitor that collects class FQCN references for PSR-4 preloading.
302/// Captures identifiers from `new X`, static calls / property / constant
303/// access, type hints, `instanceof`, and `@param`/`@return`/`@var`/`@extends`/
304/// `@implements` docblock annotations. Does *not* normalize via PSR-4 /
305/// imports — callers run the raw string through `resolve_name`.
306fn collect_class_refs_from_ast(program: &php_ast::owned::Program) -> Vec<String> {
307    use php_ast::ast::BinaryOp;
308    use php_ast::owned::visitor::{
309        walk_owned_class_member, walk_owned_expr, walk_owned_program, walk_owned_stmt, OwnedVisitor,
310    };
311    use php_ast::owned::{ClassMemberKind, ExprKind};
312    use std::ops::ControlFlow;
313
314    fn owned_name_str(name: &php_ast::owned::Name) -> String {
315        let joined: String = name
316            .parts
317            .iter()
318            .map(|p| p.as_ref())
319            .collect::<Vec<&str>>()
320            .join("\\");
321        if name.kind == php_ast::ast::NameKind::FullyQualified {
322            format!("\\{joined}")
323        } else {
324            joined
325        }
326    }
327
328    /// Recursively collect all `TNamedObject` FQCNs from a mir type, including
329    /// those nested inside generic type parameters (e.g. `Collection<Item>`).
330    fn collect_from_type(ty: &mir_types::Type, out: &mut std::collections::HashSet<String>) {
331        for atomic in ty.types.iter() {
332            if let mir_types::Atomic::TNamedObject { fqcn, type_params } = atomic {
333                out.insert(fqcn.as_ref().to_string());
334                for tp in type_params.iter() {
335                    collect_from_type(tp, out);
336                }
337            }
338        }
339    }
340
341    /// Parse a docblock and collect class names from `@param`, `@return`,
342    /// `@var`, `@extends`, and `@implements` annotations.
343    fn collect_from_docblock(text: &str, out: &mut std::collections::HashSet<String>) {
344        let parsed = crate::parser::DocblockParser::parse(text);
345        for (_, ty) in &parsed.params {
346            collect_from_type(ty, out);
347        }
348        if let Some(ret) = &parsed.return_type {
349            collect_from_type(ret, out);
350        }
351        if let Some(var) = &parsed.var_type {
352            collect_from_type(var, out);
353        }
354        if let Some(ext) = &parsed.extends {
355            collect_from_type(ext, out);
356        }
357        for impl_ty in &parsed.implements {
358            collect_from_type(impl_ty, out);
359        }
360    }
361
362    struct V {
363        names: std::collections::HashSet<String>,
364    }
365    impl OwnedVisitor for V {
366        fn visit_stmt(&mut self, stmt: &php_ast::owned::Stmt) -> ControlFlow<()> {
367            if let Some(doc) = stmt.leading_doc_comment() {
368                collect_from_docblock(&doc.text, &mut self.names);
369            }
370            walk_owned_stmt(self, stmt)
371        }
372
373        fn visit_class_member(&mut self, member: &php_ast::owned::ClassMember) -> ControlFlow<()> {
374            match &member.kind {
375                ClassMemberKind::Method(m) => {
376                    if let Some(doc) = &m.doc_comment {
377                        collect_from_docblock(&doc.text, &mut self.names);
378                    }
379                }
380                ClassMemberKind::Property(p) => {
381                    if let Some(doc) = &p.doc_comment {
382                        collect_from_docblock(&doc.text, &mut self.names);
383                    }
384                }
385                _ => {}
386            }
387            walk_owned_class_member(self, member)
388        }
389
390        fn visit_expr(&mut self, expr: &php_ast::owned::Expr) -> ControlFlow<()> {
391            match &expr.kind {
392                ExprKind::New(n) => {
393                    if let ExprKind::Identifier(name) = &n.class.kind {
394                        self.names.insert(name.as_ref().to_string());
395                    }
396                }
397                ExprKind::StaticMethodCall(c) => {
398                    if let ExprKind::Identifier(name) = &c.class.kind {
399                        self.names.insert(name.as_ref().to_string());
400                    }
401                }
402                ExprKind::StaticPropertyAccess(a) => {
403                    if let ExprKind::Identifier(name) = &a.class.kind {
404                        self.names.insert(name.as_ref().to_string());
405                    }
406                }
407                ExprKind::ClassConstAccess(a) => {
408                    if let ExprKind::Identifier(name) = &a.class.kind {
409                        self.names.insert(name.as_ref().to_string());
410                    }
411                }
412                ExprKind::Binary(b) if b.op == BinaryOp::Instanceof => {
413                    if let ExprKind::Identifier(name) = &b.right.kind {
414                        self.names.insert(name.as_ref().to_string());
415                    }
416                }
417                _ => {}
418            }
419            walk_owned_expr(self, expr)
420        }
421
422        // Walker routes every class/type-position Name here: type hints, catch types, extends/implements, trait use, attributes.
423        fn visit_name(&mut self, name: &php_ast::owned::Name) -> ControlFlow<()> {
424            let s = owned_name_str(name);
425            if !s.is_empty() {
426                self.names.insert(s);
427            }
428            ControlFlow::Continue(())
429        }
430    }
431    let mut v = V {
432        names: std::collections::HashSet::default(),
433    };
434    let _ = walk_owned_program(&mut v, program);
435    v.names.into_iter().collect()
436}