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. It is
4//! the single writer (mutations take `&mut self`); readers on other threads
5//! use [`AnalysisSnapshot`]s from [`AnalysisSession::snapshot`].
6//!
7//! See [`crate::file_analyzer::FileAnalyzer`] for the per-file analysis
8//! entry point that operates against a session.
9
10use rustc_hash::{FxHashMap as HashMap, FxHashSet as HashSet};
11use std::path::PathBuf;
12use std::sync::Arc;
13
14use crate::analyzer_db::AnalyzerDb;
15use crate::cache::AnalysisCache;
16use crate::composer::Psr4Map;
17use crate::db::{MirDatabase, MirDbStorage, RefLoc};
18use crate::php_version::PhpVersion;
19
20/// Long-lived analysis context. Owns the salsa database and tracks which
21/// stubs have been loaded.
22///
23/// `Send` but not `Sync`: share it across threads through
24/// [`AnalysisSession::snapshot`], never by reference.
25pub struct AnalysisSession {
26 /// Database management (salsa, file registry, stub tracking).
27 pub(crate) db: AnalyzerDb,
28 pub(crate) cache: Option<Arc<AnalysisCache>>,
29 /// PSR-4 / Composer autoload map. Retained alongside `resolver` so the
30 /// `psr4()` accessor can still return a typed `Psr4Map` for callers that
31 /// need Composer-specific data (project_files / vendor_files / etc.).
32 pub(crate) psr4: Option<Arc<Psr4Map>>,
33 /// Generic class resolver used for on-demand lazy loading. When `psr4`
34 /// is set via [`Self::with_psr4`], this is populated with the same map
35 /// re-typed as `dyn ClassResolver`. Consumers can also supply their own
36 /// resolver via [`Self::with_class_resolver`] without going through
37 /// Composer.
38 resolver: Option<Arc<dyn crate::ClassResolver>>,
39 pub(crate) php_version: PhpVersion,
40 pub(crate) user_stub_files: Vec<PathBuf>,
41 pub(crate) user_stub_dirs: Vec<PathBuf>,
42 /// Tracks symbols that were previously defined in a file but have since
43 /// been removed (deleted or renamed). When `ingest_file` detects that
44 /// a symbol disappears, it records it here so `dependency_graph()` can
45 /// still produce edges to files that reference the now-gone symbol.
46 ///
47 /// Keyed by the file that used to define the symbols. Symbols are removed
48 /// from the set when re-added to the same file on a subsequent ingest.
49 /// The set may contain symbols with no current referencers; those are
50 /// harmless — the `symbol_referencers_of` lookup returns empty.
51 stale_defined_symbols: HashMap<String, HashSet<Arc<str>>>,
52 /// Symbols defined by each file as of its last `ingest_file`. The
53 /// authoritative "old" set for the rename/deletion diff, independent of
54 /// whether the salsa `SourceFile` input was already updated to the new text
55 /// by a host driving the db directly (the LSP convergence path). Without
56 /// this, re-deriving "old" symbols from the (possibly pre-updated) input
57 /// would miss deletions and break cross-file dependency invalidation.
58 last_ingested_symbols: HashMap<String, HashSet<Arc<str>>>,
59 /// Structural outgoing dependency targets by file, as of the last
60 /// ingestion that updated this session's declaration state. Lets
61 /// `ingest_file` tell whether the dependency graph's declaration-shaped
62 /// edges actually changed, so body-only edits need not invalidate the
63 /// cached graph.
64 last_structural_targets: HashMap<String, HashSet<String>>,
65 /// Negative cache: FQCNs that `load_class` already failed on.
66 /// The value is the resolver-mapped path (when known) so eviction on
67 /// `set_file_text` / `ingest_file` is a path equality check rather than
68 /// re-running the resolver per entry. `None` means the resolver itself
69 /// couldn't map the FQCN; those entries survive file edits (no source
70 /// change makes a never-resolvable name resolvable).
71 /// Bounded to `UNRESOLVABLE_CACHE_CAP`; clears on overflow.
72 unresolvable_fqcns: HashMap<Arc<str>, Option<Arc<str>>>,
73 /// Vendor `autoload.files` entries not yet indexed. `Some(paths)` means
74 /// pending; `None` means the load has already run (idempotent). Populated
75 /// by [`Self::with_psr4`]; drained by [`Self::ensure_vendor_eager_functions`],
76 /// which is called automatically from [`Self::prepare_ast_for_analysis`].
77 pub(crate) pending_eager_function_files: Option<Vec<PathBuf>>,
78 /// Warm-up skip set: files whose [`Self::prepare_ast_for_analysis`] has
79 /// already run against their current text. Value is `(text, generation)` —
80 /// the entry is live while the file's input text is pointer-equal to `text`
81 /// (a text edit self-invalidates) and `generation` matches
82 /// [`Self::prepare_generation`]. Lets the per-request Phase-1 warm-up in
83 /// `indexed_references_to` / `reanalyze_dependents` skip the serial
84 /// parse + AST walk for files already faulted in.
85 prepared_files: PreparedFilesCache,
86 /// Parsed suppression directives for unchanged files. Batch analysis
87 /// revisits every analyzed file to emit `UnusedSuppress`, so retaining
88 /// maps across same-session runs avoids rescanning the full workspace.
89 pub(crate) suppression_maps: SuppressionMapCache,
90 /// Bumped whenever previously loaded declarations may have been removed
91 /// (`invalidate_file`, symbol deletions on `ingest_file`, or a host calling
92 /// [`Self::bump_prepare_generation`]) — a prepared file might then need its
93 /// warm-up re-run to lazy-load a replacement (e.g. a vendor class shadowed
94 /// by a since-deleted project class).
95 prepare_generation: u64,
96 /// Index freshness marks and query memos, shared with every
97 /// [`AnalysisSnapshot`].
98 pub(crate) index: Arc<IndexState>,
99}
100
101const _: () = {
102 const fn assert_send<T: Send>() {}
103 assert_send::<AnalysisSession>();
104};
105
106// Fails to compile once `AnalysisSession: Sync`: the second impl then makes
107// `<_>` ambiguous.
108const _: fn() = || {
109 trait AmbiguousIfSync<A> {
110 fn some_item() {}
111 }
112 impl<T: ?Sized> AmbiguousIfSync<()> for T {}
113 struct IsSync;
114 impl<T: ?Sized + Sync> AmbiguousIfSync<IsSync> for T {}
115 let _ = <AnalysisSession as AmbiguousIfSync<_>>::some_item;
116};
117
118/// Which reference postings [`AnalysisSession::indexed_references_to`]
119/// should read back from the maintained reference index.
120#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
121pub enum ReferenceIncludes {
122 /// Plain usage/declaration references only (`cls:` / `fn:` / member
123 /// postings), excluding `use` import items.
124 Plain,
125 /// Only `use` import items (`use Foo\Bar;`, `use function ...;`,
126 /// `use const ...;`), excluding plain usage/declaration references.
127 UseImports,
128 /// Plain references plus `use` import items.
129 PlainAndUseImports,
130}
131
132/// file → `(text, prepare generation)`. See `AnalysisSession::prepared_files`.
133type PreparedFilesCache = HashMap<Arc<str>, (Arc<str>, u64)>;
134
135/// Parsed inline suppressions keyed by file path and source text.
136type SuppressionMapCache = HashMap<Arc<str>, (Arc<str>, Arc<crate::suppression::SuppressionMap>)>;
137
138/// One file's replayable body-analysis output from the previous batch run.
139pub(crate) struct BatchReplayFile {
140 pub(crate) issues: Arc<[mir_issues::Issue]>,
141 pub(crate) ref_locs: Arc<[crate::cache::CachedRefLoc]>,
142 pub(crate) symbols: Arc<[crate::symbol::ResolvedSymbol]>,
143}
144
145/// Fingerprint for a session-local whole-batch replay.
146///
147/// The replay path is intentionally narrow: exact path→content-hash equality,
148/// same PHP version, and same symbol-collection mode. This keeps it suitable
149/// for watch-mode warm repeats without widening it into a general incremental
150/// cache.
151#[derive(PartialEq, Eq)]
152pub(crate) struct BatchReplayKey {
153 php_version: u8,
154 skip_symbols: bool,
155 content_hashes: HashMap<Arc<str>, String>,
156}
157
158pub(crate) struct BatchReplayState {
159 key: BatchReplayKey,
160 pub(crate) files: HashMap<Arc<str>, BatchReplayFile>,
161}
162
163/// Cap on the negative-resolution cache. Sized to accommodate a large
164/// workspace's worth of genuinely-missing references without unbounded
165/// growth. On overflow the cache is cleared; the cost is a few extra
166/// resolver calls until it re-fills.
167const UNRESOLVABLE_CACHE_CAP: usize = 10_000;
168
169/// RAII scope from [`AnalysisSession::defer_revision_bumps`]. Derefs to the
170/// session, so the scope body mutates it through the guard.
171pub(crate) struct DeferredRevisionBumps<'a> {
172 session: &'a mut AnalysisSession,
173}
174
175impl std::ops::Deref for DeferredRevisionBumps<'_> {
176 type Target = AnalysisSession;
177 fn deref(&self) -> &AnalysisSession {
178 self.session
179 }
180}
181
182impl std::ops::DerefMut for DeferredRevisionBumps<'_> {
183 fn deref_mut(&mut self) -> &mut AnalysisSession {
184 self.session
185 }
186}
187
188impl Drop for DeferredRevisionBumps<'_> {
189 fn drop(&mut self) {
190 self.session.db.salsa.resume_revision_bumps();
191 }
192}
193
194impl AnalysisSession {
195 /// Create a session targeting the given PHP language version.
196 pub fn new(php_version: PhpVersion) -> Self {
197 let mut db = AnalyzerDb::new();
198 db.salsa.set_php_version(Arc::from(php_version.to_string()));
199 db.salsa
200 .set_source_provider(Arc::new(crate::FsSourceProvider::new()));
201 Self {
202 db,
203 cache: None,
204 psr4: None,
205 resolver: None,
206 php_version,
207 user_stub_files: Vec::new(),
208 user_stub_dirs: Vec::new(),
209 stale_defined_symbols: HashMap::default(),
210 last_ingested_symbols: HashMap::default(),
211 last_structural_targets: HashMap::default(),
212 unresolvable_fqcns: HashMap::default(),
213 pending_eager_function_files: Some(Vec::new()),
214 prepared_files: HashMap::default(),
215 suppression_maps: HashMap::default(),
216 prepare_generation: 0,
217 index: Arc::default(),
218 }
219 }
220
221 /// A `Send + Clone` read handle on the current revision. See
222 /// [`AnalysisSnapshot`] for the lifetime rules.
223 pub fn snapshot(&self) -> AnalysisSnapshot {
224 AnalysisSnapshot {
225 db: self.db.snapshot_db(),
226 index: Arc::clone(&self.index),
227 cache: self.cache.clone(),
228 php_version: self.php_version,
229 index_generation: self.index_generation(),
230 retire_epoch: self.index.retire_epoch(),
231 }
232 }
233
234 /// A [`Self::snapshot`] scoped to this borrow of the session; see
235 /// [`DbView`].
236 pub(crate) fn db_view(&self) -> DbView<'_> {
237 DbView::new(self, self.snapshot())
238 }
239
240 /// Run a snapshot query on the owner's thread. The owner can't write
241 /// while borrowed, so nothing can cancel the query: a `Cancelled` is
242 /// re-raised, never retried.
243 pub(crate) fn query_snapshot<T>(
244 &self,
245 query: impl FnOnce(&AnalysisSnapshot) -> Result<T, salsa::Cancelled>,
246 ) -> T {
247 match query(&self.db_view()) {
248 Ok(out) => out,
249 Err(cancelled) => snapshot::unwind(cancelled),
250 }
251 }
252
253 /// Hits served from [`Self::indexed_references_to`]'s memoization cache.
254 /// Diagnostic only — lets tests assert a warm repeat skipped the
255 /// freshness scan entirely.
256 pub fn ref_query_cache_hits(&self) -> u64 {
257 self.index.ref_queries.hits()
258 }
259
260 /// Total cached reference-location count across the references memo.
261 /// Diagnostic only — lets tests/hosts assert the cache stays under its
262 /// byte-proportional cap rather than trusting entry count alone.
263 pub fn ref_query_cache_locations(&self) -> usize {
264 self.index.ref_queries.items()
265 }
266
267 /// Hits served from [`Self::indexed_subtype_classes`]'s memoization
268 /// cache. Diagnostic only.
269 pub fn subtype_query_cache_hits(&self) -> u64 {
270 self.index.subtype_queries.hits()
271 }
272
273 /// Total cached site count across the subtype memo. Diagnostic only.
274 pub fn subtype_query_cache_sites(&self) -> usize {
275 self.index.subtype_queries.items()
276 }
277
278 /// Times the reference index has been locked on this session's db.
279 pub fn ref_index_lock_count(&self) -> u64 {
280 self.db.salsa.ref_index_lock_count()
281 }
282
283 pub(crate) fn transient_batch_replay(
284 &self,
285 php_version: u8,
286 skip_symbols: bool,
287 content_hashes: &HashMap<Arc<str>, String>,
288 ) -> Option<Arc<BatchReplayState>> {
289 let state = self.index.transient_batch_replay()?;
290 (state.key.php_version == php_version
291 && state.key.skip_symbols == skip_symbols
292 && state.key.content_hashes == *content_hashes)
293 .then_some(state)
294 }
295
296 pub(crate) fn store_transient_batch_replay(
297 &self,
298 php_version: u8,
299 skip_symbols: bool,
300 content_hashes: &HashMap<Arc<str>, String>,
301 files: HashMap<Arc<str>, BatchReplayFile>,
302 ) {
303 self.index.store_transient_batch_replay(BatchReplayState {
304 key: BatchReplayKey {
305 php_version,
306 skip_symbols,
307 content_hashes: content_hashes.clone(),
308 },
309 files,
310 });
311 }
312
313 /// Defer workspace revision bumps until the returned scope closes; see
314 /// [`MirDbStorage::defer_revision_bumps`].
315 pub(crate) fn defer_revision_bumps(&mut self) -> DeferredRevisionBumps<'_> {
316 self.db.salsa.defer_revision_bumps();
317 DeferredRevisionBumps { session: self }
318 }
319
320 /// Coverage/size counters for the class-mention gate index (host
321 /// metrics and memory-bound checks).
322 pub fn class_mention_stats(&self) -> crate::db::ClassMentionStats {
323 self.db.salsa.class_mention_stats()
324 }
325
326 /// See [`AnalysisSnapshot::files_mentioning_class`].
327 pub fn files_mentioning_class(&self, files: &[Arc<str>], class_name: &str) -> Vec<Arc<str>> {
328 self.files_mentioning_any(files, &[class_name])
329 }
330
331 /// See [`AnalysisSnapshot::files_mentioning_any`].
332 pub fn files_mentioning_any(&self, files: &[Arc<str>], needles: &[&str]) -> Vec<Arc<str>> {
333 self.query_snapshot(|snap| snap.files_mentioning_any(files, needles))
334 }
335
336 /// Persist the attached [`AnalysisCache`] to disk. No-op without an
337 /// attached cache or when nothing changed since the last flush.
338 /// Reference postings committed by session sweeps and on-demand query
339 /// freshness passes reach disk only here — a host should call this after
340 /// its warm sweep completes and on shutdown so the next launch's
341 /// [`Self::warm_start_files`] finds them.
342 pub fn flush_analysis_cache(&self) {
343 if let Some(cache) = &self.cache {
344 cache.flush();
345 }
346 }
347
348 /// Whether the workspace symbol index singleton is populated (seeded by
349 /// [`Self::warm_start_files`] or built by `index_batch`) — symbol lookups
350 /// answer from the O(1) map instead of the tracked O(all-files) walk.
351 pub fn workspace_symbol_index_ready(&self) -> bool {
352 self.db.salsa.workspace_symbol_index_singleton().is_some()
353 }
354
355 /// Executions of the tracked O(all-files) `workspace_symbol_index` walk
356 /// (diagnostic; a warm-started session should keep this at zero).
357 pub fn workspace_index_walks(&self) -> u64 {
358 self.db.salsa.workspace_index_walks()
359 }
360
361 /// Units of `work` this session's analysis has done (diagnostic).
362 pub fn work_count(&self, work: crate::db::Work) -> u64 {
363 self.db.salsa.work_count(work)
364 }
365
366 /// Swap in a custom [`crate::SourceProvider`]. LSPs install a VFS-backed
367 /// provider here so the analyzer reads from unsaved editor buffers
368 /// instead of disk.
369 pub fn with_source_provider(mut self, provider: Arc<dyn crate::SourceProvider>) -> Self {
370 self.db.salsa.set_source_provider(provider);
371 self
372 }
373
374 /// Attach a pre-built [`AnalysisCache`] (the body-analysis issue cache) and
375 /// open a sibling definition [`StubSlice`] cache under the same root, so
376 /// callers using this builder get the same speedup as `with_cache_dir`.
377 ///
378 /// Call **before** any file is ingested. A debug assertion catches misuse.
379 ///
380 /// [`StubSlice`]: mir_codebase::definitions::StubSlice
381 pub fn with_cache(mut self, cache: Arc<AnalysisCache>) -> Self {
382 debug_assert_eq!(
383 self.db.source_file_count(),
384 0,
385 "AnalysisSession::with_cache must be called before any file is ingested"
386 );
387 self.db.attach_cache_dir(cache.cache_dir());
388 self.cache = Some(cache);
389 self
390 }
391
392 /// Convenience: open a disk-backed cache at `cache_dir` and attach it.
393 ///
394 /// Attaches both the body-analysis issue cache ([`AnalysisCache`]) and the
395 /// definition [`StubSlice`] cache to the shared database. Call **before**
396 /// any file is ingested. A debug assertion catches misuse.
397 ///
398 /// [`StubSlice`]: mir_codebase::definitions::StubSlice
399 pub fn with_cache_dir(mut self, cache_dir: &std::path::Path) -> Self {
400 debug_assert_eq!(
401 self.db.source_file_count(),
402 0,
403 "AnalysisSession::with_cache_dir must be called before any file is ingested"
404 );
405 self.db.attach_cache_dir(cache_dir);
406 // Fold the user-stub fingerprint into the cache epoch. `with_user_stubs`
407 // must run before this for it to be picked up (it does in `build_session`);
408 // sessions without user stubs get 0, which is correct.
409 let user_stub_fp =
410 crate::stubs::user_stub_fingerprint(&self.user_stub_files, &self.user_stub_dirs);
411 self.cache = Some(Arc::new(AnalysisCache::open(
412 cache_dir,
413 self.php_version.cache_byte(),
414 user_stub_fp,
415 )));
416 self
417 }
418
419 /// Attach a Composer autoload map (PSR-4, PSR-0, classmap, files).
420 /// Sets the same map as the active [`crate::ClassResolver`] so
421 /// [`Self::load_class`] works out of the box.
422 pub fn with_psr4(mut self, map: Arc<Psr4Map>) -> Self {
423 let user_resolver: Arc<dyn crate::ClassResolver> = map.clone();
424 // Wrap with stub awareness so `find_class_like` / `resolve_fqcn_to_path`
425 // can map built-in PHP class FQCNs (`ArrayObject`, `Exception`, …)
426 // to their stub virtual paths.
427 let resolver: Arc<dyn crate::ClassResolver> = Arc::new(crate::ChainedClassResolver::new(
428 user_resolver,
429 Arc::new(crate::StubClassResolver),
430 ));
431 self.psr4 = Some(map.clone());
432 self.resolver = Some(resolver.clone());
433 // Mirror into MirDbStorage so salsa-tracked resolver queries
434 // (`db::resolve_fqcn_to_path`) see the same resolver and are
435 // invalidated on swap.
436 self.db.salsa.set_resolver(Some(resolver));
437 // Register vendor autoload.files for lazy loading. They define global
438 // functions and constants that the class resolver cannot discover.
439 // `ensure_vendor_eager_functions` will index them on first analysis call.
440 self.pending_eager_function_files = Some(map.vendor_eager_files());
441 self
442 }
443
444 /// Attach a generic class resolver for projects that don't use Composer
445 /// (WordPress, Drupal, custom autoloaders, workspace-walk indexes).
446 /// Replaces any previously-set Composer-backed resolver. Automatically
447 /// wrapped with stub awareness so PHP built-ins remain resolvable.
448 pub fn with_class_resolver(mut self, resolver: Arc<dyn crate::ClassResolver>) -> Self {
449 let wrapped: Arc<dyn crate::ClassResolver> = Arc::new(crate::ChainedClassResolver::new(
450 resolver,
451 Arc::new(crate::StubClassResolver),
452 ));
453 self.db.salsa.set_resolver(Some(wrapped.clone()));
454 self.resolver = Some(wrapped);
455 self
456 }
457
458 pub fn with_user_stubs(mut self, files: Vec<PathBuf>, dirs: Vec<PathBuf>) -> Self {
459 self.user_stub_files = files;
460 self.user_stub_dirs = dirs;
461 self
462 }
463
464 pub fn php_version(&self) -> PhpVersion {
465 self.php_version
466 }
467
468 pub fn cache(&self) -> Option<&AnalysisCache> {
469 self.cache.as_deref()
470 }
471
472 pub fn psr4(&self) -> Option<&Psr4Map> {
473 self.psr4.as_deref()
474 }
475}
476
477mod incremental;
478mod index_state;
479mod ingest;
480mod loading;
481mod queries;
482mod snapshot;
483mod stubs;
484
485use index_state::IndexState;
486pub use queries::SubtypeClassSite;
487pub use snapshot::AnalysisSnapshot;
488use snapshot::DbView;
489
490/// Compute the full set of files `file` depends on by projecting structural
491/// and body-reference symbols through the workspace symbol index. Self-edges
492/// are excluded. Used to persist the disk cache's reverse-dep graph.
493fn file_outgoing_dependencies(
494 db: &dyn MirDatabase,
495 file: &str,
496 include_body_ref_edges: bool,
497) -> HashSet<String> {
498 let mut targets: HashSet<String> = HashSet::default();
499
500 if let Some(sf) = db.lookup_source_file(file) {
501 for symbol in crate::db::file_structural_symbols(db, sf).iter() {
502 let lookup = crate::defining_file_lookup_key(symbol);
503 if let Some(defining_file) = db.symbol_defining_file(lookup) {
504 if defining_file.as_ref() != file {
505 targets.insert(defining_file.as_ref().to_string());
506 }
507 }
508 }
509 }
510
511 if !include_body_ref_edges {
512 return targets;
513 }
514
515 // Bare-FQN references recorded during body analysis (new \Foo(),
516 // \Foo::method(), \foo()) that do not appear in use-import statements.
517 for symbol_key in db.file_referenced_symbols(file) {
518 let lookup = crate::defining_file_lookup_key(&symbol_key);
519 if let Some(defining_file) = db.symbol_defining_file(lookup) {
520 if defining_file.as_ref() != file {
521 targets.insert(defining_file.as_ref().to_string());
522 }
523 }
524 }
525
526 targets
527}
528
529/// AST visitor that collects class FQCN references for PSR-4 preloading.
530/// Captures identifiers from `new X`, static calls / property / constant
531/// access, type hints, `instanceof`, and `@param`/`@return`/`@var`/`@extends`/
532/// `@implements` docblock annotations. Does *not* normalize via PSR-4 /
533/// imports — callers run the raw string through `resolve_name`.
534fn collect_class_refs_from_ast(program: &php_ast::owned::Program) -> Vec<String> {
535 use php_ast::ast::BinaryOp;
536 use php_ast::owned::visitor::{
537 walk_owned_class_member, walk_owned_expr, walk_owned_program, walk_owned_stmt, OwnedVisitor,
538 };
539 use php_ast::owned::{ClassMemberKind, ExprKind};
540 use std::ops::ControlFlow;
541
542 fn owned_name_str(name: &php_ast::owned::Name) -> String {
543 let joined: String = name
544 .parts
545 .iter()
546 .map(|p| p.as_ref())
547 .collect::<Vec<&str>>()
548 .join("\\");
549 if name.kind == php_ast::ast::NameKind::FullyQualified {
550 format!("\\{joined}")
551 } else {
552 joined
553 }
554 }
555
556 /// Recursively collect all `TNamedObject` FQCNs from a mir type, including
557 /// those nested inside generic type parameters (e.g. `Collection<Item>`).
558 fn collect_from_type(ty: &mir_types::Type, out: &mut std::collections::HashSet<String>) {
559 for atomic in ty.types.iter() {
560 if let mir_types::Atomic::TNamedObject { fqcn, type_params } = atomic {
561 out.insert(fqcn.as_ref().to_string());
562 for tp in type_params.iter() {
563 collect_from_type(tp, out);
564 }
565 }
566 }
567 }
568
569 /// Parse a docblock and collect class names from `@param`, `@return`,
570 /// `@var`, `@extends`, and `@implements` annotations.
571 fn collect_from_docblock(text: &str, out: &mut std::collections::HashSet<String>) {
572 let parsed = crate::parser::DocblockParser::parse(text);
573 for (_, ty) in &parsed.params {
574 collect_from_type(ty, out);
575 }
576 if let Some(ret) = &parsed.return_type {
577 collect_from_type(ret, out);
578 }
579 if let Some(var) = &parsed.var_type {
580 collect_from_type(var, out);
581 }
582 for ext in &parsed.extends {
583 collect_from_type(ext, out);
584 }
585 for impl_ty in &parsed.implements {
586 collect_from_type(impl_ty, out);
587 }
588 }
589
590 struct V {
591 names: std::collections::HashSet<String>,
592 }
593 impl OwnedVisitor for V {
594 fn visit_stmt(&mut self, stmt: &php_ast::owned::Stmt) -> ControlFlow<()> {
595 if let Some(doc) = stmt.leading_doc_comment() {
596 collect_from_docblock(&doc.text, &mut self.names);
597 }
598 walk_owned_stmt(self, stmt)
599 }
600
601 fn visit_class_member(&mut self, member: &php_ast::owned::ClassMember) -> ControlFlow<()> {
602 match &member.kind {
603 ClassMemberKind::Method(m) => {
604 if let Some(doc) = &m.doc_comment {
605 collect_from_docblock(&doc.text, &mut self.names);
606 }
607 }
608 ClassMemberKind::Property(p) => {
609 if let Some(doc) = &p.doc_comment {
610 collect_from_docblock(&doc.text, &mut self.names);
611 }
612 }
613 _ => {}
614 }
615 walk_owned_class_member(self, member)
616 }
617
618 fn visit_expr(&mut self, expr: &php_ast::owned::Expr) -> ControlFlow<()> {
619 match &expr.kind {
620 ExprKind::New(n) => {
621 if let ExprKind::Identifier(name) = &n.class.kind {
622 self.names.insert(name.as_ref().to_string());
623 }
624 }
625 ExprKind::StaticMethodCall(c) => {
626 if let ExprKind::Identifier(name) = &c.class.kind {
627 self.names.insert(name.as_ref().to_string());
628 }
629 }
630 ExprKind::StaticPropertyAccess(a) => {
631 if let ExprKind::Identifier(name) = &a.class.kind {
632 self.names.insert(name.as_ref().to_string());
633 }
634 }
635 ExprKind::ClassConstAccess(a) => {
636 if let ExprKind::Identifier(name) = &a.class.kind {
637 self.names.insert(name.as_ref().to_string());
638 }
639 }
640 ExprKind::Binary(b) if b.op == BinaryOp::Instanceof => {
641 if let ExprKind::Identifier(name) = &b.right.kind {
642 self.names.insert(name.as_ref().to_string());
643 }
644 }
645 _ => {}
646 }
647 walk_owned_expr(self, expr)
648 }
649
650 // Walker routes every class/type-position Name here: type hints, catch types, extends/implements, trait use, attributes.
651 fn visit_name(&mut self, name: &php_ast::owned::Name) -> ControlFlow<()> {
652 let s = owned_name_str(name);
653 if !s.is_empty() {
654 self.names.insert(s);
655 }
656 ControlFlow::Continue(())
657 }
658 }
659 let mut v = V {
660 names: std::collections::HashSet::default(),
661 };
662 let _ = walk_owned_program(&mut v, program);
663 v.names.into_iter().collect()
664}