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 /// `indexed_references_to` / `reanalyze_dependents` skip the serial
93 /// parse + AST walk for files already faulted in.
94 prepared_files: PreparedFilesCache,
95 /// Parsed suppression directives for unchanged files. Batch analysis
96 /// revisits every analyzed file to emit `UnusedSuppress`, so retaining
97 /// maps across same-session runs avoids rescanning the full workspace.
98 pub(crate) suppression_maps: SuppressionMapCache,
99 /// Bumped whenever previously loaded declarations may have been removed
100 /// (`invalidate_file`, symbol deletions on `ingest_file`, or a host calling
101 /// [`Self::bump_prepare_generation`]) — a prepared file might then need its
102 /// warm-up re-run to lazy-load a replacement (e.g. a vendor class shadowed
103 /// by a since-deleted project class).
104 prepare_generation: Arc<std::sync::atomic::AtomicU64>,
105 /// file → [`RefCommit`] its reference locations were last committed
106 /// from. Exact while the text is pointer-equal and the commit either
107 /// fully resolved every name it referenced or was stamped at the current
108 /// [`Self::index_generation`] — a later symbol add elsewhere can resolve
109 /// a reference this file's analysis left unresolved, even though this
110 /// file's own text never changed. Files absent here have never been
111 /// committed.
112 ref_committed: CommittedRefs,
113 /// file → source text its subtype-index class edges were last committed
114 /// from. Same freshness contract as `ref_committed`, but definitions
115 /// depend only on the file's own text, so a pointer-equal entry is
116 /// always exact (no cross-file drift).
117 defs_committed: CommittedTexts,
118 /// Memoized [`Self::indexed_references_to`] results. See
119 /// [`RefQueryCacheKey`] for the invalidation contract. Without this, a
120 /// repeat query against an unchanged candidate set still re-pays the
121 /// O(candidates) freshness scan on every call — cheap per file, but
122 /// measured at tens of MB / seconds of churn for a widely-referenced
123 /// symbol queried repeatedly (e.g. a host recomputing code-lens
124 /// reference counts on every request). Bounded by total cached
125 /// LOCATIONS (`ref_query_cache_locations`, capped at
126 /// `REF_QUERY_CACHE_LOCATION_CAP`), not entry count — a per-entry cap
127 /// would not bound memory here, since one entry's `Vec` scales with how
128 /// many times its symbol is referenced (a handful for a typical method,
129 /// thousands for a hot one like `Str::class`'s), so a fixed entry count
130 /// gives no fixed byte ceiling. Cleared wholesale on overflow, same
131 /// trade-off as the other simple caches in this module.
132 ref_query_cache: RefQueryCache,
133 /// Sum of `.len()` across every `ref_query_cache` entry, kept in
134 /// lockstep with it. See the field doc above.
135 ref_query_cache_locations: Arc<std::sync::atomic::AtomicUsize>,
136 /// Hits served from `ref_query_cache`. Diagnostic only — lets tests
137 /// assert a warm repeat skipped the freshness scan entirely, the same
138 /// way `ref_index_lock_count` proves a bounded posting lookup.
139 ref_query_cache_hits: Arc<std::sync::atomic::AtomicU64>,
140 /// Memoized [`Self::indexed_subtype_classes`] results. Same rationale
141 /// and invalidation contract as `ref_query_cache`:
142 /// `commit_defs_for_matching`'s freshness pass costs O(candidates) on
143 /// every call regardless of outcome, so a repeat query (e.g. resolving
144 /// a protected/static method's reference scope on every code-lens
145 /// refresh) would otherwise re-pay it every time. Bounded by total
146 /// cached sites (`subtype_query_cache_sites`, capped at
147 /// `SUBTYPE_QUERY_CACHE_SITE_CAP`), not entry count, for the same
148 /// reason `ref_query_cache` isn't entry-count-capped.
149 subtype_query_cache: SubtypeQueryCache,
150 /// Sum of `.len()` across every `subtype_query_cache` entry.
151 subtype_query_cache_sites: Arc<std::sync::atomic::AtomicUsize>,
152 /// Hits served from `subtype_query_cache`. Diagnostic only.
153 subtype_query_cache_hits: Arc<std::sync::atomic::AtomicU64>,
154}
155
156/// Cache key for [`AnalysisSession::indexed_references_to`]'s memoization.
157///
158/// `generation`'s revision half is salsa's text revision, not
159/// [`AnalysisSession::index_generation`]: a body-only edit never bumps the
160/// workspace generation (by design — see `bump_workspace_revision`'s doc
161/// comment) but can still move, add, or remove a reference location, so
162/// keying on the coarser generation would serve stale locations after such
163/// an edit.
164/// `files_hash` guards against a caller narrowing/widening the candidate
165/// scope between calls for the same symbol at the same revision (e.g. a
166/// different reference-scope plan) — a coincidental hash collision would
167/// only cause a wrong cache HIT, so this hashes full content, not just
168/// length/pointers.
169///
170/// `generation` also carries the subtype-edge epoch (see
171/// [`AnalysisSession::query_cache_generation`]): a member query's hierarchy
172/// fan-out reads the subtype index, which another query's defs commit can
173/// grow without moving the text revision — the epoch keeps such an entry
174/// from being served after its fan-out went stale.
175#[derive(PartialEq, Eq, Hash)]
176struct RefQueryCacheKey {
177 symbol: String,
178 include_declaration: bool,
179 generation: (salsa::Revision, u64),
180 files_hash: u64,
181}
182
183/// Cap on `ref_query_cache`'s total cached reference-location count (summed
184/// across every entry), not entry count — see the field doc on
185/// `ref_query_cache`. Each location is `(Arc<str>, Range)`, ~24 bytes plus a
186/// refcount bump on an already-allocated path string (no new string data),
187/// so 200k locations is on the order of a few MB — a small, fixed ceiling
188/// regardless of how skewed the query distribution is (many small entries or
189/// a few huge ones for hot symbols cost the same worst case).
190const REF_QUERY_CACHE_LOCATION_CAP: usize = 200_000;
191
192/// Memoized [`AnalysisSession::indexed_references_to`] results. See
193/// [`RefQueryCacheKey`] for the invalidation contract.
194type RefQueryCache =
195 Arc<RwLock<RevisionedMap<RefQueryCacheKey, Arc<Vec<(Arc<str>, crate::Range)>>>>>;
196
197/// A memo map whose keys embed the generation — `(text revision,
198/// subtype-edge epoch)`, see [`AnalysisSession::query_cache_generation`] —
199/// they were computed at. Once the generation moves, old keys can never be
200/// looked up again, so the first insert at a newer generation drops them
201/// wholesale — without this, dead keys (heap `String`s) accumulate until
202/// the value-cap overflow clear.
203struct RevisionedMap<K, V> {
204 generation: Option<(salsa::Revision, u64)>,
205 map: HashMap<K, V>,
206}
207
208impl<K, V> Default for RevisionedMap<K, V> {
209 fn default() -> Self {
210 Self {
211 generation: None,
212 map: HashMap::default(),
213 }
214 }
215}
216
217impl<K: std::hash::Hash + Eq, V> RevisionedMap<K, V> {
218 fn get(&self, key: &K) -> Option<&V> {
219 self.map.get(key)
220 }
221
222 /// Prepare for an insert keyed at `generation`. Rolls the map forward
223 /// (dropping the dead generation) when `generation` is newer than the
224 /// resident one, running `on_clear` so the caller can zero its
225 /// lockstep size counter. Returns `false` when `generation` is older —
226 /// such a key can never hit again, so the caller should skip caching.
227 /// Both components are monotonic, so lexicographic order is sound.
228 fn advance_to(&mut self, generation: (salsa::Revision, u64), on_clear: impl FnOnce()) -> bool {
229 match self.generation {
230 Some(g) if g == generation => true,
231 Some(g) if g > generation => false,
232 _ => {
233 self.map.clear();
234 self.generation = Some(generation);
235 on_clear();
236 true
237 }
238 }
239 }
240}
241
242/// Cache key for [`AnalysisSession::indexed_subtype_classes`]'s memoization.
243/// Same invalidation contract as [`RefQueryCacheKey`]. `class_fqn` is
244/// lowercased and leading-`\`-stripped on entry (PHP class names are
245/// case-insensitive) so two callers spelling the same class differently
246/// still share a cache entry.
247#[derive(PartialEq, Eq, Hash)]
248struct SubtypeQueryCacheKey {
249 class_fqn: String,
250 include_trait_users: bool,
251 generation: (salsa::Revision, u64),
252 files_hash: u64,
253}
254
255/// Cap on `subtype_query_cache`'s total cached site count, not entry count
256/// — same rationale as [`REF_QUERY_CACHE_LOCATION_CAP`]. A `SubtypeClassSite`
257/// is ~80 bytes (two `Arc<str>`, an enum, a bool, a `Range`), so 50k sites
258/// is on the order of a few MB.
259const SUBTYPE_QUERY_CACHE_SITE_CAP: usize = 50_000;
260
261/// Memoized [`AnalysisSession::indexed_subtype_classes`] results. See
262/// [`SubtypeQueryCacheKey`] for the invalidation contract.
263type SubtypeQueryCache =
264 Arc<RwLock<RevisionedMap<SubtypeQueryCacheKey, Arc<Vec<SubtypeClassSite>>>>>;
265
266/// Stable content hash of a candidate-file list, order-sensitive. Callers
267/// that rebuild the list identically each time (the common case — the same
268/// scope-narrowing query re-run against unchanged state) still hash equal;
269/// a genuinely different list (different content OR order) safely misses
270/// rather than risking a wrong hit.
271fn hash_files(files: &[Arc<str>]) -> u64 {
272 use std::hash::{Hash, Hasher};
273 let mut hasher = rustc_hash::FxHasher::default();
274 files.len().hash(&mut hasher);
275 for f in files {
276 f.hash(&mut hasher);
277 }
278 hasher.finish()
279}
280
281/// FQCN → optional resolver-mapped path. See the field doc on
282/// `AnalysisSession::unresolvable_fqcns`.
283type UnresolvableCache = Arc<RwLock<HashMap<Arc<str>, Option<Arc<str>>>>>;
284
285/// Warm-up skip set keyed by file path. See the field doc on
286/// `AnalysisSession::prepared_files`.
287type PreparedFilesCache = Arc<RwLock<HashMap<Arc<str>, (Arc<str>, u64)>>>;
288
289/// Parsed inline suppressions keyed by file path and source text.
290type SuppressionMapCache =
291 Arc<RwLock<HashMap<Arc<str>, (Arc<str>, Arc<crate::suppression::SuppressionMap>)>>>;
292
293/// file → text a per-file index commit was computed from. See the field docs
294/// on `AnalysisSession::ref_committed` / `defs_committed`.
295type CommittedTexts = Arc<RwLock<HashMap<Arc<str>, Arc<str>>>>;
296
297/// A staged [`AnalysisCache`] write for one file's postings, prepared in the
298/// parallel analysis phase and applied during the serial index commit. See
299/// `AnalysisSession::stage_ref_cache_put`.
300pub(crate) struct RefCachePut {
301 content_hash: String,
302 surface_hash: String,
303 ref_locs: Arc<[crate::cache::CachedRefLoc]>,
304}
305
306/// One file's reference-posting commit. See `AnalysisSession::ref_committed`.
307pub(crate) struct RefCommit {
308 /// Source text the postings were computed from (pointer identity; a
309 /// text write self-invalidates).
310 text: Arc<str>,
311 /// Weak handle on the analyze memo — pointer-identical output means
312 /// identical postings, so sweeps can skip the index rewrite. The upgrade
313 /// guards against ABA on evicted memos.
314 out: std::sync::Weak<crate::db::AnalyzeOutput>,
315 /// Workspace generation whose resolution environment the postings
316 /// reflect, captured *before* the analysis snapshot.
317 generation: u64,
318 /// The analysis resolved every workspace-level name it referenced, so no
319 /// later symbol add can change the postings and the commit survives
320 /// generation bumps. FQCN shadowing and unqualified-call fallback
321 /// switches remain the reanalyze_dependents flow's job, as before.
322 resolved: bool,
323 /// Whether this commit came from this session's own `analyze_file` pass
324 /// (`out: Some(..)`) rather than a disk-cache replay (`out: None`, from
325 /// `warm_start_files`). A live analysis's postings are guaranteed
326 /// consistent with a fresh textual scan of the same text — a replayed
327 /// commit's are only as trustworthy as the cache entry, so it always
328 /// re-verifies via full re-analysis instead of the cheaper gate.
329 live_analyzed: bool,
330}
331
332/// file → [`RefCommit`] map shared across session clones.
333type CommittedRefs = Arc<RwLock<HashMap<Arc<str>, RefCommit>>>;
334
335/// Cap on the negative-resolution cache. Sized to accommodate a large
336/// workspace's worth of genuinely-missing references without unbounded
337/// growth. On overflow the cache is cleared; the cost is a few extra
338/// resolver calls until it re-fills.
339const UNRESOLVABLE_CACHE_CAP: usize = 10_000;
340
341/// RAII scope from [`AnalysisSession::defer_revision_bumps`]. The last scope
342/// to close performs the one owed `bump_workspace_revision` (taking the db
343/// write lock), so generation-stamped freshness marks made after the scope
344/// see the post-load generation.
345pub(crate) struct DeferredRevisionBumps<'s> {
346 session: &'s AnalysisSession,
347 depth: Arc<std::sync::atomic::AtomicUsize>,
348 pending: Arc<std::sync::atomic::AtomicBool>,
349}
350
351impl Drop for DeferredRevisionBumps<'_> {
352 fn drop(&mut self) {
353 use std::sync::atomic::Ordering;
354 if self.depth.fetch_sub(1, Ordering::SeqCst) == 1
355 && self.pending.swap(false, Ordering::SeqCst)
356 {
357 self.session.db.salsa.write().bump_workspace_revision();
358 }
359 }
360}
361
362impl AnalysisSession {
363 /// Create a session targeting the given PHP language version.
364 pub fn new(php_version: PhpVersion) -> Self {
365 let db = Arc::new(AnalyzerDb::new());
366 db.salsa
367 .write()
368 .set_php_version(Arc::from(php_version.to_string().as_str()));
369 Self {
370 db,
371 cache: None,
372 psr4: None,
373 resolver: None,
374 php_version,
375 user_stub_files: Vec::new(),
376 user_stub_dirs: Vec::new(),
377 stale_defined_symbols: Arc::new(RwLock::new(HashMap::default())),
378 last_ingested_symbols: Arc::new(RwLock::new(HashMap::default())),
379 unresolvable_fqcns: Arc::new(RwLock::new(HashMap::default())),
380 source_provider: Arc::new(crate::FsSourceProvider),
381 pending_eager_function_files: Arc::new(parking_lot::Mutex::new(Some(Vec::new()))),
382 prepared_files: Arc::new(RwLock::new(HashMap::default())),
383 suppression_maps: Arc::new(RwLock::new(HashMap::default())),
384 prepare_generation: Arc::new(std::sync::atomic::AtomicU64::new(0)),
385 ref_committed: Arc::new(RwLock::new(HashMap::default())),
386 defs_committed: Arc::new(RwLock::new(HashMap::default())),
387 ref_query_cache: Arc::new(RwLock::new(RevisionedMap::default())),
388 ref_query_cache_locations: Arc::new(std::sync::atomic::AtomicUsize::new(0)),
389 ref_query_cache_hits: Arc::new(std::sync::atomic::AtomicU64::new(0)),
390 subtype_query_cache: Arc::new(RwLock::new(RevisionedMap::default())),
391 subtype_query_cache_sites: Arc::new(std::sync::atomic::AtomicUsize::new(0)),
392 subtype_query_cache_hits: Arc::new(std::sync::atomic::AtomicU64::new(0)),
393 }
394 }
395
396 /// Hits served from [`Self::indexed_references_to`]'s memoization cache.
397 /// Diagnostic only — see the field doc on `ref_query_cache_hits`.
398 pub fn ref_query_cache_hits(&self) -> u64 {
399 self.ref_query_cache_hits
400 .load(std::sync::atomic::Ordering::Relaxed)
401 }
402
403 /// Total cached reference-location count across `ref_query_cache`.
404 /// Diagnostic only — lets tests/hosts assert the cache stays under its
405 /// byte-proportional cap rather than trusting entry count alone.
406 pub fn ref_query_cache_locations(&self) -> usize {
407 self.ref_query_cache_locations
408 .load(std::sync::atomic::Ordering::Relaxed)
409 }
410
411 /// Hits served from [`Self::indexed_subtype_classes`]'s memoization
412 /// cache. Diagnostic only.
413 pub fn subtype_query_cache_hits(&self) -> u64 {
414 self.subtype_query_cache_hits
415 .load(std::sync::atomic::Ordering::Relaxed)
416 }
417
418 /// Total cached site count across `subtype_query_cache`. Diagnostic
419 /// only — same purpose as `ref_query_cache_locations`.
420 pub fn subtype_query_cache_sites(&self) -> usize {
421 self.subtype_query_cache_sites
422 .load(std::sync::atomic::Ordering::Relaxed)
423 }
424
425 /// Times the reference index has been locked on this session's db.
426 pub fn ref_index_lock_count(&self) -> u64 {
427 self.db.salsa.read().ref_index_lock_count()
428 }
429
430 /// Open a scope during which `bump_workspace_revision` calls coalesce:
431 /// a pass that lazy-loads N classes (Phase-1 warm-up, bulk registration)
432 /// performs one salsa input write when the last scope closes instead of
433 /// one per class — each such write cancels every in-flight salsa reader,
434 /// so this is what keeps a warm-up loop from restarting concurrent
435 /// queries N times. Scopes nest; the flush must not run while a db
436 /// guard is held (it takes the write lock).
437 pub(crate) fn defer_revision_bumps(&self) -> DeferredRevisionBumps<'_> {
438 let (depth, pending) = self.db.salsa.read().revision_bump_deferral_handles();
439 depth.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
440 DeferredRevisionBumps {
441 session: self,
442 depth,
443 pending,
444 }
445 }
446
447 /// Coverage/size counters for the class-mention gate index (host
448 /// metrics and memory-bound checks).
449 pub fn class_mention_stats(&self) -> crate::db::ClassMentionStats {
450 self.db.salsa.read().class_mention_stats()
451 }
452
453 /// Which of `files` currently mention `class_name` as a whole
454 /// identifier (case-insensitive) — the same persistent, incrementally-
455 /// maintained mechanism [`Self::indexed_references_to`]'s own gate uses
456 /// internally (see `db::class_mention_index`'s doc comment), exposed so
457 /// a host doesn't need to re-implement an equivalent from-scratch text
458 /// scan for its own narrowing (e.g. a reachability pre-filter ahead of
459 /// a references/code-lens query). A file already scanned against a
460 /// universe that included `class_name` answers via an O(log n) lookup
461 /// with no text pass at all; only a never-scanned or since-edited file
462 /// pays a scan, and that scan is recorded for every other name already
463 /// in the universe too, not just this one.
464 ///
465 /// **Scope**: the universe is seeded from *declared class-like names*
466 /// (classes/interfaces/traits/enums) — the same population mir's own
467 /// indexing already does as a side effect — but a `class_name` outside
468 /// that set is not a reason to skip narrowing: it's admitted verbatim
469 /// on the spot (see [`Self::files_mentioning_any`]) and answered by a
470 /// real scan, same as any other needle.
471 pub fn files_mentioning_class(&self, files: &[Arc<str>], class_name: &str) -> Vec<Arc<str>> {
472 self.files_mentioning_any(files, &[class_name])
473 }
474
475 /// Which of `files` currently mention ANY of `needles` as a whole
476 /// identifier (case-insensitive) — the multi-needle form of
477 /// [`Self::files_mentioning_class`], for a caller resolving several
478 /// candidate names at once (e.g. an owner FQN plus its subtype
479 /// closure). Every needle is admitted into the shared universe
480 /// verbatim (no short-name stripping) before querying, so this call's
481 /// answer is never conservative on account of an unknown needle — a
482 /// file only falls back to a raw scan when it was scanned before all
483 /// of `needles` existed in the universe and hasn't been touched since;
484 /// that one scan then answers every needle in the universe at once,
485 /// not just this call's.
486 pub fn files_mentioning_any(&self, files: &[Arc<str>], needles: &[&str]) -> Vec<Arc<str>> {
487 use rayon::prelude::*;
488
489 if needles.is_empty() {
490 return files.to_vec();
491 }
492 let db = self.snapshot_db();
493 db.add_literal_mention_names(needles.iter().copied());
494 // Just admitted every needle above, so `prepare_class_mention_query`
495 // only fails here while the universe itself is somehow still empty
496 // (unreachable: admission just grew it) — kept as a defensive
497 // fallback, not a reachable branch.
498 let queries: Vec<_> = needles
499 .iter()
500 .filter_map(|n| db.prepare_class_mention_query(n))
501 .collect();
502 if queries.is_empty() {
503 return files.to_vec();
504 }
505 let Some(scanner) = db.class_mention_scanner() else {
506 return files.to_vec();
507 };
508
509 files
510 .par_iter()
511 .map_with(db, |db, f| -> Option<Arc<str>> {
512 let sf = db.lookup_source_file(f.as_ref())?;
513 let text = sf.text(&*db as &dyn MirDatabase).clone();
514 for q in &queries {
515 match db.class_mention_answer(f.as_ref(), q, &text) {
516 Some(true) => return Some(f.clone()),
517 Some(false) => continue,
518 None => {
519 let names = scanner.scan(text.as_ref());
520 let hit = queries
521 .iter()
522 .any(|q2| names.binary_search(&q2.name).is_ok());
523 db.set_file_class_mentions(f, &text, scanner.epoch(), names);
524 return hit.then(|| f.clone());
525 }
526 }
527 }
528 None
529 })
530 .flatten()
531 .collect()
532 }
533
534 /// Whether `file`'s reference postings are exact for `current_text` at
535 /// `current_gen`: text pointer-equal, and the commit either resolved
536 /// every name (immune to workspace growth) or was stamped at that
537 /// generation — catches a file analyzed before a class it references
538 /// was registered elsewhere, which would otherwise look fresh forever.
539 pub(crate) fn is_ref_committed(
540 &self,
541 file: &str,
542 current_text: &Arc<str>,
543 current_gen: u64,
544 ) -> bool {
545 self.ref_committed.read().get(file).is_some_and(|c| {
546 Arc::ptr_eq(&c.text, current_text) && (c.resolved || c.generation == current_gen)
547 })
548 }
549
550 /// Whether `file` has a *live-analyzed* reference commit recorded against
551 /// exactly `current_text` — i.e. it's only stale by generation (an
552 /// unresolved-name commit racing a workspace-growth bump), not because
553 /// its text changed or because it was seeded by an unverified disk-cache
554 /// replay. Such a commit is still eligible for the mention/needle gate:
555 /// the current text is exactly what this session's own analysis already
556 /// scanned, so a needle miss is just as conclusive as for a
557 /// never-committed file. A replayed commit (`live_analyzed: false`)
558 /// never qualifies here, regardless of text match — its postings are
559 /// only as trustworthy as the cache entry, so it always falls through to
560 /// unconditional re-analysis. Same for a genuinely edited file (text
561 /// differs): the old commit's postings are for different text and must
562 /// be replaced regardless of what the new text mentions.
563 pub(crate) fn ref_commit_stale_by_generation_only(
564 &self,
565 file: &str,
566 current_text: &Arc<str>,
567 ) -> bool {
568 self.ref_committed
569 .read()
570 .get(file)
571 .is_some_and(|c| c.live_analyzed && Arc::ptr_eq(&c.text, current_text))
572 }
573
574 /// Whether `file`'s stored postings came from exactly this
575 /// (text, output) pair — generation aside. Pointer-identical output
576 /// means identical postings (salsa backdates equal results to the same
577 /// Arc), so callers skip the index rewrite and only re-stamp the mark.
578 pub(crate) fn ref_commit_is_current(
579 &self,
580 file: &str,
581 current_text: &Arc<str>,
582 out: &Arc<crate::db::AnalyzeOutput>,
583 ) -> bool {
584 self.ref_committed.read().get(file).is_some_and(|c| {
585 Arc::ptr_eq(&c.text, current_text)
586 && c.out.upgrade().is_some_and(|prev| Arc::ptr_eq(&prev, out))
587 })
588 }
589
590 /// Record a commit computed against the workspace state at `generation`
591 /// — captured by the caller *before* its analysis snapshot, so a file
592 /// add racing the analysis leaves the commit stale (re-verified on the
593 /// next query) rather than wrongly fresh. `resolved` must come from the
594 /// producing analysis' own issue set
595 /// ([`crate::db::issues_have_unresolved_names`]); pass `false` when
596 /// unknown — the gen-guarded safe direction.
597 pub(crate) fn mark_ref_committed(
598 &self,
599 file: &Arc<str>,
600 text: &Arc<str>,
601 out: Option<&Arc<crate::db::AnalyzeOutput>>,
602 generation: u64,
603 resolved: bool,
604 ) {
605 let commit = RefCommit {
606 text: text.clone(),
607 out: out.map(Arc::downgrade).unwrap_or_default(),
608 generation,
609 resolved,
610 live_analyzed: out.is_some(),
611 };
612 self.ref_committed.write().insert(file.clone(), commit);
613 }
614
615 pub(crate) fn forget_ref_committed(&self, file: &str) {
616 self.ref_committed.write().remove(file);
617 }
618
619 /// Stage a disk-cache write for `file`'s postings, computed in the
620 /// parallel analysis phase (needs a live db snapshot for the memoized
621 /// parse). `None` when no cache is attached or the stored entry already
622 /// matches this content — batch-written entries are never clobbered.
623 /// The caller applies the result via [`Self::apply_ref_cache_put`] in
624 /// its serial commit, alongside the in-memory index commit.
625 pub(crate) fn stage_ref_cache_put(
626 &self,
627 db: &dyn crate::db::MirDatabase,
628 sf: crate::db::SourceFile,
629 file: &str,
630 text: &Arc<str>,
631 out: &Arc<crate::db::AnalyzeOutput>,
632 ) -> Option<RefCachePut> {
633 let cache = self.cache.as_deref()?;
634 let content_hash = crate::cache::hash_content(text);
635 if cache.is_valid(file, &content_hash) {
636 return None;
637 }
638 let parsed = crate::db::parse_file(db, sf);
639 let surface_hash = crate::cache::surface_fingerprint(text, &parsed.0.program);
640 let ref_locs: Arc<[crate::cache::CachedRefLoc]> = out
641 .ref_locs
642 .iter()
643 .map(|r| (Arc::clone(&r.symbol_key), r.line, r.col_start, r.col_end))
644 .collect();
645 Some(RefCachePut {
646 content_hash,
647 surface_hash,
648 ref_locs,
649 })
650 }
651
652 pub(crate) fn apply_ref_cache_put(
653 &self,
654 file: &str,
655 out: &Arc<crate::db::AnalyzeOutput>,
656 put: RefCachePut,
657 ) {
658 if let Some(cache) = self.cache.as_deref() {
659 cache.put(
660 file,
661 put.content_hash,
662 put.surface_hash,
663 out.issues.clone(),
664 put.ref_locs,
665 );
666 }
667 }
668
669 /// Persist the attached [`AnalysisCache`] to disk. No-op without an
670 /// attached cache or when nothing changed since the last flush.
671 /// Reference postings committed by session sweeps and on-demand query
672 /// freshness passes reach disk only here — a host should call this after
673 /// its warm sweep completes and on shutdown so the next launch's
674 /// [`Self::warm_start_files`] finds them.
675 pub fn flush_analysis_cache(&self) {
676 if let Some(cache) = &self.cache {
677 cache.flush();
678 }
679 }
680
681 /// Whether the workspace symbol index singleton is populated (seeded by
682 /// [`Self::warm_start_files`] or built by `index_batch`) — symbol lookups
683 /// answer from the O(1) map instead of the tracked O(all-files) walk.
684 pub fn workspace_symbol_index_ready(&self) -> bool {
685 self.db
686 .salsa
687 .read()
688 .workspace_symbol_index_singleton()
689 .is_some()
690 }
691
692 /// Executions of the tracked O(all-files) `workspace_symbol_index` walk
693 /// (diagnostic; a warm-started session should keep this at zero).
694 pub fn workspace_index_walks(&self) -> u64 {
695 self.db.salsa.read().workspace_index_walks()
696 }
697
698 /// Whether `file`'s subtype-index class edges were committed from exactly
699 /// `current_text`.
700 pub(crate) fn is_defs_committed(&self, file: &str, current_text: &Arc<str>) -> bool {
701 self.defs_committed
702 .read()
703 .get(file)
704 .is_some_and(|t| Arc::ptr_eq(t, current_text))
705 }
706
707 pub(crate) fn mark_defs_committed(&self, file: &Arc<str>, text: &Arc<str>) {
708 self.defs_committed
709 .write()
710 .insert(file.clone(), text.clone());
711 }
712
713 pub(crate) fn forget_defs_committed(&self, file: &str) {
714 self.defs_committed.write().remove(file);
715 }
716
717 /// Every file with a defs commit on record, regardless of staleness.
718 pub(crate) fn defs_committed_keys(&self) -> Vec<Arc<str>> {
719 self.defs_committed.read().keys().cloned().collect()
720 }
721
722 /// Every file with a reference commit on record, regardless of
723 /// staleness. Files absent here have no reference postings at all.
724 pub(crate) fn ref_committed_keys(&self) -> Vec<Arc<str>> {
725 self.ref_committed.read().keys().cloned().collect()
726 }
727
728 /// Swap in a custom [`crate::SourceProvider`]. LSPs install a VFS-backed
729 /// provider here so the analyzer reads from unsaved editor buffers
730 /// instead of disk.
731 pub fn with_source_provider(mut self, provider: Arc<dyn crate::SourceProvider>) -> Self {
732 self.source_provider = provider;
733 self
734 }
735
736 /// Attach a pre-built [`AnalysisCache`] (the body-analysis issue cache) and
737 /// open a sibling definition [`StubSlice`] cache under the same root, so
738 /// callers using this builder get the same speedup as `with_cache_dir`.
739 ///
740 /// Rebuilds the shared database to attach the definition cache — call
741 /// **before** any file is ingested. A debug assertion catches misuse.
742 ///
743 /// [`StubSlice`]: mir_codebase::definitions::StubSlice
744 pub fn with_cache(mut self, cache: Arc<AnalysisCache>) -> Self {
745 debug_assert_eq!(
746 self.db.source_file_count(),
747 0,
748 "AnalysisSession::with_cache must be called before any file is ingested"
749 );
750 let dir = cache.cache_dir().to_path_buf();
751 self.db = Arc::new(AnalyzerDb::new().with_cache_dir(&dir));
752 self.db
753 .salsa
754 .write()
755 .set_php_version(Arc::from(self.php_version.to_string().as_str()));
756 self.cache = Some(cache);
757 self
758 }
759
760 /// Convenience: open a disk-backed cache at `cache_dir` and attach it.
761 ///
762 /// Attaches both the body-analysis issue cache ([`AnalysisCache`]) and the
763 /// definition [`StubSlice`] cache to the shared database. Builds a fresh
764 /// [`AnalyzerDb`] internally — call **before** any file is ingested. A
765 /// debug assertion catches misuse.
766 ///
767 /// [`StubSlice`]: mir_codebase::definitions::StubSlice
768 pub fn with_cache_dir(mut self, cache_dir: &std::path::Path) -> Self {
769 debug_assert_eq!(
770 self.db.source_file_count(),
771 0,
772 "AnalysisSession::with_cache_dir must be called before any file is ingested"
773 );
774 self.db = Arc::new(AnalyzerDb::new().with_cache_dir(cache_dir));
775 self.db
776 .salsa
777 .write()
778 .set_php_version(Arc::from(self.php_version.to_string().as_str()));
779 // Fold the user-stub fingerprint into the cache epoch. `with_user_stubs`
780 // must run before this for it to be picked up (it does in `build_session`);
781 // sessions without user stubs get 0, which is correct.
782 let user_stub_fp =
783 crate::stubs::user_stub_fingerprint(&self.user_stub_files, &self.user_stub_dirs);
784 self.cache = Some(Arc::new(AnalysisCache::open(
785 cache_dir,
786 self.php_version.cache_byte(),
787 user_stub_fp,
788 )));
789 self
790 }
791
792 /// Attach a Composer autoload map (PSR-4, PSR-0, classmap, files).
793 /// Sets the same map as the active [`crate::ClassResolver`] so
794 /// [`Self::load_class`] works out of the box.
795 pub fn with_psr4(mut self, map: Arc<Psr4Map>) -> Self {
796 let user_resolver: Arc<dyn crate::ClassResolver> = map.clone();
797 // Wrap with stub awareness so `find_class_like` / `resolve_fqcn_to_path`
798 // can map built-in PHP class FQCNs (`ArrayObject`, `Exception`, …)
799 // to their stub virtual paths.
800 let resolver: Arc<dyn crate::ClassResolver> = Arc::new(crate::ChainedClassResolver::new(
801 user_resolver,
802 Arc::new(crate::StubClassResolver),
803 ));
804 self.psr4 = Some(map.clone());
805 self.resolver = Some(resolver.clone());
806 // Mirror into MirDbStorage so salsa-tracked resolver queries
807 // (`db::resolve_fqcn_to_path`) see the same resolver and are
808 // invalidated on swap.
809 self.db.salsa.write().set_resolver(Some(resolver));
810 // Register vendor autoload.files for lazy loading. They define global
811 // functions and constants that the class resolver cannot discover.
812 // `ensure_vendor_eager_functions` will index them on first analysis call.
813 *self.pending_eager_function_files.lock() = Some(map.vendor_eager_files());
814 self
815 }
816
817 /// Attach a generic class resolver for projects that don't use Composer
818 /// (WordPress, Drupal, custom autoloaders, workspace-walk indexes).
819 /// Replaces any previously-set Composer-backed resolver. Automatically
820 /// wrapped with stub awareness so PHP built-ins remain resolvable.
821 pub fn with_class_resolver(mut self, resolver: Arc<dyn crate::ClassResolver>) -> Self {
822 let wrapped: Arc<dyn crate::ClassResolver> = Arc::new(crate::ChainedClassResolver::new(
823 resolver,
824 Arc::new(crate::StubClassResolver),
825 ));
826 self.db.salsa.write().set_resolver(Some(wrapped.clone()));
827 self.resolver = Some(wrapped);
828 self
829 }
830
831 pub fn with_user_stubs(mut self, files: Vec<PathBuf>, dirs: Vec<PathBuf>) -> Self {
832 self.user_stub_files = files;
833 self.user_stub_dirs = dirs;
834 self
835 }
836
837 pub fn php_version(&self) -> PhpVersion {
838 self.php_version
839 }
840
841 pub fn cache(&self) -> Option<&AnalysisCache> {
842 self.cache.as_deref()
843 }
844
845 pub fn psr4(&self) -> Option<&Psr4Map> {
846 self.psr4.as_deref()
847 }
848}
849
850mod incremental;
851mod ingest;
852mod loading;
853mod queries;
854mod stubs;
855
856pub use queries::SubtypeClassSite;
857
858/// Compute the full set of files `file` depends on by projecting structural
859/// and body-reference symbols through the workspace symbol index. Self-edges
860/// are excluded. Used to persist the disk cache's reverse-dep graph.
861fn file_outgoing_dependencies(
862 db: &dyn MirDatabase,
863 file: &str,
864 include_body_ref_edges: bool,
865) -> HashSet<String> {
866 let mut targets: HashSet<String> = HashSet::default();
867
868 if let Some(sf) = db.lookup_source_file(file) {
869 for symbol in crate::db::file_structural_symbols(db, sf).iter() {
870 let lookup = crate::defining_file_lookup_key(symbol);
871 if let Some(defining_file) = db.symbol_defining_file(lookup) {
872 if defining_file.as_ref() != file {
873 targets.insert(defining_file.as_ref().to_string());
874 }
875 }
876 }
877 }
878
879 if !include_body_ref_edges {
880 return targets;
881 }
882
883 // Bare-FQN references recorded during body analysis (new \Foo(),
884 // \Foo::method(), \foo()) that do not appear in use-import statements.
885 for symbol_key in db.file_referenced_symbols(file) {
886 let lookup = crate::defining_file_lookup_key(&symbol_key);
887 if let Some(defining_file) = db.symbol_defining_file(lookup) {
888 if defining_file.as_ref() != file {
889 targets.insert(defining_file.as_ref().to_string());
890 }
891 }
892 }
893
894 targets
895}
896
897/// AST visitor that collects class FQCN references for PSR-4 preloading.
898/// Captures identifiers from `new X`, static calls / property / constant
899/// access, type hints, `instanceof`, and `@param`/`@return`/`@var`/`@extends`/
900/// `@implements` docblock annotations. Does *not* normalize via PSR-4 /
901/// imports — callers run the raw string through `resolve_name`.
902fn collect_class_refs_from_ast(program: &php_ast::owned::Program) -> Vec<String> {
903 use php_ast::ast::BinaryOp;
904 use php_ast::owned::visitor::{
905 walk_owned_class_member, walk_owned_expr, walk_owned_program, walk_owned_stmt, OwnedVisitor,
906 };
907 use php_ast::owned::{ClassMemberKind, ExprKind};
908 use std::ops::ControlFlow;
909
910 fn owned_name_str(name: &php_ast::owned::Name) -> String {
911 let joined: String = name
912 .parts
913 .iter()
914 .map(|p| p.as_ref())
915 .collect::<Vec<&str>>()
916 .join("\\");
917 if name.kind == php_ast::ast::NameKind::FullyQualified {
918 format!("\\{joined}")
919 } else {
920 joined
921 }
922 }
923
924 /// Recursively collect all `TNamedObject` FQCNs from a mir type, including
925 /// those nested inside generic type parameters (e.g. `Collection<Item>`).
926 fn collect_from_type(ty: &mir_types::Type, out: &mut std::collections::HashSet<String>) {
927 for atomic in ty.types.iter() {
928 if let mir_types::Atomic::TNamedObject { fqcn, type_params } = atomic {
929 out.insert(fqcn.as_ref().to_string());
930 for tp in type_params.iter() {
931 collect_from_type(tp, out);
932 }
933 }
934 }
935 }
936
937 /// Parse a docblock and collect class names from `@param`, `@return`,
938 /// `@var`, `@extends`, and `@implements` annotations.
939 fn collect_from_docblock(text: &str, out: &mut std::collections::HashSet<String>) {
940 let parsed = crate::parser::DocblockParser::parse(text);
941 for (_, ty) in &parsed.params {
942 collect_from_type(ty, out);
943 }
944 if let Some(ret) = &parsed.return_type {
945 collect_from_type(ret, out);
946 }
947 if let Some(var) = &parsed.var_type {
948 collect_from_type(var, out);
949 }
950 for ext in &parsed.extends {
951 collect_from_type(ext, out);
952 }
953 for impl_ty in &parsed.implements {
954 collect_from_type(impl_ty, out);
955 }
956 }
957
958 struct V {
959 names: std::collections::HashSet<String>,
960 }
961 impl OwnedVisitor for V {
962 fn visit_stmt(&mut self, stmt: &php_ast::owned::Stmt) -> ControlFlow<()> {
963 if let Some(doc) = stmt.leading_doc_comment() {
964 collect_from_docblock(&doc.text, &mut self.names);
965 }
966 walk_owned_stmt(self, stmt)
967 }
968
969 fn visit_class_member(&mut self, member: &php_ast::owned::ClassMember) -> ControlFlow<()> {
970 match &member.kind {
971 ClassMemberKind::Method(m) => {
972 if let Some(doc) = &m.doc_comment {
973 collect_from_docblock(&doc.text, &mut self.names);
974 }
975 }
976 ClassMemberKind::Property(p) => {
977 if let Some(doc) = &p.doc_comment {
978 collect_from_docblock(&doc.text, &mut self.names);
979 }
980 }
981 _ => {}
982 }
983 walk_owned_class_member(self, member)
984 }
985
986 fn visit_expr(&mut self, expr: &php_ast::owned::Expr) -> ControlFlow<()> {
987 match &expr.kind {
988 ExprKind::New(n) => {
989 if let ExprKind::Identifier(name) = &n.class.kind {
990 self.names.insert(name.as_ref().to_string());
991 }
992 }
993 ExprKind::StaticMethodCall(c) => {
994 if let ExprKind::Identifier(name) = &c.class.kind {
995 self.names.insert(name.as_ref().to_string());
996 }
997 }
998 ExprKind::StaticPropertyAccess(a) => {
999 if let ExprKind::Identifier(name) = &a.class.kind {
1000 self.names.insert(name.as_ref().to_string());
1001 }
1002 }
1003 ExprKind::ClassConstAccess(a) => {
1004 if let ExprKind::Identifier(name) = &a.class.kind {
1005 self.names.insert(name.as_ref().to_string());
1006 }
1007 }
1008 ExprKind::Binary(b) if b.op == BinaryOp::Instanceof => {
1009 if let ExprKind::Identifier(name) = &b.right.kind {
1010 self.names.insert(name.as_ref().to_string());
1011 }
1012 }
1013 _ => {}
1014 }
1015 walk_owned_expr(self, expr)
1016 }
1017
1018 // Walker routes every class/type-position Name here: type hints, catch types, extends/implements, trait use, attributes.
1019 fn visit_name(&mut self, name: &php_ast::owned::Name) -> ControlFlow<()> {
1020 let s = owned_name_str(name);
1021 if !s.is_empty() {
1022 self.names.insert(s);
1023 }
1024 ControlFlow::Continue(())
1025 }
1026 }
1027 let mut v = V {
1028 names: std::collections::HashSet::default(),
1029 };
1030 let _ = walk_owned_program(&mut v, program);
1031 v.names.into_iter().collect()
1032}