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