Skip to main content

mir_analyzer/session/
queries.rs

1use super::*;
2
3impl AnalysisSession {
4    /// Resolve a top-level symbol (class or function) to its declaration
5    /// location. Powers go-to-definition.
6    ///
7    /// **Side effects:** if the symbol isn't yet known, this may invoke the
8    /// configured [`crate::SourceProvider`] to fault in additional files and
9    /// mutate the salsa input set. Use [`Self::definition_of_cached`] for a
10    /// pure variant that only consults already-loaded state.
11    ///
12    /// Returns:
13    /// - `Ok(Location)` — symbol found with a source location
14    /// - `Err(NotFound)` — no such symbol in the codebase
15    /// - `Err(NoSourceLocation)` — symbol exists but has no recorded span
16    ///   (e.g. some stub-only declarations)
17    pub fn definition_of(
18        &self,
19        symbol: &crate::Name,
20    ) -> Result<mir_types::Location, crate::SymbolLookupError> {
21        // Trigger any necessary lazy-load mutations before snapshotting.
22        match symbol {
23            crate::Name::Class(fqcn) => {
24                let _ = self.load_class(fqcn.as_ref());
25            }
26            crate::Name::Function(fqn) => {
27                let _ = self.load_class(fqn.as_ref());
28            }
29            crate::Name::Method { class, .. }
30            | crate::Name::Property { class, .. }
31            | crate::Name::ClassConstant { class, .. } => {
32                let _ = self.load_class(class.as_ref());
33            }
34            _ => {}
35        }
36        self.definition_of_cached(symbol)
37    }
38
39    /// Pure variant of [`Self::definition_of`]. Never invokes the
40    /// [`crate::SourceProvider`] and never mutates salsa inputs; resolves
41    /// only against state already loaded by `set_file_text` / `ingest_file`.
42    /// Returns `Err(NotFound)` when the symbol isn't in the loaded set, even
43    /// if a resolver could in principle map it.
44    pub fn definition_of_cached(
45        &self,
46        symbol: &crate::Name,
47    ) -> Result<mir_types::Location, crate::SymbolLookupError> {
48        let db = self.snapshot_db();
49        match symbol {
50            crate::Name::Class(fqcn) => {
51                let here = crate::db::Fqcn::from_str(&db, fqcn.as_ref());
52                let class = crate::db::find_class_like(&db, here)
53                    .ok_or(crate::SymbolLookupError::NotFound)?;
54                class
55                    .location()
56                    .cloned()
57                    .ok_or(crate::SymbolLookupError::NoSourceLocation)
58            }
59            crate::Name::Function(fqn) => {
60                let here = crate::db::Fqcn::from_str(&db, fqn.as_ref());
61                let f = crate::db::find_function(&db, here)
62                    .ok_or(crate::SymbolLookupError::NotFound)?;
63                f.location
64                    .clone()
65                    .ok_or(crate::SymbolLookupError::NoSourceLocation)
66            }
67            crate::Name::Method { class, name }
68            | crate::Name::Property { class, name }
69            | crate::Name::ClassConstant { class, name } => {
70                crate::db::member_location(&db, class, name)
71                    .ok_or(crate::SymbolLookupError::NotFound)
72            }
73            crate::Name::GlobalConstant(_) => Err(crate::SymbolLookupError::NoSourceLocation),
74        }
75    }
76
77    /// Hover information for a symbol: type, docstring, and definition location.
78    ///
79    /// Use [`crate::FileAnalysis::symbol_at`] to find the symbol at a cursor
80    /// position, then build a [`crate::Name`] from its `kind`. This method
81    /// assembles the displayable hover data.
82    ///
83    /// **Side effects:** when `symbol`'s owning class isn't yet loaded, this
84    /// may invoke the configured [`crate::SourceProvider`] to fault in
85    /// dependencies. Use [`Self::hover_cached`] for a pure variant.
86    ///
87    /// Returns `Err(NotFound)` if the symbol doesn't exist. May still return
88    /// `Ok` with `docstring: None` or `definition: None` if those specific
89    /// pieces aren't available.
90    pub fn hover(
91        &self,
92        symbol: &crate::Name,
93    ) -> Result<crate::HoverInfo, crate::SymbolLookupError> {
94        // Trigger lazy loading for class-rooted symbols before snapshotting.
95        // No-op when the class is already known; ensures inherited member
96        // lookups have the chain present.
97        match symbol {
98            crate::Name::Class(fqcn) => {
99                self.load_class(fqcn.as_ref());
100            }
101            crate::Name::Method { class, .. }
102            | crate::Name::Property { class, .. }
103            | crate::Name::ClassConstant { class, .. } => {
104                // Fault in the owning class for navigation if the background
105                // indexer hasn't reached it yet. Its inheritance ancestors
106                // resolve through the (eagerly-built) workspace symbol index.
107                self.load_class(class.as_ref());
108            }
109            _ => {}
110        }
111        self.hover_cached(symbol)
112    }
113
114    /// Pure variant of [`Self::hover`]. Never invokes the
115    /// [`crate::SourceProvider`]; consults only the already-loaded db.
116    pub fn hover_cached(
117        &self,
118        symbol: &crate::Name,
119    ) -> Result<crate::HoverInfo, crate::SymbolLookupError> {
120        use mir_types::{Atomic, Type};
121        let db = self.snapshot_db();
122        match symbol {
123            crate::Name::Function(fqn) => {
124                let here = crate::db::Fqcn::from_str(&db, fqn.as_ref());
125                let f = crate::db::find_function(&db, here)
126                    .ok_or(crate::SymbolLookupError::NotFound)?;
127                let ty = f
128                    .return_type
129                    .as_deref()
130                    .cloned()
131                    .unwrap_or_else(Type::mixed);
132                let docstring = f.docstring.as_ref().map(|s| s.to_string());
133                Ok(crate::HoverInfo {
134                    ty,
135                    docstring,
136                    definition: f.location.clone(),
137                })
138            }
139            crate::Name::Method { class, name } => {
140                let here = crate::db::Fqcn::from_str(&db, class.as_ref());
141                let (_, m) = crate::db::find_method_in_chain(&db, here, name)
142                    .ok_or(crate::SymbolLookupError::NotFound)?;
143                let ty = m
144                    .return_type
145                    .as_deref()
146                    .cloned()
147                    .unwrap_or_else(Type::mixed);
148                let docstring = m.docstring.as_ref().map(|s| s.to_string());
149                Ok(crate::HoverInfo {
150                    ty,
151                    docstring,
152                    definition: m.location.clone(),
153                })
154            }
155            crate::Name::Class(fqcn) => {
156                let here = crate::db::Fqcn::from_str(&db, fqcn.as_ref());
157                let class = crate::db::find_class_like(&db, here)
158                    .ok_or(crate::SymbolLookupError::NotFound)?;
159                let ty = Type::single(Atomic::TNamedObject {
160                    fqcn: mir_types::Name::from(fqcn.as_ref()),
161                    type_params: mir_types::union::empty_type_params(),
162                });
163                Ok(crate::HoverInfo {
164                    ty,
165                    docstring: None,
166                    definition: class.location().cloned(),
167                })
168            }
169            crate::Name::Property { class, name } => {
170                let here = crate::db::Fqcn::from_str(&db, class.as_ref());
171                let (_, p) = crate::db::find_property_in_chain(&db, here, name)
172                    .ok_or(crate::SymbolLookupError::NotFound)?;
173                let ty = p.ty.as_deref().cloned().unwrap_or_else(Type::mixed);
174                Ok(crate::HoverInfo {
175                    ty,
176                    docstring: None,
177                    definition: p.location.clone(),
178                })
179            }
180            crate::Name::ClassConstant { class, name } => {
181                let here = crate::db::Fqcn::from_str(&db, class.as_ref());
182                let (_, c) = crate::db::find_class_constant_in_chain(&db, here, name)
183                    .ok_or(crate::SymbolLookupError::NotFound)?;
184                Ok(crate::HoverInfo {
185                    ty: c.ty.clone(),
186                    docstring: None,
187                    definition: c.location.clone(),
188                })
189            }
190            crate::Name::GlobalConstant(fqn) => {
191                let here = crate::db::Fqcn::from_str(&db, fqn.as_ref());
192                let ty = crate::db::find_global_constant(&db, here)
193                    .ok_or(crate::SymbolLookupError::NotFound)?;
194                Ok(crate::HoverInfo {
195                    ty: (*ty).clone(),
196                    docstring: None,
197                    definition: None,
198                })
199            }
200        }
201    }
202
203    /// Raw reference locations indexed by string symbol key, kept for tests
204    /// that use the legacy stringly-typed API. Prefer [`Self::indexed_references_to`]
205    /// with a typed [`crate::Name`].
206    #[doc(hidden)]
207    pub fn reference_locations(&self, symbol: &str) -> Vec<(Arc<str>, u32, u16, u16)> {
208        use crate::db::MirDatabase;
209        let db = self.snapshot_db();
210        db.reference_locations(symbol)
211    }
212
213    /// Files declaring transitive subclasses of `class_fqn`, backed by the
214    /// maintained subtype index (see [`Self::indexed_subtype_classes`]).
215    /// Excludes `class_fqn`'s own declaring file — the caller adds it.
216    ///
217    /// Lets a reference-search caller scope a `protected` member to its class
218    /// hierarchy without reconstructing that hierarchy from declaration text:
219    /// subclasses are matched by resolved FQCN, so `extends \Ns\Base` and
220    /// aliased `use` forms are all found. Read-only from the caller's
221    /// perspective; may trigger an on-demand commit of stale/uncommitted
222    /// candidates' class edges (same self-heal `indexed_subtype_classes` uses).
223    pub fn subtype_files(&self, class_fqn: &str) -> Vec<Arc<str>> {
224        self.settle_workspace_index();
225        let files = self.snapshot_db().source_file_paths();
226        let mut out: Vec<Arc<str>> = self
227            .indexed_subtype_classes(class_fqn, &files, false)
228            .into_iter()
229            .map(|s| s.file)
230            .collect();
231        out.sort();
232        out.dedup();
233        out
234    }
235
236    /// `use`-import occurrences of `symbol` — the import statement's own name
237    /// token (`use Foo\Bar;`, `use function ...;`, `use const ...;`), not a
238    /// usage site. Recorded under a `use:`-prefixed posting distinct from the
239    /// plain `cls:`/`fn:`/`gcnst:` keys [`Self::indexed_references_to`] reads,
240    /// so a symbol rename can also find/update the import line without a
241    /// plain find-references query suddenly including import statements.
242    ///
243    /// Read-only posting-list lookup, filtered to `files` — no freshness pass:
244    /// callers that need guaranteed-fresh results for an uncommitted file
245    /// should analyze it first (e.g. via [`Self::indexed_references_to`] on
246    /// the same file set).
247    pub fn indexed_use_import_locations(
248        &self,
249        symbol: &crate::Name,
250        files: &[Arc<str>],
251    ) -> Vec<(Arc<str>, crate::Range)> {
252        self.settle_workspace_index();
253        let key = format!("use:{}", symbol.codebase_key());
254        let scope: rustc_hash::FxHashSet<&str> = files.iter().map(|f| f.as_ref()).collect();
255        let guard = self.db.salsa.read();
256        let mut out: Vec<(Arc<str>, crate::Range)> = guard
257            .reference_locations(&key)
258            .into_iter()
259            .filter(|(file, ..)| scope.contains(file.as_ref()))
260            .map(|(file, line, col_start, col_end)| {
261                (file, span_range(line, col_start as u32, col_end as u32))
262            })
263            .collect();
264        out.sort_by(|a, b| {
265            a.0.cmp(&b.0)
266                .then(a.1.start.line.cmp(&b.1.start.line))
267                .then(a.1.start.column.cmp(&b.1.start.column))
268        });
269        out.dedup();
270        out
271    }
272
273    /// Inverted-index find-references: posting-list lookup plus an on-demand
274    /// freshness/completeness pass over `files` (the host's candidate scope
275    /// — passing the whole workspace is fine; see the gate below).
276    ///
277    /// A candidate whose postings were committed from its current input text
278    /// (Arc identity) is answered from the index with no salsa work at all.
279    /// Stale or never-committed candidates are analyzed via the memoized
280    /// `analyze_file` query and committed, so each file pays that cost once
281    /// per text change — after a background warm sweep the steady state is a
282    /// pure lookup, O(results) instead of O(candidates). Never-committed
283    /// candidates are additionally gated on their raw text mentioning the
284    /// symbol's name (whole-identifier, ASCII-case-insensitive), so hosts
285    /// need no text prefilter of their own — and must not use one, since a
286    /// host-side filter cannot know these matching semantics.
287    ///
288    /// Results are filtered to `files` (the host controls scope — e.g.
289    /// workspace files only, excluding stubs/vendor). With
290    /// `include_declaration`, the symbol's declaration name span is appended
291    /// when it lies inside the scope.
292    ///
293    /// `should_cancel` is polled at phase boundaries and between
294    /// cancellation retries; `true` aborts with `None`.
295    ///
296    /// Memoized per `(symbol, files, include_declaration, text_revision)` —
297    /// see [`RefQueryCacheKey`]. The freshness scan below still costs
298    /// O(candidates) even when every candidate is already committed (it has
299    /// to check), so a caller re-running the same query against unchanged
300    /// state (e.g. a host recomputing reference counts for a code-lens
301    /// refresh) would otherwise re-pay that scan on every call; this makes
302    /// the repeat a single hashmap lookup instead.
303    pub fn indexed_references_to(
304        &self,
305        symbol: &crate::Name,
306        files: &[Arc<str>],
307        include_declaration: bool,
308        should_cancel: &(dyn Fn() -> bool + Sync),
309    ) -> Option<Vec<(Arc<str>, crate::Range)>> {
310        // No `should_cancel()` check here: a cache hit does no analysis
311        // work, so there's nothing to cancel, and calling it would consume
312        // one of the caller's cancellation-probe invocations before the
313        // uncached path's own checks ever run (some callers, e.g.
314        // `session_sweep_persists_postings_for_next_launch`, count these to
315        // prove a warm query needed no re-analysis).
316        let cache_key = RefQueryCacheKey {
317            symbol: symbol.codebase_key(),
318            include_declaration,
319            generation: self.query_cache_generation(),
320            files_hash: hash_files(files),
321        };
322        if let Some(cached) = self.ref_query_cache.read().get(&cache_key) {
323            self.ref_query_cache_hits
324                .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
325            return Some((**cached).clone());
326        }
327        let result =
328            self.indexed_references_to_uncached(symbol, files, include_declaration, should_cancel)?;
329        if self.query_cache_generation() != cache_key.generation {
330            // The generation moved while computing (an edit, or a defs
331            // commit growing the subtype index — possibly this query's own).
332            // The key can never be looked up again, so don't cache it; the
333            // next identical query recomputes once against settled state
334            // and caches then.
335            return Some(result);
336        }
337        let mut cache = self.ref_query_cache.write();
338        if !cache.advance_to(cache_key.generation, || {
339            self.ref_query_cache_locations
340                .store(0, std::sync::atomic::Ordering::Relaxed);
341        }) {
342            return Some(result);
343        }
344        let new_len = result.len();
345        let prior = self
346            .ref_query_cache_locations
347            .fetch_add(new_len, std::sync::atomic::Ordering::Relaxed);
348        if prior + new_len > REF_QUERY_CACHE_LOCATION_CAP {
349            cache.map.clear();
350            self.ref_query_cache_locations
351                .store(new_len, std::sync::atomic::Ordering::Relaxed);
352        }
353        cache.map.insert(cache_key, Arc::new(result.clone()));
354        Some(result)
355    }
356
357    /// Uncached implementation of [`Self::indexed_references_to`]. Callers
358    /// should use the memoizing wrapper; this is split out only so the cache
359    /// check/populate logic doesn't have to interleave with the retry loops
360    /// below.
361    fn indexed_references_to_uncached(
362        &self,
363        symbol: &crate::Name,
364        files: &[Arc<str>],
365        include_declaration: bool,
366        should_cancel: &(dyn Fn() -> bool + Sync),
367    ) -> Option<Vec<(Arc<str>, crate::Range)>> {
368        self.settle_workspace_index();
369        use std::panic::AssertUnwindSafe;
370
371        use rayon::prelude::*;
372
373        let key = symbol.codebase_key();
374
375        // Freshness pass: candidates whose postings are not exact for their
376        // current text. Files not registered as `SourceFile` inputs are
377        // skipped. Never-committed files — no commit mark, hence no postings
378        // at all (every mark drop accompanies a posting clear) — are further
379        // gated on their text mentioning the symbol's name: such a file can
380        // neither hold stale postings nor produce new ones, so a cold query
381        // on a common name skips the bulk of the workspace instead of
382        // analyzing it. A LIVE-analyzed file stale only by generation
383        // (unresolved-name commit, text unchanged since) gets the same gate:
384        // the current text is exactly what this session's own analysis
385        // already scanned, so a needle miss is just as conclusive as for a
386        // never-committed file. Everything else — a genuinely edited file, or
387        // a commit seeded by an unverified disk-cache replay
388        // (`warm_start_files`, never scanned by this session) — re-analyzes
389        // unconditionally: an edited file's old postings are for different
390        // text, and a replayed commit's postings are only as trustworthy as
391        // the cache entry, so neither can be cleared by a textual gate alone.
392        // Same discipline as `commit_defs_for_matching` on the defs index.
393        //
394        let gate = self.reference_gate(symbol);
395        // The whole gate — identifier needles and raw call tokens alike —
396        // answers from the persistent mention index: every needle is admitted
397        // (a declared class-like short name is already in the universe;
398        // member/function names and the two `__construct` call tokens enter
399        // verbatim), so a recorded mention set answers with lookups and only
400        // a never-scanned or since-edited file pays one scan against the
401        // whole universe, recorded for every later consumer (including the
402        // subtype-BFS gate). A needle new to the universe epoch-invalidates
403        // older recordings for itself only — the first query on it rescans
404        // uncovered files once, the same cost the per-query scan paid every
405        // time before.
406        let has_needles = !gate.idents.is_empty() || !gate.raw.is_empty();
407        let (mention_queries, mention_scanner) = if has_needles {
408            let guard = self.db.salsa.read();
409            guard.add_literal_mention_names(gate.idents.iter().map(|s| s.as_str()));
410            guard.add_raw_mention_needles(gate.raw.iter().map(|s| s.as_str()));
411            let queries: Vec<_> = gate
412                .idents
413                .iter()
414                .chain(gate.raw.iter())
415                .filter_map(|s| guard.prepare_class_mention_query(s))
416                .collect();
417            (queries, guard.class_mention_scanner())
418        } else {
419            (Vec::new(), None)
420        };
421        // Admission guarantees a query per needle and a non-empty universe;
422        // anything else is defensive — the gate then admits every candidate
423        // (analyze rather than skip, the conservative direction).
424        let gate_complete = mention_queries.len() == gate.idents.len() + gate.raw.len()
425            && mention_scanner.is_some();
426        let committed_any: rustc_hash::FxHashSet<Arc<str>> =
427            self.ref_committed_keys().into_iter().collect();
428        type MentionScanRec = (Arc<str>, Arc<str>, Box<[mir_types::Name]>);
429        let (stale, scanned): (Vec<Arc<str>>, Vec<MentionScanRec>) = loop {
430            if should_cancel() {
431                return None;
432            }
433            let attempt = salsa::Cancelled::catch(AssertUnwindSafe(|| {
434                let current_gen = self.index_generation();
435                let db_main = self.snapshot_db();
436                files
437                    .par_iter()
438                    .map_with(db_main, |db, f| {
439                        let Some(sf) = db.lookup_source_file(f.as_ref()) else {
440                            return (None, None);
441                        };
442                        let text = sf.text(&*db as &dyn MirDatabase);
443                        if self.is_ref_committed(f.as_ref(), text, current_gen) {
444                            return (None, None);
445                        }
446                        if committed_any.contains(f.as_ref())
447                            && !self.ref_commit_stale_by_generation_only(f.as_ref(), text)
448                        {
449                            return (Some(f.clone()), None);
450                        }
451                        if has_needles && gate_complete {
452                            // Any needle answering `true` admits the file; an
453                            // unanswerable one forces the single recorded
454                            // scan, which settles every needle at once.
455                            let mut answer = Some(false);
456                            for q in &mention_queries {
457                                match db.class_mention_answer(f.as_ref(), q, text) {
458                                    Some(true) => {
459                                        answer = Some(true);
460                                        break;
461                                    }
462                                    Some(false) => {}
463                                    None => answer = None,
464                                }
465                            }
466                            match answer {
467                                Some(true) => {}
468                                Some(false) => return (None, None),
469                                None => {
470                                    let scanner = mention_scanner
471                                        .as_ref()
472                                        .expect("gate_complete implies a scanner");
473                                    let names = scanner.scan(text);
474                                    let hit = mention_queries
475                                        .iter()
476                                        .any(|q| names.binary_search(&q.name).is_ok());
477                                    let rec = (f.clone(), text.clone(), names);
478                                    return (hit.then(|| f.clone()), Some(rec));
479                                }
480                            }
481                        }
482                        (Some(f.clone()), None)
483                    })
484                    .collect::<Vec<_>>()
485            }));
486            match attempt {
487                Ok(v) => {
488                    let mut stale = Vec::new();
489                    let mut scanned = Vec::new();
490                    for (s, rec) in v {
491                        if let Some(s) = s {
492                            stale.push(s);
493                        }
494                        if let Some(rec) = rec {
495                            scanned.push(rec);
496                        }
497                    }
498                    break (stale, scanned);
499                }
500                Err(_) if should_cancel() => return None,
501                Err(_) => {}
502            }
503        };
504
505        // Record the fallback scans regardless of how the query proceeds:
506        // each is a complete, current mention set for its file.
507        if let Some(scanner) = &mention_scanner {
508            if !scanned.is_empty() {
509                let guard = self.db.salsa.read();
510                for (file, text, names) in scanned {
511                    guard.set_file_class_mentions(&file, &text, scanner.epoch(), names);
512                }
513            }
514        }
515
516        if !stale.is_empty() {
517            // Phase 1 (serial, no live snapshot held): warm up stale
518            // candidates. `prepare_file_for_analysis` mutates salsa inputs
519            // (via `load_class`), so a concurrent writer — the background
520            // warm sweep, or another request — can raise `salsa::Cancelled`
521            // partway through a file. Catch and retry the SAME file here
522            // rather than letting the panic escape: uncaught, it would force
523            // the caller's outer retry loop (`indexed_references`) to
524            // re-enter from scratch, redoing the freshness pass and
525            // re-walking every already-warmed file in `stale` (cheap no-ops
526            // via the `prepared_files` cache, but not free) before it even
527            // gets back to the file that was interrupted. This doesn't
528            // change how many times a write is ultimately attempted (the
529            // outer loop already retries indefinitely on `Cancelled`); it
530            // only narrows what a single cancellation discards from "the
531            // whole query so far" to "the one file that was mid-flight".
532            //
533            // Tried and reverted TWICE: running this loop itself in parallel
534            // (rayon; per-file and whole-batch retry variants, and again as
535            // a `try_for_each` after the deferred-bump scope landed). Each
536            // file's warm-up is individually safe under concurrent access
537            // (every shared registry it touches — `prepared_files`,
538            // `unresolvable_fqcns`, `pending_eager_function_files`, the
539            // salsa db via `with_db_mut` — is lock-protected), but under the
540            // `concurrent_reference_cancel` stress test (sustained
541            // multi-thread writers + a background indexer, both hammering
542            // the same db while several readers each run this phase
543            // concurrently) every parallel variant deadlocks: CPU usage
544            // drops to ~0 while wall time keeps climbing — OS threads parked
545            // on a lock, most likely the fixed-size rayon pool saturated
546            // with workers blocked on `with_db_mut`'s `RwLock` write lock
547            // (an OS-level block, invisible to rayon's cooperative
548            // scheduler) while the thread that would release it is itself
549            // queued waiting for a free pool worker. Coalescing the
550            // per-load revision bumps into one per pass (the deferred scope
551            // below) did NOT fix it — the re-attempt hung the same way
552            // (>590s for a ~5s test), so the cancellation storm was not the
553            // trigger. Serial execution never contends for the pool this
554            // way, so it stays the safe choice here even though it forgoes
555            // the extra wall-clock parallelism a large stale set could
556            // otherwise use.
557            {
558                // One revision bump for the whole warm-up loop instead of one
559                // per lazily-loaded class: each bump is a salsa input write
560                // that cancels every in-flight reader (a concurrent request's
561                // Phase 2 pass restarts per bump). The scope closes before
562                // Phase 2 reads `index_generation`, so commits below are
563                // stamped with the post-load generation as before.
564                let _deferred_bumps = self.defer_revision_bumps();
565                for path in &stale {
566                    loop {
567                        if should_cancel() {
568                            return None;
569                        }
570                        match salsa::Cancelled::catch(AssertUnwindSafe(|| {
571                            self.prepare_file_for_analysis(path)
572                        })) {
573                            Ok(()) => break,
574                            Err(_) if should_cancel() => return None,
575                            Err(_) => {}
576                        }
577                    }
578                }
579            }
580
581            // Phase 2 (parallel, pure) under a cancellation retry loop, then
582            // a serial commit into both inverted indexes.
583            let (commit_gen, analyzed) = loop {
584                if should_cancel() {
585                    return None;
586                }
587                // Generation before the snapshot: a file add racing the
588                // analysis leaves these commits stale (self-healing on the
589                // next query), never wrongly fresh.
590                let gen = self.index_generation();
591                let attempt = salsa::Cancelled::catch(AssertUnwindSafe(|| {
592                    // Freeze on the pass-scoped snapshot (borrow-only symbol
593                    // lookups + pass-shared subtype cache): all lazy-loading
594                    // finished in Phase 1, and a concurrent index write
595                    // cancels this attempt, so the frozen view is never
596                    // stale. Same discipline as the batch body pass.
597                    let mut db_main = self.snapshot_db();
598                    db_main.freeze_workspace_index();
599                    stale
600                        .iter()
601                        .filter_map(|path| {
602                            let sf = db_main.lookup_source_file(path.as_ref())?;
603                            let text = sf.text(&db_main as &dyn MirDatabase).clone();
604                            let out =
605                                crate::db::analyze_file(&db_main as &dyn MirDatabase, sf).clone();
606                            let defs = crate::db::collect_file_definitions(
607                                &db_main as &dyn MirDatabase,
608                                sf,
609                            );
610                            let entries = crate::db::subtype_index::entries_from_slice(&defs.slice);
611                            // Stage the disk-cache write only when the commit
612                            // below will rewrite postings (see the sweep in
613                            // `reanalyze_file_set` for the cost rationale).
614                            let put = if self.ref_commit_is_current(path.as_ref(), &text, &out) {
615                                None
616                            } else {
617                                self.stage_ref_cache_put(
618                                    &db_main as &dyn MirDatabase,
619                                    sf,
620                                    path.as_ref(),
621                                    &text,
622                                    &out,
623                                )
624                            };
625                            // Mention scan piggybacks on the analysis pass
626                            // (pure; committed serially below), skipped when
627                            // the file already holds a current scan.
628                            let mentions = mention_scanner.as_ref().and_then(|s| {
629                                (!db_main.class_mentions_current(path.as_ref(), &text, s.epoch()))
630                                    .then(|| s.scan(&text))
631                            });
632                            Some((path.clone(), text, out, entries, put, mentions))
633                        })
634                        .collect::<Vec<_>>()
635                }));
636                match attempt {
637                    Ok(v) => break (gen, v),
638                    Err(_) if should_cancel() => return None,
639                    Err(_) => {}
640                }
641            };
642            let mut analyzed = analyzed;
643            let guard = self.db.salsa.read();
644            for (file, text, out, entries, put, mentions) in analyzed.iter_mut() {
645                // Pointer-identical memo ⇒ identical postings: skip the
646                // index rewrite and only re-stamp the freshness mark.
647                if !self.ref_commit_is_current(file.as_ref(), text, out) {
648                    guard.set_file_reference_locations(file.as_ref(), out.ref_locs.to_vec());
649                }
650                if let (Some(s), Some(m)) = (&mention_scanner, mentions.take()) {
651                    guard.set_file_class_mentions(file, text, s.epoch(), m);
652                }
653                if let Some(put) = put.take() {
654                    self.apply_ref_cache_put(file.as_ref(), out, put);
655                }
656                self.mark_ref_committed(
657                    file,
658                    text,
659                    Some(out),
660                    commit_gen,
661                    !out.has_unresolved_names(),
662                );
663                if !self.is_defs_committed(file.as_ref(), text) {
664                    guard.set_file_class_edges(file, entries.clone());
665                    self.mark_defs_committed(file, text);
666                }
667            }
668        }
669
670        // Posting lookup, filtered to the candidate scope.
671        //
672        // Member symbols resolve against the queried class plus its hierarchy
673        // (mir records member refs under the *declaring* class, so a query on
674        // an interface method must include implementor keys and vice versa).
675        // Name-only fallback postings — receivers whose type couldn't be
676        // resolved — are consulted only when the typed keys produce nothing,
677        // mirroring the pre-index two-tier behavior: exact results when
678        // resolution succeeds, by-name matches when nothing resolves.
679        // `__construct` stays exact: `new Sub()` invokes `Sub::__construct`
680        // even when only a parent declares one, so hierarchy fan-out would
681        // wrongly return subtype instantiation sites for a parent query.
682        let hierarchy: Vec<String> = match symbol {
683            crate::Name::Method { class, name } => {
684                if name.as_ref() == "__construct" || class.is_empty() {
685                    if class.is_empty() {
686                        Vec::new()
687                    } else {
688                        vec![class.trim_start_matches('\\').to_string()]
689                    }
690                } else {
691                    self.member_hierarchy_classes(class.as_ref())
692                }
693            }
694            crate::Name::Property { class, .. } | crate::Name::ClassConstant { class, .. } => {
695                if class.is_empty() {
696                    Vec::new()
697                } else {
698                    self.member_hierarchy_classes(class.as_ref())
699                }
700            }
701            _ => Vec::new(),
702        };
703        let scope: rustc_hash::FxHashSet<&str> = files.iter().map(|f| f.as_ref()).collect();
704        let read_symbol_key = |symbol_key: &str| -> Vec<(Arc<str>, crate::Range)> {
705            let guard = self.db.salsa.read();
706            guard
707                .reference_locations(symbol_key)
708                .into_iter()
709                .filter(|(file, ..)| scope.contains(file.as_ref()))
710                .map(|(file, line, col_start, col_end)| {
711                    (file, span_range(line, col_start as u32, col_end as u32))
712                })
713                .collect()
714        };
715        let mut scratch_key = String::new();
716        let mut read_composed_key = |prefix: &str, middle: &str, separator: &str, suffix: &str| {
717            scratch_key.clear();
718            scratch_key.reserve(prefix.len() + middle.len() + separator.len() + suffix.len());
719            scratch_key.push_str(prefix);
720            scratch_key.push_str(middle);
721            scratch_key.push_str(separator);
722            scratch_key.push_str(suffix);
723            read_symbol_key(&scratch_key)
724        };
725        let mut out: Vec<(Arc<str>, crate::Range)> = Vec::new();
726        match symbol {
727            crate::Name::Method { name, .. } => {
728                for class in &hierarchy {
729                    out.extend(read_composed_key(
730                        "meth:",
731                        class.as_ref(),
732                        "::",
733                        name.as_ref(),
734                    ));
735                }
736            }
737            crate::Name::Property { name, .. } => {
738                for class in &hierarchy {
739                    out.extend(read_composed_key(
740                        "prop:",
741                        class.as_ref(),
742                        "::",
743                        name.as_ref(),
744                    ));
745                }
746            }
747            crate::Name::ClassConstant { name, .. } => {
748                for class in &hierarchy {
749                    out.extend(read_composed_key(
750                        "cnst:",
751                        class.as_ref(),
752                        "::",
753                        name.as_ref(),
754                    ));
755                }
756            }
757            _ => out.extend(read_symbol_key(key.as_str())),
758        }
759        if out.is_empty() {
760            match symbol {
761                crate::Name::Method { name, .. } => {
762                    out = read_composed_key("methname:", name.as_ref(), "", "");
763                }
764                crate::Name::Property { name, .. } => {
765                    out = read_composed_key("propname:", name.as_ref(), "", "");
766                }
767                _ => {}
768            }
769        }
770        out.sort_by(|a, b| {
771            a.0.cmp(&b.0)
772                .then(a.1.start.line.cmp(&b.1.start.line))
773                .then(a.1.start.column.cmp(&b.1.start.column))
774        });
775        out.dedup_by(|a, b| a.0 == b.0 && a.1 == b.1);
776
777        if include_declaration {
778            // Declaration lookup runs salsa queries (and may lazy-load); a
779            // concurrent write cancels it — declarations are then simply
780            // omitted rather than failing the whole request.
781            let decls: Vec<(Arc<str>, crate::Range)> = match symbol {
782                crate::Name::Method { class, .. }
783                | crate::Name::Property { class, .. }
784                | crate::Name::ClassConstant { class, .. } => {
785                    if class.is_empty() {
786                        // Unknown owner: declarations by name, recorded as
787                        // `methdecl:`/`propdecl:`/`cnstdecl:` postings during
788                        // class/trait/interface/enum analysis.
789                        match symbol {
790                            crate::Name::Method { name, .. } => {
791                                read_composed_key("methdecl:", name.as_ref(), "", "")
792                            }
793                            crate::Name::Property { name, .. } => {
794                                read_composed_key("propdecl:", name.as_ref(), "", "")
795                            }
796                            crate::Name::ClassConstant { name, .. } => {
797                                read_composed_key("cnstdecl:", name.as_ref(), "", "")
798                            }
799                            _ => Vec::new(),
800                        }
801                    } else {
802                        salsa::Cancelled::catch(AssertUnwindSafe(|| {
803                            self.member_decl_sites(&hierarchy, symbol)
804                        }))
805                        .unwrap_or_default()
806                    }
807                }
808                _ => salsa::Cancelled::catch(AssertUnwindSafe(|| {
809                    self.declaration_name_range(symbol).into_iter().collect()
810                }))
811                .unwrap_or_default(),
812            };
813            for (file, range) in decls {
814                if scope.contains(file.as_ref())
815                    && !out.iter().any(|(f, r)| *f == file && *r == range)
816                {
817                    out.push((file, range));
818                }
819            }
820        }
821        Some(out)
822    }
823
824    /// The queried class plus every class its members' references could be
825    /// keyed under: resolved ancestors (a call on a subtype instance records
826    /// the declaring ancestor) and transitive subtypes including trait users
827    /// (a call on a subtype that overrides records the subtype). Display-form
828    /// FQCNs, deduplicated case-insensitively.
829    fn member_hierarchy_classes(&self, class_fqn: &str) -> Vec<String> {
830        use std::panic::AssertUnwindSafe;
831        let target = class_fqn.trim_start_matches('\\').to_string();
832        let mut out: Vec<String> = vec![target.clone()];
833        let ancestors = salsa::Cancelled::catch(AssertUnwindSafe(|| {
834            let db = self.snapshot_db();
835            let here = crate::db::Fqcn::from_str(&db, &target);
836            crate::db::class_ancestors_by_fqcn(&db, here)
837                .iter()
838                .skip(1)
839                .map(|a| a.trim_start_matches('\\').to_string())
840                .collect::<Vec<_>>()
841        }))
842        .unwrap_or_default();
843        out.extend(ancestors);
844        let subs = {
845            let guard = self.db.salsa.read();
846            guard.subtype_sites_of(&target, true)
847        };
848        out.extend(
849            subs.into_iter()
850                .map(|s| s.fqcn.trim_start_matches('\\').to_string()),
851        );
852        let mut seen: rustc_hash::FxHashSet<String> = rustc_hash::FxHashSet::default();
853        out.retain(|c| seen.insert(c.to_ascii_lowercase()));
854        out
855    }
856
857    /// Own-member declaration sites for `symbol` across `classes`: each class
858    /// that itself declares the member (not inherited) contributes its name
859    /// token. Kind-specific lookups — a class often declares a property and a
860    /// method with the same short name, and `member_location` can't tell them
861    /// apart.
862    fn member_decl_sites(
863        &self,
864        classes: &[String],
865        symbol: &crate::Name,
866    ) -> Vec<(Arc<str>, crate::Range)> {
867        let mut out: Vec<(Arc<str>, crate::Range)> = Vec::new();
868        let db = self.snapshot_db();
869        for class in classes {
870            let here = crate::db::Fqcn::from_str(&db, class);
871            let (loc, needle) = match symbol {
872                crate::Name::Method { name, .. } => {
873                    let Some(m) = crate::db::find_method_in_class(&db, here, name) else {
874                        continue;
875                    };
876                    (m.location.clone(), name.to_string())
877                }
878                crate::Name::Property { name, .. } => {
879                    let Some(p) = crate::db::find_property_in_class(&db, here, name) else {
880                        continue;
881                    };
882                    (p.location.clone(), name.to_string())
883                }
884                crate::Name::ClassConstant { name, .. } => {
885                    let Some(c) = crate::db::find_class_constant_in_class(&db, here, name) else {
886                        continue;
887                    };
888                    (c.location.clone(), name.to_string())
889                }
890                _ => continue,
891            };
892            let Some(loc) = loc else { continue };
893            let range = self.refine_location_to_name(&loc, &needle);
894            out.push((loc.file.clone(), range));
895        }
896        out
897    }
898
899    /// The symbol's declaration site, narrowed from the collector's
900    /// whole-declaration span to the declared name's own token (matching the
901    /// span shape of recorded references).
902    pub fn declaration_name_range(&self, symbol: &crate::Name) -> Option<(Arc<str>, crate::Range)> {
903        if let crate::Name::GlobalConstant(fqn) = symbol {
904            return self.global_constant_decl_range(fqn);
905        }
906        let loc = self.definition_of(symbol).ok()?;
907        let short = match symbol {
908            crate::Name::Class(f) | crate::Name::Function(f) | crate::Name::GlobalConstant(f) => {
909                crate::db::subtype_index::short_name_of(f)
910            }
911            crate::Name::Method { name, .. }
912            | crate::Name::Property { name, .. }
913            | crate::Name::ClassConstant { name, .. } => name.as_ref(),
914        };
915        // Property declarations carry a `$` sigil in source, but reference
916        // ranges cover the bare name; the word-boundary search below lands on
917        // the name right after the sigil.
918        let file = loc.file.clone();
919        let range = self.refine_location_to_name(&loc, short);
920        Some((file, range))
921    }
922
923    /// Narrow a whole-declaration [`mir_types::Location`] to the first
924    /// word-boundary occurrence of `needle` inside its line span. Falls back
925    /// to the location's own coordinates when the text is unavailable or the
926    /// name doesn't appear (e.g. stub-only declarations).
927    fn refine_location_to_name(&self, loc: &mir_types::Location, needle: &str) -> crate::Range {
928        let fallback = span_range(loc.line, loc.col_start as u32, loc.col_end as u32);
929        let text = {
930            let db = self.snapshot_db();
931            db.lookup_source_file(loc.file.as_ref())
932                .map(|sf| sf.text(&db as &dyn MirDatabase).clone())
933        };
934        let Some(text) = text else {
935            return fallback;
936        };
937        let needle_chars = needle.chars().count() as u32;
938        let first_line = loc.line.saturating_sub(1) as usize;
939        // Exact-case first: PHP property/constant names are case-sensitive
940        // and an early case-insensitive hit can land on an unrelated token
941        // (a type hint sharing the name). Case-insensitive second, for
942        // method/class needles that arrive lowercase-normalized.
943        for case_insensitive in [false, true] {
944            for (idx, line_text) in text.lines().enumerate().skip(first_line) {
945                let line_no = idx as u32 + 1;
946                if line_no > loc.line_end {
947                    break;
948                }
949                let min_col = if line_no == loc.line {
950                    loc.col_start as usize
951                } else {
952                    0
953                };
954                if let Some(col) = identifier_char_col(line_text, needle, min_col, case_insensitive)
955                {
956                    return span_range(line_no, col, col + needle_chars);
957                }
958            }
959        }
960        fallback
961    }
962
963    /// Transitive subtypes of `class_fqn` (classes/interfaces/enums whose
964    /// resolved ancestor chain reaches it), answered from the maintained
965    /// subtype edge index.
966    ///
967    /// `files` is the host's candidate scope for the on-demand completeness
968    /// pass: per BFS round, not-yet-committed files whose text mentions a
969    /// frontier name get their definitions committed, so results are complete
970    /// even before a background sweep has covered the workspace. Committed
971    /// files answer from the index with no parsing at all.
972    ///
973    /// `include_trait_users` also counts `use Trait;` composition as a
974    /// subtype edge (visibility-scoping semantics); leave it off for
975    /// goto-implementation semantics (extends/implements only).
976    ///
977    /// Memoized per `(class_fqn, include_trait_users, files, text_revision)`
978    /// — same shape and rationale as [`Self::indexed_references_to`]'s
979    /// cache: `commit_defs_for_matching`'s freshness pass costs O(candidates)
980    /// on every call regardless of outcome, so a repeat query (e.g. a host
981    /// resolving a protected/static method's reference scope on every
982    /// code-lens refresh) would otherwise re-pay it every time.
983    pub fn indexed_subtype_classes(
984        &self,
985        class_fqn: &str,
986        files: &[Arc<str>],
987        include_trait_users: bool,
988    ) -> Vec<SubtypeClassSite> {
989        let cache_key = SubtypeQueryCacheKey {
990            class_fqn: class_fqn.trim_start_matches('\\').to_ascii_lowercase(),
991            include_trait_users,
992            generation: self.query_cache_generation(),
993            files_hash: hash_files(files),
994        };
995        if let Some(cached) = self.subtype_query_cache.read().get(&cache_key) {
996            self.subtype_query_cache_hits
997                .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
998            return (**cached).clone();
999        }
1000        let result = self.indexed_subtype_classes_uncached(class_fqn, files, include_trait_users);
1001        if self.query_cache_generation() != cache_key.generation {
1002            // The generation moved while computing (an edit, or a defs
1003            // commit growing the subtype index — possibly this query's own).
1004            // The key can never be looked up again, so don't cache it; the
1005            // next identical query recomputes once against settled state
1006            // and caches then.
1007            return result;
1008        }
1009        let mut cache = self.subtype_query_cache.write();
1010        if !cache.advance_to(cache_key.generation, || {
1011            self.subtype_query_cache_sites
1012                .store(0, std::sync::atomic::Ordering::Relaxed);
1013        }) {
1014            return result;
1015        }
1016        let new_len = result.len();
1017        let prior = self
1018            .subtype_query_cache_sites
1019            .fetch_add(new_len, std::sync::atomic::Ordering::Relaxed);
1020        if prior + new_len > SUBTYPE_QUERY_CACHE_SITE_CAP {
1021            cache.map.clear();
1022            self.subtype_query_cache_sites
1023                .store(new_len, std::sync::atomic::Ordering::Relaxed);
1024        }
1025        cache.map.insert(cache_key, Arc::new(result.clone()));
1026        result
1027    }
1028
1029    /// Uncached implementation of [`Self::indexed_subtype_classes`]. Callers
1030    /// should use the memoizing wrapper.
1031    fn indexed_subtype_classes_uncached(
1032        &self,
1033        class_fqn: &str,
1034        files: &[Arc<str>],
1035        include_trait_users: bool,
1036    ) -> Vec<SubtypeClassSite> {
1037        self.settle_workspace_index();
1038        let mut scanned: rustc_hash::FxHashSet<String> = rustc_hash::FxHashSet::default();
1039        let mut pending: Vec<String> = vec![class_fqn.trim_start_matches('\\').to_string()];
1040        let mut sites: Vec<crate::db::SubtypeSite> = Vec::new();
1041        while !pending.is_empty() {
1042            let needles: Vec<String> = pending
1043                .drain(..)
1044                .filter(|f| scanned.insert(f.clone()))
1045                .map(|f| crate::db::subtype_index::short_name_of(&f).to_string())
1046                .collect();
1047            if !needles.is_empty() {
1048                self.commit_defs_for_matching(files, &needles);
1049            }
1050            sites = {
1051                let guard = self.db.salsa.read();
1052                guard.subtype_sites_of_lenient(class_fqn, include_trait_users)
1053            };
1054            pending = sites
1055                .iter()
1056                .map(|s| s.fqcn.trim_start_matches('\\').to_string())
1057                .filter(|f| !scanned.contains(f))
1058                .collect();
1059        }
1060        let mut out: Vec<SubtypeClassSite> = sites
1061            .into_iter()
1062            .filter_map(|s| {
1063                let loc = s.location.as_ref()?;
1064                let short = crate::db::subtype_index::short_name_of(&s.fqcn).to_string();
1065                let range = self.refine_location_to_name(loc, &short);
1066                Some(SubtypeClassSite {
1067                    fqcn: s.fqcn,
1068                    kind: s.kind,
1069                    is_abstract: s.is_abstract,
1070                    file: s.file,
1071                    range,
1072                })
1073            })
1074            .collect();
1075        // Anonymous classes never reach the definition collector; their
1076        // `new class implements X {}` sites are recorded as `impl:` postings
1077        // during body analysis (exact FQCN key plus a short-name key for the
1078        // same written-form leniency named classes get above).
1079        let root_lc = class_fqn.trim_start_matches('\\').to_ascii_lowercase();
1080        let short_lc = crate::db::subtype_index::short_name_of(&root_lc).to_string();
1081        let scope: rustc_hash::FxHashSet<&str> = files.iter().map(|f| f.as_ref()).collect();
1082        let anon: Vec<(Arc<str>, u32, u16, u16)> = {
1083            let guard = self.db.salsa.read();
1084            let mut key = String::with_capacity("implshort:".len() + root_lc.len());
1085            key.push_str("impl:");
1086            key.push_str(&root_lc);
1087            let mut v = guard.reference_locations(&key);
1088            key.clear();
1089            key.push_str("implshort:");
1090            key.push_str(&short_lc);
1091            v.extend(guard.reference_locations(&key));
1092            v.sort();
1093            v.dedup();
1094            v
1095        };
1096        for (file, line, cs, ce) in anon {
1097            if !scope.contains(file.as_ref()) {
1098                continue;
1099            }
1100            let range = span_range(line, cs as u32, ce as u32);
1101            if out.iter().any(|s| s.file == file && s.range == range) {
1102                continue;
1103            }
1104            out.push(SubtypeClassSite {
1105                fqcn: Arc::from("class@anonymous"),
1106                kind: crate::db::ClassLikeKind::Class,
1107                is_abstract: false,
1108                file,
1109                range,
1110            });
1111        }
1112        out
1113    }
1114
1115    /// Concrete implementations of `class_fqn::method` across its transitive
1116    /// subtypes: the same-named non-abstract method available to each subtype
1117    /// (its own declaration, or one inherited/composed from a parent, trait,
1118    /// or mixin), as `(subtype fqcn, file, name range)`. Subtypes resolving to
1119    /// the same declaring location collapse to a single entry.
1120    pub fn indexed_method_implementations(
1121        &self,
1122        class_fqn: &str,
1123        method: &str,
1124        files: &[Arc<str>],
1125    ) -> Vec<(Arc<str>, Arc<str>, crate::Range)> {
1126        use std::panic::AssertUnwindSafe;
1127        let subs = self.indexed_subtype_classes(class_fqn, files, false);
1128        if subs.is_empty() {
1129            return Vec::new();
1130        }
1131        loop {
1132            let attempt = salsa::Cancelled::catch(AssertUnwindSafe(|| {
1133                let db = self.snapshot_db();
1134                let mut out: Vec<(Arc<str>, Arc<str>, crate::Range)> = Vec::new();
1135                for sub in &subs {
1136                    let here = crate::db::Fqcn::from_str(&db, sub.fqcn.as_ref());
1137                    let Some((_, m)) = crate::db::find_method_in_chain(&db, here, method) else {
1138                        continue;
1139                    };
1140                    if m.is_abstract {
1141                        continue;
1142                    }
1143                    let Some(loc) = m.location.as_ref() else {
1144                        continue;
1145                    };
1146                    let range = self.refine_location_to_name(loc, method);
1147                    out.push((sub.fqcn.clone(), loc.file.clone(), range));
1148                }
1149                out
1150            }));
1151            if let Ok(mut out) = attempt {
1152                out.sort_by(|a, b| a.1.cmp(&b.1).then(a.2.start.line.cmp(&b.2.start.line)));
1153                out.dedup_by(|a, b| a.1 == b.1 && a.2 == b.2);
1154                return out;
1155            }
1156        }
1157    }
1158
1159    /// Commit definitions (class edges + freshness) for every file in `files`
1160    /// that is stale (committed against older text) or that has never been
1161    /// committed and mentions one of `shorts` as a whole identifier.
1162    ///
1163    /// The textual gate answers from the shared per-file mention cache — the
1164    /// same one `indexed_references_to`'s gate populates — so a file scanned
1165    /// by either consumer answers the other with a set lookup instead of an
1166    /// O(text) rescan per BFS round. A file the cache can't answer for is
1167    /// scanned once against the whole name universe and recorded.
1168    fn commit_defs_for_matching(&self, files: &[Arc<str>], shorts: &[String]) {
1169        use std::panic::AssertUnwindSafe;
1170
1171        use rayon::prelude::*;
1172
1173        let committed_any: rustc_hash::FxHashSet<Arc<str>> = {
1174            let guard = self.defs_committed_keys();
1175            guard.into_iter().collect()
1176        };
1177        // Admit the frontier names before preparing, so every needle gets a
1178        // real query (a declared class's short name is already in the
1179        // universe from indexing — admission then changes nothing).
1180        let (queries, mention_scanner) = {
1181            let guard = self.db.salsa.read();
1182            guard.add_literal_mention_names(shorts.iter().map(|s| s.as_str()));
1183            let queries: Vec<_> = shorts
1184                .iter()
1185                .filter_map(|s| guard.prepare_class_mention_query(s))
1186                .collect();
1187            (queries, guard.class_mention_scanner())
1188        };
1189        // Admission guarantees a query per needle and a non-empty universe;
1190        // anything else is defensive — the gate then admits every candidate
1191        // (recommit rather than skip, the conservative direction).
1192        let use_mentions = queries.len() == shorts.len() && mention_scanner.is_some();
1193        type Work = (Arc<str>, Arc<str>, Vec<crate::db::SubtypeEntry>);
1194        type MentionScanRec = (Arc<str>, Arc<str>, Box<[mir_types::Name]>);
1195        let (work, scanned): (Vec<Work>, Vec<MentionScanRec>) = loop {
1196            let attempt = salsa::Cancelled::catch(AssertUnwindSafe(|| {
1197                let db_main = self.snapshot_db();
1198                files
1199                    .par_iter()
1200                    .map_with(db_main, |db, path| {
1201                        let Some(sf) = db.lookup_source_file(path.as_ref()) else {
1202                            return (None, None);
1203                        };
1204                        let text = sf.text(&*db as &dyn MirDatabase).clone();
1205                        if self.is_defs_committed(path.as_ref(), &text) {
1206                            return (None, None);
1207                        }
1208                        // Never-committed files must mention a frontier name;
1209                        // stale (previously committed) files recommit
1210                        // unconditionally — their classes may have re-parented.
1211                        let mut scan_rec: Option<MentionScanRec> = None;
1212                        if use_mentions && !committed_any.contains(path.as_ref()) {
1213                            let mut answer = Some(false);
1214                            for q in &queries {
1215                                match db.class_mention_answer(path.as_ref(), q, &text) {
1216                                    Some(true) => {
1217                                        answer = Some(true);
1218                                        break;
1219                                    }
1220                                    Some(false) => {}
1221                                    None => answer = None,
1222                                }
1223                            }
1224                            let hit = match answer {
1225                                Some(hit) => hit,
1226                                None => {
1227                                    // Uncoverable entry: one scan answers
1228                                    // every query and is recorded below.
1229                                    let scanner = mention_scanner.as_ref().unwrap();
1230                                    let names = scanner.scan(&text);
1231                                    let hit = queries
1232                                        .iter()
1233                                        .any(|q| names.binary_search(&q.name).is_ok());
1234                                    scan_rec = Some((path.clone(), text.clone(), names));
1235                                    hit
1236                                }
1237                            };
1238                            if !hit {
1239                                return (None, scan_rec);
1240                            }
1241                        }
1242                        let defs =
1243                            crate::db::collect_file_definitions(&*db as &dyn MirDatabase, sf);
1244                        let entries = crate::db::subtype_index::entries_from_slice(&defs.slice);
1245                        (Some((path.clone(), text, entries)), scan_rec)
1246                    })
1247                    .collect::<Vec<_>>()
1248            }));
1249            if let Ok(v) = attempt {
1250                let mut work = Vec::new();
1251                let mut scanned = Vec::new();
1252                for (w, rec) in v {
1253                    if let Some(w) = w {
1254                        work.push(w);
1255                    }
1256                    if let Some(rec) = rec {
1257                        scanned.push(rec);
1258                    }
1259                }
1260                break (work, scanned);
1261            }
1262        };
1263        // Record the fallback scans regardless of hit/miss: each is a
1264        // complete, current mention set for its file, so the next round's
1265        // (and the references gate's) checks become set lookups.
1266        if let Some(scanner) = &mention_scanner {
1267            if !scanned.is_empty() {
1268                let guard = self.db.salsa.read();
1269                for (file, text, names) in scanned {
1270                    guard.set_file_class_mentions(&file, &text, scanner.epoch(), names);
1271                }
1272            }
1273        }
1274        if work.is_empty() {
1275            return;
1276        }
1277        let guard = self.db.salsa.read();
1278        for (file, text, entries) in &work {
1279            guard.set_file_class_edges(file, entries.clone());
1280            self.mark_defs_committed(file, text);
1281        }
1282    }
1283
1284    /// Declaration name span for a global constant. Constant slices carry no
1285    /// stored location, so this finds the declaring file via the workspace
1286    /// constants index and locates the `const NAME` / `define('NAME'` token
1287    /// textually.
1288    fn global_constant_decl_range(&self, fqn: &str) -> Option<(Arc<str>, crate::Range)> {
1289        use std::panic::AssertUnwindSafe;
1290        let short = crate::db::subtype_index::short_name_of(fqn).to_string();
1291        salsa::Cancelled::catch(AssertUnwindSafe(|| {
1292            let db = self.snapshot_db();
1293            let index = crate::db::workspace_index(&db);
1294            let loc = index.constant_loc(mir_types::Name::from(fqn.trim_start_matches('\\')))?;
1295            let file = loc.file().path(&db).clone();
1296            let sf = db.lookup_source_file(file.as_ref())?;
1297            let text = sf.text(&db as &dyn MirDatabase);
1298            for (idx, line) in text.lines().enumerate() {
1299                let trimmed = line.trim_start();
1300                let is_decl_line = trimmed.starts_with("const ")
1301                    || trimmed.contains("define(")
1302                    || trimmed.contains("define (");
1303                if !is_decl_line {
1304                    continue;
1305                }
1306                if let Some(col) = identifier_char_col(line, &short, 0, false) {
1307                    let n = short.chars().count() as u32;
1308                    return Some((file, span_range(idx as u32 + 1, col, col + n)));
1309                }
1310            }
1311            None
1312        }))
1313        .ok()
1314        .flatten()
1315    }
1316
1317    /// Class-level issues (inheritance violations, abstract-method gaps, override
1318    /// incompatibilities) for the given set of files.
1319    ///
1320    /// These checks are cross-file by nature and are not emitted by
1321    /// [`crate::FileAnalyzer::analyze`]. Call this after ingesting or
1322    /// re-analyzing a file and its dependents to get the full diagnostic picture.
1323    ///
1324    /// Circular-inheritance checks always run against the full workspace graph
1325    /// regardless of the `files` filter — a cycle is a workspace-wide problem.
1326    pub fn class_issues(&self, files: &[Arc<str>]) -> Vec<crate::Issue> {
1327        self.settle_workspace_index();
1328        let db = self.snapshot_db();
1329        let file_set: HashSet<Arc<str>> = files.iter().cloned().collect();
1330        // Read source texts through the snapshot already in hand — calling
1331        // `source_of` here would re-enter the session RwLock while this
1332        // snapshot is live, and a concurrent salsa write (which blocks new
1333        // readers behind the fair write lock while waiting for existing
1334        // snapshots to drop) turns that into a deadlock.
1335        let file_data: Vec<(Arc<str>, Arc<str>)> = files
1336            .iter()
1337            .filter_map(|f| {
1338                let sf = db.lookup_source_file(f)?;
1339                Some((
1340                    f.clone(),
1341                    sf.text(&db as &dyn crate::db::MirDatabase).clone(),
1342                ))
1343            })
1344            .collect();
1345        crate::class::ClassAnalyzer::with_files(&db, file_set, &file_data).analyze_all()
1346    }
1347
1348    /// Collector-phase issues (e.g. `BackedEnumCaseTypeMismatch`,
1349    /// `InvalidReadonlyPropertyDeclaration`, `InvalidDocblock`, and raw parse
1350    /// errors) for the given files.
1351    ///
1352    /// These are found while building a file's declaration slice
1353    /// ([`crate::db::collect_file_definitions`]), before body analysis or
1354    /// cross-file class checks ever run — neither [`crate::FileAnalyzer::analyze`]
1355    /// nor [`Self::class_issues`] reads them, so a caller merging just those
1356    /// two sources silently drops every collector-time diagnostic. Call this
1357    /// alongside them to get the full picture.
1358    ///
1359    /// A plain snapshot read through [`crate::db::collect_file_definitions`],
1360    /// same as [`Self::document_symbols`] — correct regardless of which path
1361    /// put the file's text into the db (`ingest_file`, `set_file_text`, lazy
1362    /// vendor load) or how many times. The parse-cache fast paths behind that
1363    /// query used to zero out `issues` on any hit, including re-collecting
1364    /// the *same* file after its salsa memo was invalidated; they now
1365    /// preserve (and, for a genuinely different file sharing content,
1366    /// re-point) the originally-computed issues instead.
1367    pub fn collector_issues(&self, files: &[Arc<str>]) -> Vec<crate::Issue> {
1368        let db = self.snapshot_db();
1369        files
1370            .iter()
1371            .filter_map(|f| db.lookup_source_file(f))
1372            .flat_map(|sf| {
1373                crate::db::collect_file_definitions(&db, sf)
1374                    .issues
1375                    .as_ref()
1376                    .clone()
1377            })
1378            .collect()
1379    }
1380
1381    /// All declarations defined in `file` as a **hierarchical tree**.
1382    ///
1383    /// Classes/interfaces/traits/enums are returned with their methods,
1384    /// properties, and constants nested in `children`. Top-level functions
1385    /// and constants are returned with empty `children`.
1386    pub fn document_symbols(&self, file: &str) -> Vec<crate::symbol::DocumentSymbol> {
1387        use crate::symbol::{DeclarationKind, DocumentSymbol};
1388
1389        let db = self.snapshot_db();
1390        let Some(sf) = db.lookup_source_file(file) else {
1391            return Vec::new();
1392        };
1393        let defs = crate::db::collect_file_definitions(&db, sf);
1394        let mut out: Vec<DocumentSymbol> = Vec::new();
1395
1396        let class_children = |methods: &mir_codebase::definitions::MemberMap<
1397            Arc<mir_codebase::definitions::MethodDef>,
1398        >,
1399                              props: Option<
1400            &mir_codebase::definitions::MemberMap<mir_codebase::definitions::PropertyDef>,
1401        >,
1402                              consts: &mir_codebase::definitions::MemberMap<
1403            mir_codebase::definitions::ConstantDef,
1404        >,
1405                              is_enum: bool|
1406         -> Vec<DocumentSymbol> {
1407            let mut out: Vec<DocumentSymbol> = Vec::new();
1408            for (_, m) in methods.iter() {
1409                out.push(DocumentSymbol {
1410                    name: m.name.clone(),
1411                    kind: DeclarationKind::Method,
1412                    location: m.location.clone(),
1413                    children: Vec::new(),
1414                });
1415            }
1416            if let Some(props) = props {
1417                for (_, p) in props.iter() {
1418                    out.push(DocumentSymbol {
1419                        name: p.name.clone(),
1420                        kind: DeclarationKind::Property,
1421                        location: p.location.clone(),
1422                        children: Vec::new(),
1423                    });
1424                }
1425            }
1426            let const_kind = if is_enum {
1427                DeclarationKind::EnumCase
1428            } else {
1429                DeclarationKind::Constant
1430            };
1431            for (_, c) in consts.iter() {
1432                out.push(DocumentSymbol {
1433                    name: c.name.clone(),
1434                    kind: const_kind,
1435                    location: c.location.clone(),
1436                    children: Vec::new(),
1437                });
1438            }
1439            out
1440        };
1441
1442        for c in defs.slice.classes.iter() {
1443            out.push(DocumentSymbol {
1444                name: c.fqcn.clone(),
1445                kind: DeclarationKind::Class,
1446                location: c.location.clone(),
1447                children: class_children(
1448                    &c.own_methods,
1449                    Some(&c.own_properties),
1450                    &c.own_constants,
1451                    false,
1452                ),
1453            });
1454        }
1455        for i in defs.slice.interfaces.iter() {
1456            out.push(DocumentSymbol {
1457                name: i.fqcn.clone(),
1458                kind: DeclarationKind::Interface,
1459                location: i.location.clone(),
1460                children: class_children(&i.own_methods, None, &i.own_constants, false),
1461            });
1462        }
1463        for t in defs.slice.traits.iter() {
1464            out.push(DocumentSymbol {
1465                name: t.fqcn.clone(),
1466                kind: DeclarationKind::Trait,
1467                location: t.location.clone(),
1468                children: class_children(
1469                    &t.own_methods,
1470                    Some(&t.own_properties),
1471                    &t.own_constants,
1472                    false,
1473                ),
1474            });
1475        }
1476        for e in defs.slice.enums.iter() {
1477            let mut children = class_children(&e.own_methods, None, &e.own_constants, true);
1478            for (_, case) in e.cases.iter() {
1479                children.push(DocumentSymbol {
1480                    name: case.name.clone(),
1481                    kind: DeclarationKind::EnumCase,
1482                    location: case.location.clone(),
1483                    children: Vec::new(),
1484                });
1485            }
1486            out.push(DocumentSymbol {
1487                name: e.fqcn.clone(),
1488                kind: DeclarationKind::Enum,
1489                location: e.location.clone(),
1490                children,
1491            });
1492        }
1493        for f in defs.slice.functions.iter() {
1494            out.push(DocumentSymbol {
1495                name: f.fqn.clone(),
1496                kind: DeclarationKind::Function,
1497                location: f.location.clone(),
1498                children: Vec::new(),
1499            });
1500        }
1501        for (name, _) in defs.slice.constants.iter() {
1502            out.push(DocumentSymbol {
1503                name: name.clone(),
1504                kind: DeclarationKind::Constant,
1505                location: None,
1506                children: Vec::new(),
1507            });
1508        }
1509        out
1510    }
1511
1512    /// Choose the candidate-admission gate for `symbol`.
1513    ///
1514    /// For a method resolving to a *static* declaration (PHP forbids a
1515    /// static/non-static override mismatch, so it is static everywhere
1516    /// reachable in a valid hierarchy), the member name alone is a sound
1517    /// gate — and drops the owner short name the general needle set ORs in,
1518    /// which on common owner names (Color, Asset, ...) admits most of a
1519    /// large workspace. Every posting-producing static reference spells the
1520    /// member token: `Owner::m()`, inherited `Sub::m()`, `self::`/
1521    /// `static::`/`parent::m()`, aliased `Alias::m()`, an *instance*
1522    /// receiver `$obj::m()` (whose file may never name the class at all —
1523    /// this is what makes requiring an owner-group name unsound), and
1524    /// callable strings `'Owner::m'`. Dynamic member names (`Owner::$m()`)
1525    /// produce no posting, so nothing is lost there.
1526    ///
1527    /// For `__construct` with a known owner, the identifier needle is the
1528    /// owner's short name (`new Cls(` sites never spell the member name and
1529    /// the bare word `__construct` would admit every file *declaring* a
1530    /// constructor), complemented by the raw call tokens `->__construct` /
1531    /// `::__construct`: an explicit re-init `$obj->__construct()` is a real
1532    /// recorded reference whose file may never name the class.
1533    ///
1534    /// Everything else uses the general OR needles
1535    /// ([`reference_gate_needles`]).
1536    fn reference_gate(&self, symbol: &crate::Name) -> ReferenceGate {
1537        if let crate::Name::Method { class, name } = symbol {
1538            if name.as_ref() == "__construct" && !class.is_empty() {
1539                return ReferenceGate {
1540                    idents: reference_gate_needles(symbol),
1541                    raw: vec!["->__construct".to_string(), "::__construct".to_string()],
1542                };
1543            }
1544            if name.as_ref() != "__construct" && !class.is_empty() {
1545                let db = self.snapshot_db();
1546                let here = crate::db::Fqcn::from_str(&db, class.as_ref());
1547                let is_static = crate::db::find_method_in_chain(&db, here, name)
1548                    .map(|(_, m)| m.is_static)
1549                    .unwrap_or(false);
1550                if is_static {
1551                    return ReferenceGate {
1552                        idents: vec![name.to_string()],
1553                        raw: Vec::new(),
1554                    };
1555                }
1556            }
1557        }
1558        ReferenceGate {
1559            idents: reference_gate_needles(symbol),
1560            raw: Vec::new(),
1561        }
1562    }
1563}
1564
1565/// A transitive subtype hit with its declaration name span, as returned by
1566/// [`AnalysisSession::indexed_subtype_classes`].
1567#[derive(Debug, Clone)]
1568pub struct SubtypeClassSite {
1569    /// Display-form FQCN (no leading `\`).
1570    pub fqcn: Arc<str>,
1571    pub kind: crate::db::ClassLikeKind,
1572    pub is_abstract: bool,
1573    pub file: Arc<str>,
1574    /// The declared name's own token (1-based line, 0-based char columns).
1575    pub range: crate::Range,
1576}
1577
1578/// Build a [`crate::Range`] on one line from mir's native coordinates
1579/// (1-based line, 0-based columns).
1580fn span_range(line: u32, col_start: u32, col_end: u32) -> crate::Range {
1581    crate::Range {
1582        start: crate::Position {
1583            line,
1584            column: col_start,
1585        },
1586        end: crate::Position {
1587            line,
1588            column: col_end,
1589        },
1590    }
1591}
1592
1593/// Char column of the first word-boundary occurrence of `needle` in `line`
1594/// at or after char column `min_col`. Columns are code points, matching the
1595/// collector's `Location` convention.
1596fn identifier_char_col(
1597    line: &str,
1598    needle: &str,
1599    min_col: usize,
1600    case_insensitive: bool,
1601) -> Option<u32> {
1602    if needle.is_empty() {
1603        return None;
1604    }
1605    let is_ident = |c: char| c.is_ascii_alphanumeric() || c == '_';
1606    let chars: Vec<char> = line.chars().collect();
1607    let needle_chars: Vec<char> = needle.chars().collect();
1608    let n = needle_chars.len();
1609    if chars.len() < n {
1610        return None;
1611    }
1612    for start in min_col..=chars.len().saturating_sub(n) {
1613        let matches = chars[start..start + n]
1614            .iter()
1615            .zip(needle_chars.iter())
1616            .all(|(a, b)| {
1617                if case_insensitive {
1618                    a.eq_ignore_ascii_case(b)
1619                } else {
1620                    a == b
1621                }
1622            });
1623        if !matches {
1624            continue;
1625        }
1626        let before_ok = start == 0 || !is_ident(chars[start - 1]);
1627        let after = start + n;
1628        let after_ok = after >= chars.len() || !is_ident(chars[after]);
1629        if before_ok && after_ok {
1630            return Some(start as u32);
1631        }
1632    }
1633    None
1634}
1635
1636/// Whether `hay` mentions `needle` as a whole identifier (ASCII word
1637/// boundaries; conservative near multibyte text). ASCII-case-insensitive:
1638/// PHP class, function, and method names are case-insensitive, so `new
1639/// COLOR()` must count as mentioning `Color`; for the case-sensitive kinds
1640/// (constants, properties) folding only widens the candidate superset.
1641///
1642/// Test-only semantic oracle: the production gates (references freshness,
1643/// subtype-BFS defs commit) answer this predicate through the persistent
1644/// `ClassMentionIndex`; the parity test below pins the scanner to these
1645/// exact boundary and case semantics.
1646#[cfg(test)]
1647fn mentions_identifier(hay: &str, needle: &str) -> bool {
1648    let hay = hay.as_bytes();
1649    let needle = needle.as_bytes();
1650    let n = needle.len();
1651    if n == 0 || hay.len() < n {
1652        return false;
1653    }
1654    let is_ident = |b: u8| b.is_ascii_alphanumeric() || b == b'_';
1655    let first = needle[0].to_ascii_lowercase();
1656    for i in 0..=(hay.len() - n) {
1657        if hay[i].to_ascii_lowercase() != first || !hay[i..i + n].eq_ignore_ascii_case(needle) {
1658            continue;
1659        }
1660        if (i == 0 || !is_ident(hay[i - 1])) && (i + n == hay.len() || !is_ident(hay[i + n])) {
1661            return true;
1662        }
1663    }
1664    false
1665}
1666
1667fn short(fqn: &str) -> &str {
1668    fqn.rsplit('\\').next().unwrap_or(fqn)
1669}
1670
1671/// A candidate-file admission predicate for `indexed_references_to`'s
1672/// freshness pass, chosen by [`AnalysisSession::reference_gate`]. A file is
1673/// admitted when its text mentions any of `idents` as a whole identifier
1674/// (word-bounded, ASCII-case-insensitive) OR contains any of `raw` as a
1675/// plain substring (ASCII-case-insensitive, no word bounds — used for
1676/// call-shaped tokens like `->__construct`). A file matching neither can
1677/// hold no posting for the symbol.
1678struct ReferenceGate {
1679    idents: Vec<String>,
1680    raw: Vec<String>,
1681}
1682
1683/// Identifier words whose whole-word presence in a file's text is necessary
1684/// for the file to hold any posting [`AnalysisSession::indexed_references_to`]
1685/// can return for `symbol`. Member symbols include the owner class's short
1686/// name alongside the member name: `__construct` postings are recorded at
1687/// `new Cls(` sites, which never spell the member name.
1688fn reference_gate_needles(symbol: &crate::Name) -> Vec<String> {
1689    let mut needles = match symbol {
1690        crate::Name::Class(f) | crate::Name::Function(f) | crate::Name::GlobalConstant(f) => {
1691            vec![short(f).to_string()]
1692        }
1693        // `__construct` is invoked only as `new Cls(...)`, `parent::__construct()`,
1694        // or `self::__construct()`/`static::__construct()` from inside a
1695        // subclass — every real call site textually names the class itself
1696        // (directly, or via the enclosing subclass's own `extends`/`use`),
1697        // never the bare word `__construct`. Gating on the class's short name
1698        // alone is exact (no lost call sites) and, unlike the general member
1699        // case, dropping the method-name needle here doesn't reintroduce a
1700        // false negative. This matters: `__construct` is one of the most
1701        // common tokens in any real codebase, so OR-ing it in as a needle
1702        // admits nearly every file as a "must re-analyze" candidate on a
1703        // cold query, defeating the gate's entire purpose for constructors.
1704        crate::Name::Method { class, name } if name.as_ref() == "__construct" => {
1705            if class.is_empty() {
1706                // No class to scope to (owner unknown) — fall back to gating
1707                // on the bare name, same as the general member case below.
1708                vec![name.to_string()]
1709            } else {
1710                vec![short(class).to_string()]
1711            }
1712        }
1713        crate::Name::Method { class, name }
1714        | crate::Name::Property { class, name }
1715        | crate::Name::ClassConstant { class, name } => {
1716            let mut v = vec![name.to_string()];
1717            if !class.is_empty() {
1718                v.push(short(class).to_string());
1719            }
1720            v
1721        }
1722    };
1723    // An empty needle can never match; dropping it keeps the "empty needle
1724    // set disables the gate" contract at the call site conservative.
1725    needles.retain(|n| !n.is_empty());
1726    needles
1727}
1728
1729#[cfg(test)]
1730mod tests {
1731    use super::*;
1732
1733    #[test]
1734    fn mentions_identifier_is_case_insensitive_and_word_bounded() {
1735        assert!(mentions_identifier("$this->save();", "save"));
1736        assert!(mentions_identifier("new COLOR()", "Color"));
1737        assert!(mentions_identifier("use App\\Color as Paint;", "color"));
1738        assert!(!mentions_identifier("$this->saveAll();", "save"));
1739        assert!(!mentions_identifier("return $unsaved;", "save"));
1740        assert!(!mentions_identifier("no occurrence", "save"));
1741        assert!(!mentions_identifier("anything", ""));
1742        // Multibyte neighbors are conservatively treated as boundaries, and
1743        // substring scans must not split codepoints.
1744        assert!(!mentions_identifier("function xÉclairFoo() {}", "Éclair"));
1745        assert!(mentions_identifier("implements Éclair {}", "Éclair"));
1746    }
1747
1748    #[test]
1749    fn mention_scanner_membership_equals_per_needle_scans() {
1750        // The mention index is the sole implementation of the gates' textual
1751        // predicate, so scanner membership must equal the reference
1752        // per-needle predicate for every (hay, needle) pair — same boundary
1753        // and case semantics.
1754        use crate::db::MentionScanner;
1755        use std::sync::Arc;
1756        let universe = ["Color", "save", "ColorPicker", "Éclair", "C1", "_Wrap"];
1757        let names: Vec<(mir_types::Name, bool)> = universe
1758            .iter()
1759            .map(|s| (mir_types::Name::new(s).ascii_lowercase(), false))
1760            .collect();
1761        let scanner = Arc::new(MentionScanner::build(1, names).unwrap());
1762        let hays = [
1763            "$this->save();",
1764            "new COLOR()",
1765            "use App\\Color as Paint;",
1766            "$this->saveAll();",
1767            "return $unsaved;",
1768            "new ColorPicker(); Color::save();",
1769            "function xÉclairFoo() {}",
1770            "implements Éclair {}",
1771            "colorsave savecolor color_save",
1772            "class C1 extends _Wrap {}",
1773            "",
1774        ];
1775        for hay in hays {
1776            let scanned = scanner.scan(hay);
1777            for needle in universe {
1778                let expected = mentions_identifier(hay, needle);
1779                let name = mir_types::Name::new(needle).ascii_lowercase();
1780                assert_eq!(
1781                    scanned.binary_search(&name).is_ok(),
1782                    expected,
1783                    "needle {needle:?} on {hay:?}"
1784                );
1785            }
1786        }
1787    }
1788
1789    #[test]
1790    fn gate_needles_cover_member_and_owner_class() {
1791        // A regular member (non-constructor) gates on both the member name
1792        // and the owner's short name — a call site may name only one.
1793        let n = reference_gate_needles(&crate::Name::method("App\\Job", "run"));
1794        assert!(n.contains(&"run".to_string()) && n.contains(&"Job".to_string()));
1795        let n = reference_gate_needles(&crate::Name::class("App\\Ui\\Color"));
1796        assert_eq!(n, vec!["Color".to_string()]);
1797        // Unknown-owner member symbols still gate on the member name alone.
1798        let n = reference_gate_needles(&crate::Name::method("", "run"));
1799        assert_eq!(n, vec!["run".to_string()]);
1800    }
1801
1802    #[test]
1803    fn gate_needles_for_constructor_scope_to_owner_class_only() {
1804        // `__construct` is only ever spelled at `new Cls(`/`parent::__construct()`
1805        // sites, which always name the class — the bare method-name needle is
1806        // dropped so a cold constructor query doesn't admit nearly every file
1807        // in the workspace (every class defines *some* `__construct`).
1808        let n = reference_gate_needles(&crate::Name::method("App\\Job", "__construct"));
1809        assert_eq!(n, vec!["Job".to_string()]);
1810        // Unknown owner: nothing to scope to, fall back to the bare name.
1811        let n = reference_gate_needles(&crate::Name::method("", "__construct"));
1812        assert_eq!(n, vec!["__construct".to_string()]);
1813    }
1814
1815    fn session_with(files: &[(&str, &str)]) -> crate::AnalysisSession {
1816        let session = crate::AnalysisSession::new(crate::PhpVersion::LATEST);
1817        for (path, text) in files {
1818            session.set_file_text(Arc::from(*path), Arc::from(*text));
1819        }
1820        session
1821    }
1822
1823    #[test]
1824    fn gate_static_method_is_member_name_only() {
1825        // Regardless of subtypes: the member token alone is the sound gate
1826        // (an instance receiver `$obj::m()` never names the owner), and it
1827        // is also the selective part — the owner short name would only
1828        // widen the admitted set.
1829        let session = session_with(&[
1830            (
1831                "owner.php",
1832                "<?php\nclass Owner { public static function m(): void {} }\n",
1833            ),
1834            ("sub.php", "<?php\nclass Sub extends Owner {}\n"),
1835        ]);
1836        let gate = session.reference_gate(&crate::Name::method("Owner", "m"));
1837        assert_eq!(gate.idents, vec!["m".to_string()]);
1838        assert!(gate.raw.is_empty());
1839    }
1840
1841    #[test]
1842    fn gate_instance_method_keeps_general_needles() {
1843        let session = session_with(&[(
1844            "owner.php",
1845            "<?php\nclass Owner { public function m(): void {} }\n",
1846        )]);
1847        let gate = session.reference_gate(&crate::Name::method("Owner", "m"));
1848        assert_eq!(
1849            gate.idents,
1850            reference_gate_needles(&crate::Name::method("Owner", "m"))
1851        );
1852        assert!(gate.raw.is_empty());
1853    }
1854
1855    #[test]
1856    fn gate_constructor_adds_raw_call_tokens() {
1857        // Owner short name for `new Cls(` sites, plus the raw call tokens
1858        // for explicit re-init (`$obj->__construct()`) whose file may never
1859        // name the class. The bare identifier `__construct` must NOT be a
1860        // needle — it would admit every file declaring a constructor.
1861        let session = session_with(&[(
1862            "owner.php",
1863            "<?php\nclass Owner { public function __construct() {} }\n",
1864        )]);
1865        let gate = session.reference_gate(&crate::Name::method("Owner", "__construct"));
1866        assert_eq!(
1867            gate.idents,
1868            reference_gate_needles(&crate::Name::method("Owner", "__construct"))
1869        );
1870        assert_eq!(
1871            gate.raw,
1872            vec!["->__construct".to_string(), "::__construct".to_string()]
1873        );
1874    }
1875
1876    #[test]
1877    fn gate_unresolvable_owner_falls_back_to_general_needles() {
1878        let session = session_with(&[(
1879            "owner.php",
1880            "<?php\nclass Owner { public static function m(): void {} }\n",
1881        )]);
1882        let gate = session.reference_gate(&crate::Name::method("Nonexistent\\Missing", "m"));
1883        assert_eq!(
1884            gate.idents,
1885            reference_gate_needles(&crate::Name::method("Nonexistent\\Missing", "m"))
1886        );
1887        assert!(gate.raw.is_empty());
1888    }
1889}