Skip to main content

mir_analyzer/session/
queries.rs

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