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