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    /// Swap in a custom [`crate::SourceProvider`]. LSPs install a VFS-backed
344    /// provider here so the analyzer reads from unsaved editor buffers
345    /// instead of disk.
346    pub fn with_source_provider(mut self, provider: Arc<dyn crate::SourceProvider>) -> Self {
347        self.source_provider = provider;
348        self
349    }
350
351    /// Attach a pre-built [`AnalysisCache`] (the body-analysis issue cache) and
352    /// open a sibling definition [`StubSlice`] cache under the same root, so
353    /// callers using this builder get the same speedup as `with_cache_dir`.
354    ///
355    /// Rebuilds the shared database to attach the definition cache — call
356    /// **before** any file is ingested. A debug assertion catches misuse.
357    ///
358    /// [`StubSlice`]: mir_codebase::definitions::StubSlice
359    pub fn with_cache(mut self, cache: Arc<AnalysisCache>) -> Self {
360        debug_assert_eq!(
361            self.db.source_file_count(),
362            0,
363            "AnalysisSession::with_cache must be called before any file is ingested"
364        );
365        let dir = cache.cache_dir().to_path_buf();
366        self.db = Arc::new(AnalyzerDb::new().with_cache_dir(&dir));
367        self.db
368            .salsa
369            .write()
370            .set_php_version(Arc::from(self.php_version.to_string().as_str()));
371        self.cache = Some(cache);
372        self
373    }
374
375    /// Convenience: open a disk-backed cache at `cache_dir` and attach it.
376    ///
377    /// Attaches both the body-analysis issue cache ([`AnalysisCache`]) and the
378    /// definition [`StubSlice`] cache to the shared database. Builds a fresh
379    /// [`AnalyzerDb`] internally — call **before** any file is ingested. A
380    /// debug assertion catches misuse.
381    ///
382    /// [`StubSlice`]: mir_codebase::definitions::StubSlice
383    pub fn with_cache_dir(mut self, cache_dir: &std::path::Path) -> Self {
384        debug_assert_eq!(
385            self.db.source_file_count(),
386            0,
387            "AnalysisSession::with_cache_dir must be called before any file is ingested"
388        );
389        self.db = Arc::new(AnalyzerDb::new().with_cache_dir(cache_dir));
390        self.db
391            .salsa
392            .write()
393            .set_php_version(Arc::from(self.php_version.to_string().as_str()));
394        // Fold the user-stub fingerprint into the cache epoch. `with_user_stubs`
395        // must run before this for it to be picked up (it does in `build_session`);
396        // sessions without user stubs get 0, which is correct.
397        let user_stub_fp =
398            crate::stubs::user_stub_fingerprint(&self.user_stub_files, &self.user_stub_dirs);
399        self.cache = Some(Arc::new(AnalysisCache::open(
400            cache_dir,
401            self.php_version.cache_byte(),
402            user_stub_fp,
403        )));
404        self
405    }
406
407    /// Attach a Composer autoload map (PSR-4, PSR-0, classmap, files).
408    /// Sets the same map as the active [`crate::ClassResolver`] so
409    /// [`Self::load_class`] works out of the box.
410    pub fn with_psr4(mut self, map: Arc<Psr4Map>) -> Self {
411        let user_resolver: Arc<dyn crate::ClassResolver> = map.clone();
412        // Wrap with stub awareness so `find_class_like` / `resolve_fqcn_to_path`
413        // can map built-in PHP class FQCNs (`ArrayObject`, `Exception`, …)
414        // to their stub virtual paths.
415        let resolver: Arc<dyn crate::ClassResolver> = Arc::new(crate::ChainedClassResolver::new(
416            user_resolver,
417            Arc::new(crate::StubClassResolver),
418        ));
419        self.psr4 = Some(map.clone());
420        self.resolver = Some(resolver.clone());
421        // Mirror into MirDbStorage so salsa-tracked resolver queries
422        // (`db::resolve_fqcn_to_path`) see the same resolver and are
423        // invalidated on swap.
424        self.db.salsa.write().set_resolver(Some(resolver));
425        // Register vendor autoload.files for lazy loading. They define global
426        // functions and constants that the class resolver cannot discover.
427        // `ensure_vendor_eager_functions` will index them on first analysis call.
428        *self.pending_eager_function_files.lock() = Some(map.vendor_eager_files());
429        self
430    }
431
432    /// Attach a generic class resolver for projects that don't use Composer
433    /// (WordPress, Drupal, custom autoloaders, workspace-walk indexes).
434    /// Replaces any previously-set Composer-backed resolver. Automatically
435    /// wrapped with stub awareness so PHP built-ins remain resolvable.
436    pub fn with_class_resolver(mut self, resolver: Arc<dyn crate::ClassResolver>) -> Self {
437        let wrapped: Arc<dyn crate::ClassResolver> = Arc::new(crate::ChainedClassResolver::new(
438            resolver,
439            Arc::new(crate::StubClassResolver),
440        ));
441        self.db.salsa.write().set_resolver(Some(wrapped.clone()));
442        self.resolver = Some(wrapped);
443        self
444    }
445
446    pub fn with_user_stubs(mut self, files: Vec<PathBuf>, dirs: Vec<PathBuf>) -> Self {
447        self.user_stub_files = files;
448        self.user_stub_dirs = dirs;
449        self
450    }
451
452    pub fn php_version(&self) -> PhpVersion {
453        self.php_version
454    }
455
456    pub fn cache(&self) -> Option<&AnalysisCache> {
457        self.cache.as_deref()
458    }
459
460    pub fn psr4(&self) -> Option<&Psr4Map> {
461        self.psr4.as_deref()
462    }
463}
464
465mod incremental;
466mod ingest;
467mod loading;
468mod queries;
469mod stubs;
470
471pub use queries::SubtypeClassSite;
472
473/// Compute the full set of files `file` depends on: structural edges from
474/// the memoized [`crate::db::file_structural_deps`] tracked query, plus
475/// bare-FQN references recorded during body analysis (which live in the
476/// reference index and are not visible to salsa). Self-edges are excluded.
477/// Used to persist the disk cache's reverse-dep graph.
478fn file_outgoing_dependencies(
479    db: &dyn MirDatabase,
480    file: &str,
481    include_body_ref_edges: bool,
482) -> HashSet<String> {
483    let mut targets: HashSet<String> = HashSet::default();
484
485    if let Some(sf) = db.lookup_source_file(file) {
486        for target in crate::db::file_structural_deps(db, sf).iter() {
487            targets.insert(target.as_ref().to_string());
488        }
489    }
490
491    if !include_body_ref_edges {
492        return targets;
493    }
494
495    // Bare-FQN references recorded during body analysis (new \Foo(),
496    // \Foo::method(), \foo()) that do not appear in use-import statements.
497    for symbol_key in db.file_referenced_symbols(file) {
498        let lookup = crate::defining_file_lookup_key(&symbol_key);
499        if let Some(defining_file) = db.symbol_defining_file(lookup) {
500            if defining_file.as_ref() != file {
501                targets.insert(defining_file.as_ref().to_string());
502            }
503        }
504    }
505
506    targets
507}
508
509/// AST visitor that collects class FQCN references for PSR-4 preloading.
510/// Captures identifiers from `new X`, static calls / property / constant
511/// access, type hints, `instanceof`, and `@param`/`@return`/`@var`/`@extends`/
512/// `@implements` docblock annotations. Does *not* normalize via PSR-4 /
513/// imports — callers run the raw string through `resolve_name`.
514fn collect_class_refs_from_ast(program: &php_ast::owned::Program) -> Vec<String> {
515    use php_ast::ast::BinaryOp;
516    use php_ast::owned::visitor::{
517        walk_owned_class_member, walk_owned_expr, walk_owned_program, walk_owned_stmt, OwnedVisitor,
518    };
519    use php_ast::owned::{ClassMemberKind, ExprKind};
520    use std::ops::ControlFlow;
521
522    fn owned_name_str(name: &php_ast::owned::Name) -> String {
523        let joined: String = name
524            .parts
525            .iter()
526            .map(|p| p.as_ref())
527            .collect::<Vec<&str>>()
528            .join("\\");
529        if name.kind == php_ast::ast::NameKind::FullyQualified {
530            format!("\\{joined}")
531        } else {
532            joined
533        }
534    }
535
536    /// Recursively collect all `TNamedObject` FQCNs from a mir type, including
537    /// those nested inside generic type parameters (e.g. `Collection<Item>`).
538    fn collect_from_type(ty: &mir_types::Type, out: &mut std::collections::HashSet<String>) {
539        for atomic in ty.types.iter() {
540            if let mir_types::Atomic::TNamedObject { fqcn, type_params } = atomic {
541                out.insert(fqcn.as_ref().to_string());
542                for tp in type_params.iter() {
543                    collect_from_type(tp, out);
544                }
545            }
546        }
547    }
548
549    /// Parse a docblock and collect class names from `@param`, `@return`,
550    /// `@var`, `@extends`, and `@implements` annotations.
551    fn collect_from_docblock(text: &str, out: &mut std::collections::HashSet<String>) {
552        let parsed = crate::parser::DocblockParser::parse(text);
553        for (_, ty) in &parsed.params {
554            collect_from_type(ty, out);
555        }
556        if let Some(ret) = &parsed.return_type {
557            collect_from_type(ret, out);
558        }
559        if let Some(var) = &parsed.var_type {
560            collect_from_type(var, out);
561        }
562        for ext in &parsed.extends {
563            collect_from_type(ext, out);
564        }
565        for impl_ty in &parsed.implements {
566            collect_from_type(impl_ty, out);
567        }
568    }
569
570    struct V {
571        names: std::collections::HashSet<String>,
572    }
573    impl OwnedVisitor for V {
574        fn visit_stmt(&mut self, stmt: &php_ast::owned::Stmt) -> ControlFlow<()> {
575            if let Some(doc) = stmt.leading_doc_comment() {
576                collect_from_docblock(&doc.text, &mut self.names);
577            }
578            walk_owned_stmt(self, stmt)
579        }
580
581        fn visit_class_member(&mut self, member: &php_ast::owned::ClassMember) -> ControlFlow<()> {
582            match &member.kind {
583                ClassMemberKind::Method(m) => {
584                    if let Some(doc) = &m.doc_comment {
585                        collect_from_docblock(&doc.text, &mut self.names);
586                    }
587                }
588                ClassMemberKind::Property(p) => {
589                    if let Some(doc) = &p.doc_comment {
590                        collect_from_docblock(&doc.text, &mut self.names);
591                    }
592                }
593                _ => {}
594            }
595            walk_owned_class_member(self, member)
596        }
597
598        fn visit_expr(&mut self, expr: &php_ast::owned::Expr) -> ControlFlow<()> {
599            match &expr.kind {
600                ExprKind::New(n) => {
601                    if let ExprKind::Identifier(name) = &n.class.kind {
602                        self.names.insert(name.as_ref().to_string());
603                    }
604                }
605                ExprKind::StaticMethodCall(c) => {
606                    if let ExprKind::Identifier(name) = &c.class.kind {
607                        self.names.insert(name.as_ref().to_string());
608                    }
609                }
610                ExprKind::StaticPropertyAccess(a) => {
611                    if let ExprKind::Identifier(name) = &a.class.kind {
612                        self.names.insert(name.as_ref().to_string());
613                    }
614                }
615                ExprKind::ClassConstAccess(a) => {
616                    if let ExprKind::Identifier(name) = &a.class.kind {
617                        self.names.insert(name.as_ref().to_string());
618                    }
619                }
620                ExprKind::Binary(b) if b.op == BinaryOp::Instanceof => {
621                    if let ExprKind::Identifier(name) = &b.right.kind {
622                        self.names.insert(name.as_ref().to_string());
623                    }
624                }
625                _ => {}
626            }
627            walk_owned_expr(self, expr)
628        }
629
630        // Walker routes every class/type-position Name here: type hints, catch types, extends/implements, trait use, attributes.
631        fn visit_name(&mut self, name: &php_ast::owned::Name) -> ControlFlow<()> {
632            let s = owned_name_str(name);
633            if !s.is_empty() {
634                self.names.insert(s);
635            }
636            ControlFlow::Continue(())
637        }
638    }
639    let mut v = V {
640        names: std::collections::HashSet::default(),
641    };
642    let _ = walk_owned_program(&mut v, program);
643    v.names.into_iter().collect()
644}