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    /// 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}
115
116/// FQCN → optional resolver-mapped path. See the field doc on
117/// `AnalysisSession::unresolvable_fqcns`.
118type UnresolvableCache = Arc<RwLock<HashMap<Arc<str>, Option<Arc<str>>>>>;
119
120/// Warm-up skip set keyed by file path. See the field doc on
121/// `AnalysisSession::prepared_files`.
122type PreparedFilesCache = Arc<RwLock<HashMap<Arc<str>, (Arc<str>, u64)>>>;
123
124/// file → text a per-file index commit was computed from. See the field docs
125/// on `AnalysisSession::ref_committed` / `defs_committed`.
126type CommittedTexts = Arc<RwLock<HashMap<Arc<str>, Arc<str>>>>;
127
128/// A staged [`AnalysisCache`] write for one file's postings, prepared in the
129/// parallel analysis phase and applied during the serial index commit. See
130/// `AnalysisSession::stage_ref_cache_put`.
131pub(crate) struct RefCachePut {
132    content_hash: String,
133    surface_hash: String,
134    ref_locs: Arc<[crate::cache::CachedRefLoc]>,
135}
136
137/// One file's reference-posting commit. See `AnalysisSession::ref_committed`.
138pub(crate) struct RefCommit {
139    /// Source text the postings were computed from (pointer identity; a
140    /// text write self-invalidates).
141    text: Arc<str>,
142    /// Weak handle on the analyze memo — pointer-identical output means
143    /// identical postings, so sweeps can skip the index rewrite. The upgrade
144    /// guards against ABA on evicted memos.
145    out: std::sync::Weak<crate::db::AnalyzeOutput>,
146    /// Workspace generation whose resolution environment the postings
147    /// reflect, captured *before* the analysis snapshot.
148    generation: u64,
149    /// The analysis resolved every workspace-level name it referenced, so no
150    /// later symbol add can change the postings and the commit survives
151    /// generation bumps. FQCN shadowing and unqualified-call fallback
152    /// switches remain the reanalyze_dependents flow's job, as before.
153    resolved: bool,
154}
155
156/// file → [`RefCommit`] map shared across session clones.
157type CommittedRefs = Arc<RwLock<HashMap<Arc<str>, RefCommit>>>;
158
159/// Cap on the negative-resolution cache. Sized to accommodate a large
160/// workspace's worth of genuinely-missing references without unbounded
161/// growth. On overflow the cache is cleared; the cost is a few extra
162/// resolver calls until it re-fills.
163const UNRESOLVABLE_CACHE_CAP: usize = 10_000;
164
165impl AnalysisSession {
166    /// Create a session targeting the given PHP language version.
167    pub fn new(php_version: PhpVersion) -> Self {
168        let db = Arc::new(AnalyzerDb::new());
169        db.salsa
170            .write()
171            .set_php_version(Arc::from(php_version.to_string().as_str()));
172        Self {
173            db,
174            cache: None,
175            psr4: None,
176            resolver: None,
177            php_version,
178            user_stub_files: Vec::new(),
179            user_stub_dirs: Vec::new(),
180            stale_defined_symbols: Arc::new(RwLock::new(HashMap::default())),
181            last_ingested_symbols: Arc::new(RwLock::new(HashMap::default())),
182            unresolvable_fqcns: Arc::new(RwLock::new(HashMap::default())),
183            source_provider: Arc::new(crate::FsSourceProvider),
184            pending_eager_function_files: Arc::new(parking_lot::Mutex::new(Some(Vec::new()))),
185            prepared_files: Arc::new(RwLock::new(HashMap::default())),
186            prepare_generation: Arc::new(std::sync::atomic::AtomicU64::new(0)),
187            ref_committed: Arc::new(RwLock::new(HashMap::default())),
188            defs_committed: Arc::new(RwLock::new(HashMap::default())),
189        }
190    }
191
192    /// Times the reference index has been locked on this session's db.
193    pub fn ref_index_lock_count(&self) -> u64 {
194        self.db.salsa.read().ref_index_lock_count()
195    }
196
197    /// Whether `file`'s reference postings are exact for `current_text` at
198    /// `current_gen`: text pointer-equal, and the commit either resolved
199    /// every name (immune to workspace growth) or was stamped at that
200    /// generation — catches a file analyzed before a class it references
201    /// was registered elsewhere, which would otherwise look fresh forever.
202    pub(crate) fn is_ref_committed(
203        &self,
204        file: &str,
205        current_text: &Arc<str>,
206        current_gen: u64,
207    ) -> bool {
208        self.ref_committed.read().get(file).is_some_and(|c| {
209            Arc::ptr_eq(&c.text, current_text) && (c.resolved || c.generation == current_gen)
210        })
211    }
212
213    /// Whether `file`'s stored postings came from exactly this
214    /// (text, output) pair — generation aside. Pointer-identical output
215    /// means identical postings (salsa backdates equal results to the same
216    /// Arc), so callers skip the index rewrite and only re-stamp the mark.
217    pub(crate) fn ref_commit_is_current(
218        &self,
219        file: &str,
220        current_text: &Arc<str>,
221        out: &Arc<crate::db::AnalyzeOutput>,
222    ) -> bool {
223        self.ref_committed.read().get(file).is_some_and(|c| {
224            Arc::ptr_eq(&c.text, current_text)
225                && c.out.upgrade().is_some_and(|prev| Arc::ptr_eq(&prev, out))
226        })
227    }
228
229    /// Record a commit computed against the workspace state at `generation`
230    /// — captured by the caller *before* its analysis snapshot, so a file
231    /// add racing the analysis leaves the commit stale (re-verified on the
232    /// next query) rather than wrongly fresh. `resolved` must come from the
233    /// producing analysis' own issue set
234    /// ([`crate::db::issues_have_unresolved_names`]); pass `false` when
235    /// unknown — the gen-guarded safe direction.
236    pub(crate) fn mark_ref_committed(
237        &self,
238        file: &Arc<str>,
239        text: &Arc<str>,
240        out: Option<&Arc<crate::db::AnalyzeOutput>>,
241        generation: u64,
242        resolved: bool,
243    ) {
244        let commit = RefCommit {
245            text: text.clone(),
246            out: out.map(Arc::downgrade).unwrap_or_default(),
247            generation,
248            resolved,
249        };
250        self.ref_committed.write().insert(file.clone(), commit);
251    }
252
253    pub(crate) fn forget_ref_committed(&self, file: &str) {
254        self.ref_committed.write().remove(file);
255    }
256
257    /// Stage a disk-cache write for `file`'s postings, computed in the
258    /// parallel analysis phase (needs a live db snapshot for the memoized
259    /// parse). `None` when no cache is attached or the stored entry already
260    /// matches this content — batch-written entries are never clobbered.
261    /// The caller applies the result via [`Self::apply_ref_cache_put`] in
262    /// its serial commit, alongside the in-memory index commit.
263    pub(crate) fn stage_ref_cache_put(
264        &self,
265        db: &dyn crate::db::MirDatabase,
266        sf: crate::db::SourceFile,
267        file: &str,
268        text: &Arc<str>,
269        out: &Arc<crate::db::AnalyzeOutput>,
270    ) -> Option<RefCachePut> {
271        let cache = self.cache.as_deref()?;
272        let content_hash = crate::cache::hash_content(text);
273        if cache.is_valid(file, &content_hash) {
274            return None;
275        }
276        let parsed = crate::db::parse_file(db, sf);
277        let surface_hash = crate::cache::surface_fingerprint(text, &parsed.0.program);
278        let ref_locs: Arc<[crate::cache::CachedRefLoc]> = out
279            .ref_locs
280            .iter()
281            .map(|r| (Arc::clone(&r.symbol_key), r.line, r.col_start, r.col_end))
282            .collect();
283        Some(RefCachePut {
284            content_hash,
285            surface_hash,
286            ref_locs,
287        })
288    }
289
290    pub(crate) fn apply_ref_cache_put(
291        &self,
292        file: &str,
293        out: &Arc<crate::db::AnalyzeOutput>,
294        put: RefCachePut,
295    ) {
296        if let Some(cache) = self.cache.as_deref() {
297            cache.put(
298                file,
299                put.content_hash,
300                put.surface_hash,
301                out.issues.clone(),
302                put.ref_locs,
303            );
304        }
305    }
306
307    /// Persist the attached [`AnalysisCache`] to disk. No-op without an
308    /// attached cache or when nothing changed since the last flush.
309    /// Reference postings committed by session sweeps and on-demand query
310    /// freshness passes reach disk only here — a host should call this after
311    /// its warm sweep completes and on shutdown so the next launch's
312    /// [`Self::warm_start_files`] finds them.
313    pub fn flush_analysis_cache(&self) {
314        if let Some(cache) = &self.cache {
315            cache.flush();
316        }
317    }
318
319    /// Whether `file`'s subtype-index class edges were committed from exactly
320    /// `current_text`.
321    pub(crate) fn is_defs_committed(&self, file: &str, current_text: &Arc<str>) -> bool {
322        self.defs_committed
323            .read()
324            .get(file)
325            .is_some_and(|t| Arc::ptr_eq(t, current_text))
326    }
327
328    pub(crate) fn mark_defs_committed(&self, file: &Arc<str>, text: &Arc<str>) {
329        self.defs_committed
330            .write()
331            .insert(file.clone(), text.clone());
332    }
333
334    pub(crate) fn forget_defs_committed(&self, file: &str) {
335        self.defs_committed.write().remove(file);
336    }
337
338    /// Every file with a defs commit on record, regardless of staleness.
339    pub(crate) fn defs_committed_keys(&self) -> Vec<Arc<str>> {
340        self.defs_committed.read().keys().cloned().collect()
341    }
342
343    /// Every file with a reference commit on record, regardless of
344    /// staleness. Files absent here have no reference postings at all.
345    pub(crate) fn ref_committed_keys(&self) -> Vec<Arc<str>> {
346        self.ref_committed.read().keys().cloned().collect()
347    }
348
349    /// Swap in a custom [`crate::SourceProvider`]. LSPs install a VFS-backed
350    /// provider here so the analyzer reads from unsaved editor buffers
351    /// instead of disk.
352    pub fn with_source_provider(mut self, provider: Arc<dyn crate::SourceProvider>) -> Self {
353        self.source_provider = provider;
354        self
355    }
356
357    /// Attach a pre-built [`AnalysisCache`] (the body-analysis issue cache) and
358    /// open a sibling definition [`StubSlice`] cache under the same root, so
359    /// callers using this builder get the same speedup as `with_cache_dir`.
360    ///
361    /// Rebuilds the shared database to attach the definition cache — call
362    /// **before** any file is ingested. A debug assertion catches misuse.
363    ///
364    /// [`StubSlice`]: mir_codebase::definitions::StubSlice
365    pub fn with_cache(mut self, cache: Arc<AnalysisCache>) -> Self {
366        debug_assert_eq!(
367            self.db.source_file_count(),
368            0,
369            "AnalysisSession::with_cache must be called before any file is ingested"
370        );
371        let dir = cache.cache_dir().to_path_buf();
372        self.db = Arc::new(AnalyzerDb::new().with_cache_dir(&dir));
373        self.db
374            .salsa
375            .write()
376            .set_php_version(Arc::from(self.php_version.to_string().as_str()));
377        self.cache = Some(cache);
378        self
379    }
380
381    /// Convenience: open a disk-backed cache at `cache_dir` and attach it.
382    ///
383    /// Attaches both the body-analysis issue cache ([`AnalysisCache`]) and the
384    /// definition [`StubSlice`] cache to the shared database. Builds a fresh
385    /// [`AnalyzerDb`] internally — call **before** any file is ingested. A
386    /// debug assertion catches misuse.
387    ///
388    /// [`StubSlice`]: mir_codebase::definitions::StubSlice
389    pub fn with_cache_dir(mut self, cache_dir: &std::path::Path) -> Self {
390        debug_assert_eq!(
391            self.db.source_file_count(),
392            0,
393            "AnalysisSession::with_cache_dir must be called before any file is ingested"
394        );
395        self.db = Arc::new(AnalyzerDb::new().with_cache_dir(cache_dir));
396        self.db
397            .salsa
398            .write()
399            .set_php_version(Arc::from(self.php_version.to_string().as_str()));
400        // Fold the user-stub fingerprint into the cache epoch. `with_user_stubs`
401        // must run before this for it to be picked up (it does in `build_session`);
402        // sessions without user stubs get 0, which is correct.
403        let user_stub_fp =
404            crate::stubs::user_stub_fingerprint(&self.user_stub_files, &self.user_stub_dirs);
405        self.cache = Some(Arc::new(AnalysisCache::open(
406            cache_dir,
407            self.php_version.cache_byte(),
408            user_stub_fp,
409        )));
410        self
411    }
412
413    /// Attach a Composer autoload map (PSR-4, PSR-0, classmap, files).
414    /// Sets the same map as the active [`crate::ClassResolver`] so
415    /// [`Self::load_class`] works out of the box.
416    pub fn with_psr4(mut self, map: Arc<Psr4Map>) -> Self {
417        let user_resolver: Arc<dyn crate::ClassResolver> = map.clone();
418        // Wrap with stub awareness so `find_class_like` / `resolve_fqcn_to_path`
419        // can map built-in PHP class FQCNs (`ArrayObject`, `Exception`, …)
420        // to their stub virtual paths.
421        let resolver: Arc<dyn crate::ClassResolver> = Arc::new(crate::ChainedClassResolver::new(
422            user_resolver,
423            Arc::new(crate::StubClassResolver),
424        ));
425        self.psr4 = Some(map.clone());
426        self.resolver = Some(resolver.clone());
427        // Mirror into MirDbStorage so salsa-tracked resolver queries
428        // (`db::resolve_fqcn_to_path`) see the same resolver and are
429        // invalidated on swap.
430        self.db.salsa.write().set_resolver(Some(resolver));
431        // Register vendor autoload.files for lazy loading. They define global
432        // functions and constants that the class resolver cannot discover.
433        // `ensure_vendor_eager_functions` will index them on first analysis call.
434        *self.pending_eager_function_files.lock() = Some(map.vendor_eager_files());
435        self
436    }
437
438    /// Attach a generic class resolver for projects that don't use Composer
439    /// (WordPress, Drupal, custom autoloaders, workspace-walk indexes).
440    /// Replaces any previously-set Composer-backed resolver. Automatically
441    /// wrapped with stub awareness so PHP built-ins remain resolvable.
442    pub fn with_class_resolver(mut self, resolver: Arc<dyn crate::ClassResolver>) -> Self {
443        let wrapped: Arc<dyn crate::ClassResolver> = Arc::new(crate::ChainedClassResolver::new(
444            resolver,
445            Arc::new(crate::StubClassResolver),
446        ));
447        self.db.salsa.write().set_resolver(Some(wrapped.clone()));
448        self.resolver = Some(wrapped);
449        self
450    }
451
452    pub fn with_user_stubs(mut self, files: Vec<PathBuf>, dirs: Vec<PathBuf>) -> Self {
453        self.user_stub_files = files;
454        self.user_stub_dirs = dirs;
455        self
456    }
457
458    pub fn php_version(&self) -> PhpVersion {
459        self.php_version
460    }
461
462    pub fn cache(&self) -> Option<&AnalysisCache> {
463        self.cache.as_deref()
464    }
465
466    pub fn psr4(&self) -> Option<&Psr4Map> {
467        self.psr4.as_deref()
468    }
469}
470
471mod incremental;
472mod ingest;
473mod loading;
474mod queries;
475mod stubs;
476
477pub use queries::SubtypeClassSite;
478
479/// Compute the full set of files `file` depends on: structural edges from
480/// the memoized [`crate::db::file_structural_deps`] tracked query, plus
481/// bare-FQN references recorded during body analysis (which live in the
482/// reference index and are not visible to salsa). Self-edges are excluded.
483/// Used to persist the disk cache's reverse-dep graph.
484fn file_outgoing_dependencies(
485    db: &dyn MirDatabase,
486    file: &str,
487    include_body_ref_edges: bool,
488) -> HashSet<String> {
489    let mut targets: HashSet<String> = HashSet::default();
490
491    if let Some(sf) = db.lookup_source_file(file) {
492        for target in crate::db::file_structural_deps(db, sf).iter() {
493            targets.insert(target.as_ref().to_string());
494        }
495    }
496
497    if !include_body_ref_edges {
498        return targets;
499    }
500
501    // Bare-FQN references recorded during body analysis (new \Foo(),
502    // \Foo::method(), \foo()) that do not appear in use-import statements.
503    for symbol_key in db.file_referenced_symbols(file) {
504        let lookup = crate::defining_file_lookup_key(&symbol_key);
505        if let Some(defining_file) = db.symbol_defining_file(lookup) {
506            if defining_file.as_ref() != file {
507                targets.insert(defining_file.as_ref().to_string());
508            }
509        }
510    }
511
512    targets
513}
514
515/// AST visitor that collects class FQCN references for PSR-4 preloading.
516/// Captures identifiers from `new X`, static calls / property / constant
517/// access, type hints, `instanceof`, and `@param`/`@return`/`@var`/`@extends`/
518/// `@implements` docblock annotations. Does *not* normalize via PSR-4 /
519/// imports — callers run the raw string through `resolve_name`.
520fn collect_class_refs_from_ast(program: &php_ast::owned::Program) -> Vec<String> {
521    use php_ast::ast::BinaryOp;
522    use php_ast::owned::visitor::{
523        walk_owned_class_member, walk_owned_expr, walk_owned_program, walk_owned_stmt, OwnedVisitor,
524    };
525    use php_ast::owned::{ClassMemberKind, ExprKind};
526    use std::ops::ControlFlow;
527
528    fn owned_name_str(name: &php_ast::owned::Name) -> String {
529        let joined: String = name
530            .parts
531            .iter()
532            .map(|p| p.as_ref())
533            .collect::<Vec<&str>>()
534            .join("\\");
535        if name.kind == php_ast::ast::NameKind::FullyQualified {
536            format!("\\{joined}")
537        } else {
538            joined
539        }
540    }
541
542    /// Recursively collect all `TNamedObject` FQCNs from a mir type, including
543    /// those nested inside generic type parameters (e.g. `Collection<Item>`).
544    fn collect_from_type(ty: &mir_types::Type, out: &mut std::collections::HashSet<String>) {
545        for atomic in ty.types.iter() {
546            if let mir_types::Atomic::TNamedObject { fqcn, type_params } = atomic {
547                out.insert(fqcn.as_ref().to_string());
548                for tp in type_params.iter() {
549                    collect_from_type(tp, out);
550                }
551            }
552        }
553    }
554
555    /// Parse a docblock and collect class names from `@param`, `@return`,
556    /// `@var`, `@extends`, and `@implements` annotations.
557    fn collect_from_docblock(text: &str, out: &mut std::collections::HashSet<String>) {
558        let parsed = crate::parser::DocblockParser::parse(text);
559        for (_, ty) in &parsed.params {
560            collect_from_type(ty, out);
561        }
562        if let Some(ret) = &parsed.return_type {
563            collect_from_type(ret, out);
564        }
565        if let Some(var) = &parsed.var_type {
566            collect_from_type(var, out);
567        }
568        for ext in &parsed.extends {
569            collect_from_type(ext, out);
570        }
571        for impl_ty in &parsed.implements {
572            collect_from_type(impl_ty, out);
573        }
574    }
575
576    struct V {
577        names: std::collections::HashSet<String>,
578    }
579    impl OwnedVisitor for V {
580        fn visit_stmt(&mut self, stmt: &php_ast::owned::Stmt) -> ControlFlow<()> {
581            if let Some(doc) = stmt.leading_doc_comment() {
582                collect_from_docblock(&doc.text, &mut self.names);
583            }
584            walk_owned_stmt(self, stmt)
585        }
586
587        fn visit_class_member(&mut self, member: &php_ast::owned::ClassMember) -> ControlFlow<()> {
588            match &member.kind {
589                ClassMemberKind::Method(m) => {
590                    if let Some(doc) = &m.doc_comment {
591                        collect_from_docblock(&doc.text, &mut self.names);
592                    }
593                }
594                ClassMemberKind::Property(p) => {
595                    if let Some(doc) = &p.doc_comment {
596                        collect_from_docblock(&doc.text, &mut self.names);
597                    }
598                }
599                _ => {}
600            }
601            walk_owned_class_member(self, member)
602        }
603
604        fn visit_expr(&mut self, expr: &php_ast::owned::Expr) -> ControlFlow<()> {
605            match &expr.kind {
606                ExprKind::New(n) => {
607                    if let ExprKind::Identifier(name) = &n.class.kind {
608                        self.names.insert(name.as_ref().to_string());
609                    }
610                }
611                ExprKind::StaticMethodCall(c) => {
612                    if let ExprKind::Identifier(name) = &c.class.kind {
613                        self.names.insert(name.as_ref().to_string());
614                    }
615                }
616                ExprKind::StaticPropertyAccess(a) => {
617                    if let ExprKind::Identifier(name) = &a.class.kind {
618                        self.names.insert(name.as_ref().to_string());
619                    }
620                }
621                ExprKind::ClassConstAccess(a) => {
622                    if let ExprKind::Identifier(name) = &a.class.kind {
623                        self.names.insert(name.as_ref().to_string());
624                    }
625                }
626                ExprKind::Binary(b) if b.op == BinaryOp::Instanceof => {
627                    if let ExprKind::Identifier(name) = &b.right.kind {
628                        self.names.insert(name.as_ref().to_string());
629                    }
630                }
631                _ => {}
632            }
633            walk_owned_expr(self, expr)
634        }
635
636        // Walker routes every class/type-position Name here: type hints, catch types, extends/implements, trait use, attributes.
637        fn visit_name(&mut self, name: &php_ast::owned::Name) -> ControlFlow<()> {
638            let s = owned_name_str(name);
639            if !s.is_empty() {
640                self.names.insert(s);
641            }
642            ControlFlow::Continue(())
643        }
644    }
645    let mut v = V {
646        names: std::collections::HashSet::default(),
647    };
648    let _ = walk_owned_program(&mut v, program);
649    v.names.into_iter().collect()
650}