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(&mut 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        &mut 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(&mut 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(&mut 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(&mut 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        &mut 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        &mut 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        &mut 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        &mut 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        &mut 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        &mut 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(&mut 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        &mut 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        &mut 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        &mut 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        use std::panic::AssertUnwindSafe;
551
552        let key = symbol.codebase_key();
553
554        // Freshness pass: candidates whose postings are not exact for their
555        // current text. Files not registered as `SourceFile` inputs are
556        // skipped. Never-committed files — no commit mark, hence no postings
557        // at all (every mark drop accompanies a posting clear) — are further
558        // gated on their text mentioning the symbol's name: such a file can
559        // neither hold stale postings nor produce new ones, so a cold query
560        // on a common name skips the bulk of the workspace instead of
561        // analyzing it. A LIVE-analyzed file stale only by generation
562        // (unresolved-name commit, text unchanged since) gets the same gate:
563        // the current text is exactly what this session's own analysis
564        // already scanned, so a needle miss is just as conclusive as for a
565        // never-committed file. Everything else — a genuinely edited file, or
566        // a commit seeded by an unverified disk-cache replay
567        // (`warm_start_files`, never scanned by this session) — re-analyzes
568        // unconditionally: an edited file's old postings are for different
569        // text, and a replayed commit's postings are only as trustworthy as
570        // the cache entry, so neither can be cleared by a textual gate alone.
571        // Same discipline as `commit_defs_for_matching` on the defs index.
572        //
573        let gate = self.reference_gate(symbol);
574        // The whole gate — identifier needles and raw call tokens alike —
575        // answers from the persistent mention index: every needle is admitted
576        // (a declared class-like short name is already in the universe;
577        // member/function names and the two `__construct` call tokens enter
578        // verbatim), so a recorded mention set answers with lookups and only
579        // a never-scanned or since-edited file pays one scan against the
580        // whole universe, recorded for every later consumer (including the
581        // subtype-BFS gate). A needle new to the universe epoch-invalidates
582        // older recordings for itself only — the first query on it rescans
583        // uncovered files once, the same cost the per-query scan paid every
584        // time before.
585        let has_needles = !gate.idents.is_empty() || !gate.raw.is_empty();
586        let (mention_queries, mention_scanner) = if has_needles {
587            let guard = &self.db.salsa;
588            guard.add_literal_mention_names(gate.idents.iter().map(|s| s.as_str()));
589            guard.add_raw_mention_needles(gate.raw.iter().map(|s| s.as_str()));
590            let queries: Vec<_> = gate
591                .idents
592                .iter()
593                .chain(gate.raw.iter())
594                .filter_map(|s| guard.prepare_class_mention_query(s))
595                .collect();
596            (queries, guard.class_mention_scanner())
597        } else {
598            (Vec::new(), None)
599        };
600        // Admission guarantees a query per needle and a non-empty universe;
601        // anything else is defensive — the gate then admits every candidate
602        // (analyze rather than skip, the conservative direction).
603        let gate_complete = mention_queries.len() == gate.idents.len() + gate.raw.len()
604            && mention_scanner.is_some();
605        let committed_any: rustc_hash::FxHashSet<Arc<str>> =
606            self.ref_committed_keys().into_iter().collect();
607        type MentionScanRec = (Arc<str>, Arc<str>, Box<[mir_types::Name]>);
608        let (stale, scanned): (Vec<Arc<str>>, Vec<MentionScanRec>) = loop {
609            if should_cancel() {
610                return None;
611            }
612            let attempt = salsa::Cancelled::catch(AssertUnwindSafe(|| {
613                let current_gen = self.index_generation();
614                let db_main = self.snapshot_db();
615                let mut stale = Vec::new();
616                let mut scanned = Vec::new();
617                // This pass is intentionally serial. Each request already runs
618                // on its caller thread; putting every concurrent request back
619                // onto the shared Rayon pool lets an index batch monopolize the
620                // workers while readers wait without polling `should_cancel`.
621                // The per-file work is mostly cache lookups, and keeping it on
622                // the caller thread makes cancellation responsive under write
623                // contention instead of turning a short LSP deadline into an
624                // unbounded pool wait.
625                for f in files {
626                    let Some(sf) = db_main.lookup_source_file(f.as_ref()) else {
627                        continue;
628                    };
629                    let text = sf.text(&db_main as &dyn MirDatabase);
630                    if self.is_ref_committed(f.as_ref(), text, current_gen) {
631                        continue;
632                    }
633                    if committed_any.contains(f.as_ref())
634                        && !self.ref_commit_stale_by_generation_only(f.as_ref(), text)
635                    {
636                        stale.push(f.clone());
637                        continue;
638                    }
639                    if has_needles && gate_complete {
640                        // Any needle answering `true` admits the file; an
641                        // unanswerable one forces the single recorded scan,
642                        // which settles every needle at once.
643                        let mut answer = Some(false);
644                        for q in &mention_queries {
645                            match db_main.class_mention_answer(f.as_ref(), q, text) {
646                                Some(true) => {
647                                    answer = Some(true);
648                                    break;
649                                }
650                                Some(false) => {}
651                                None => answer = None,
652                            }
653                        }
654                        match answer {
655                            Some(true) => {}
656                            Some(false) => continue,
657                            None => {
658                                let scanner = mention_scanner
659                                    .as_ref()
660                                    .expect("gate_complete implies a scanner");
661                                let names = scanner.scan(text);
662                                let hit = mention_queries
663                                    .iter()
664                                    .any(|q| names.binary_search(&q.name).is_ok());
665                                scanned.push((f.clone(), text.clone(), names));
666                                if hit {
667                                    stale.push(f.clone());
668                                }
669                                continue;
670                            }
671                        }
672                    }
673                    stale.push(f.clone());
674                }
675                Some((stale, scanned))
676            }));
677            match attempt {
678                Ok(Some(v)) => break v,
679                Ok(None) => return None,
680                Err(_) if should_cancel() => return None,
681                Err(_) => {}
682            }
683        };
684
685        // Record the fallback scans regardless of how the query proceeds:
686        // each is a complete, current mention set for its file.
687        if let Some(scanner) = &mention_scanner {
688            if !scanned.is_empty() {
689                let guard = &self.db.salsa;
690                for (file, text, names) in scanned {
691                    guard.set_file_class_mentions(&file, &text, scanner.epoch(), names);
692                }
693            }
694        }
695
696        if !stale.is_empty() {
697            // Replayed postings which are already current answer directly
698            // below. Do not make that read-only path wait for (or consume the
699            // cancellation budget on) unrelated pending symbol-index work:
700            // warm start has already seeded the index needed to interpret its
701            // postings. A stale candidate, on the other hand, is about to
702            // analyze against the workspace, so reconcile first and retain
703            // the cancellable behavior for that potentially expensive work.
704            if !self.settle_workspace_index_cancellable(should_cancel) {
705                return None;
706            }
707            // Phase 1 (serial, no live snapshot held): warm up stale
708            // candidates, retrying a cancelled file in place rather than
709            // restarting the whole query. Parallel variants deadlocked under
710            // `concurrent_reference_cancel`; keep it serial. The bump scope
711            // closes before Phase 2 reads `index_generation`.
712            {
713                let mut session = self.defer_revision_bumps();
714                for path in &stale {
715                    loop {
716                        if should_cancel() {
717                            return None;
718                        }
719                        match salsa::Cancelled::catch(AssertUnwindSafe(|| {
720                            session.prepare_file_for_analysis(path)
721                        })) {
722                            Ok(()) => break,
723                            Err(_) if should_cancel() => return None,
724                            Err(_) => {}
725                        }
726                    }
727                }
728            }
729
730            // Phase 2 (parallel, pure) under a cancellation retry loop, then
731            // a serial commit into both inverted indexes.
732            let (commit_gen, analyzed) = loop {
733                if should_cancel() {
734                    return None;
735                }
736                // Generation before the snapshot: a file add racing the
737                // analysis leaves these commits stale (self-healing on the
738                // next query), never wrongly fresh.
739                let gen = self.index_generation();
740                let attempt = salsa::Cancelled::catch(AssertUnwindSafe(|| {
741                    // Freeze on the pass-scoped snapshot (borrow-only symbol
742                    // lookups + pass-shared subtype cache): all lazy-loading
743                    // finished in Phase 1, and a concurrent index write
744                    // cancels this attempt, so the frozen view is never
745                    // stale. Same discipline as the batch body pass.
746                    let mut db_main = self.snapshot_db();
747                    db_main.freeze_workspace_index();
748                    stale
749                        .iter()
750                        .filter_map(|path| {
751                            let sf = db_main.lookup_source_file(path.as_ref())?;
752                            let text = sf.text(&db_main as &dyn MirDatabase).clone();
753                            let out =
754                                crate::db::analyze_file(&db_main as &dyn MirDatabase, sf).clone();
755                            let defs = crate::db::collect_file_definitions(
756                                &db_main as &dyn MirDatabase,
757                                sf,
758                            );
759                            let entries = crate::db::subtype_index::entries_from_slice(&defs.slice);
760                            // Stage the disk-cache write only when the commit
761                            // below will rewrite postings (see the sweep in
762                            // `reanalyze_file_set` for the cost rationale).
763                            let put = if self.ref_commit_is_current(path.as_ref(), &text, &out) {
764                                None
765                            } else {
766                                self.stage_ref_cache_put(
767                                    &db_main as &dyn MirDatabase,
768                                    sf,
769                                    path.as_ref(),
770                                    &text,
771                                    &out,
772                                )
773                            };
774                            // Mention scan piggybacks on the analysis pass
775                            // (pure; committed serially below), skipped when
776                            // the file already holds a current scan.
777                            let mentions = mention_scanner.as_ref().and_then(|s| {
778                                (!db_main.class_mentions_current(path.as_ref(), &text, s.epoch()))
779                                    .then(|| s.scan(&text))
780                            });
781                            Some((path.clone(), text, out, entries, put, mentions))
782                        })
783                        .collect::<Vec<_>>()
784                }));
785                match attempt {
786                    Ok(v) => break (gen, v),
787                    Err(_) if should_cancel() => return None,
788                    Err(_) => {}
789                }
790            };
791            let mut analyzed = analyzed;
792            let guard = &self.db.salsa;
793            for (file, text, out, entries, put, mentions) in analyzed.iter_mut() {
794                // Pointer-identical memo ⇒ identical postings: skip the
795                // index rewrite and only re-stamp the freshness mark.
796                if !self.ref_commit_is_current(file.as_ref(), text, out) {
797                    let file_no = guard.locked_ref_index().intern_path(file);
798                    guard.set_file_reference_locations(file_no, out.ref_locs.to_vec());
799                }
800                if let (Some(s), Some(m)) = (&mention_scanner, mentions.take()) {
801                    guard.set_file_class_mentions(file, text, s.epoch(), m);
802                }
803                if let Some(put) = put.take() {
804                    self.apply_ref_cache_put(file.as_ref(), out, put);
805                }
806                self.mark_ref_committed(
807                    file,
808                    text,
809                    Some(out),
810                    commit_gen,
811                    !out.has_unresolved_names(),
812                );
813                if !self.is_defs_committed(file.as_ref(), text) {
814                    let file_no = guard.locked_ref_index().intern_path(file);
815                    guard.set_file_class_edges(file_no, entries.clone());
816                    self.mark_defs_committed(file, text);
817                }
818            }
819        }
820
821        // Posting lookup, filtered to the candidate scope.
822        //
823        // Member symbols resolve against the queried class plus its hierarchy
824        // (mir records member refs under the *declaring* class, so a query on
825        // an interface method must include implementor keys and vice versa).
826        // Name-only fallback postings — receivers whose type couldn't be
827        // resolved — are consulted only when the typed keys produce nothing,
828        // mirroring the pre-index two-tier behavior: exact results when
829        // resolution succeeds, by-name matches when nothing resolves.
830        // `__construct` stays exact: `new Sub()` invokes `Sub::__construct`
831        // even when only a parent declares one, so hierarchy fan-out would
832        // wrongly return subtype instantiation sites for a parent query.
833        let hierarchy: Vec<String> = match symbol {
834            crate::Name::Method { class, name } => {
835                if name.as_ref() == "__construct" || class.is_empty() {
836                    if class.is_empty() {
837                        Vec::new()
838                    } else {
839                        vec![class.trim_start_matches('\\').to_string()]
840                    }
841                } else {
842                    self.member_hierarchy_classes(class.as_ref())
843                }
844            }
845            crate::Name::Property { class, .. } | crate::Name::ClassConstant { class, .. } => {
846                if class.is_empty() {
847                    Vec::new()
848                } else {
849                    self.member_hierarchy_classes(class.as_ref())
850                }
851            }
852            _ => Vec::new(),
853        };
854        let scope: rustc_hash::FxHashSet<&str> = files.iter().map(|f| f.as_ref()).collect();
855        let read_symbol_key = |symbol_key: &str| -> Vec<(Arc<str>, crate::Range)> {
856            let guard = &self.db.salsa;
857            guard
858                .reference_locations(symbol_key)
859                .into_iter()
860                .filter(|(file, ..)| scope.contains(file.as_ref()))
861                .map(|(file, line, col_start, col_end)| {
862                    (file, span_range(line, col_start as u32, col_end as u32))
863                })
864                .collect()
865        };
866        let mut scratch_key = String::new();
867        let mut read_composed_key = |prefix: &str, middle: &str, separator: &str, suffix: &str| {
868            scratch_key.clear();
869            scratch_key.reserve(prefix.len() + middle.len() + separator.len() + suffix.len());
870            scratch_key.push_str(prefix);
871            scratch_key.push_str(middle);
872            scratch_key.push_str(separator);
873            scratch_key.push_str(suffix);
874            read_symbol_key(&scratch_key)
875        };
876        let mut out: Vec<(Arc<str>, crate::Range)> = Vec::new();
877        let mut append_plain = || match symbol {
878            crate::Name::Method { name, .. } => {
879                for class in &hierarchy {
880                    out.extend(read_composed_key(
881                        "meth:",
882                        class.as_ref(),
883                        "::",
884                        name.as_ref(),
885                    ));
886                }
887            }
888            crate::Name::Property { name, .. } => {
889                for class in &hierarchy {
890                    out.extend(read_composed_key(
891                        "prop:",
892                        class.as_ref(),
893                        "::",
894                        name.as_ref(),
895                    ));
896                }
897            }
898            crate::Name::ClassConstant { name, .. } => {
899                for class in &hierarchy {
900                    out.extend(read_composed_key(
901                        "cnst:",
902                        class.as_ref(),
903                        "::",
904                        name.as_ref(),
905                    ));
906                }
907            }
908            _ => out.extend(read_symbol_key(key.as_str())),
909        };
910        match includes {
911            crate::ReferenceIncludes::Plain => append_plain(),
912            crate::ReferenceIncludes::UseImports => {
913                out.extend(read_composed_key("use:", key.as_str(), "", ""));
914            }
915            crate::ReferenceIncludes::PlainAndUseImports => {
916                append_plain();
917                out.extend(read_composed_key("use:", key.as_str(), "", ""));
918            }
919        }
920        if matches!(includes, crate::ReferenceIncludes::Plain) && out.is_empty() {
921            match symbol {
922                crate::Name::Method { name, .. } => {
923                    out = read_composed_key("methname:", name.as_ref(), "", "");
924                }
925                crate::Name::Property { name, .. } => {
926                    out = read_composed_key("propname:", name.as_ref(), "", "");
927                }
928                _ => {}
929            }
930        }
931        out.sort_by(|a, b| {
932            a.0.cmp(&b.0)
933                .then(a.1.start.line.cmp(&b.1.start.line))
934                .then(a.1.start.column.cmp(&b.1.start.column))
935        });
936        out.dedup_by(|a, b| a.0 == b.0 && a.1 == b.1);
937
938        if include_declaration {
939            // Declaration lookup runs salsa queries (and may lazy-load); a
940            // concurrent write cancels it — declarations are then simply
941            // omitted rather than failing the whole request.
942            let decls: Vec<(Arc<str>, crate::Range)> = match symbol {
943                crate::Name::Method { class, .. }
944                | crate::Name::Property { class, .. }
945                | crate::Name::ClassConstant { class, .. } => {
946                    if class.is_empty() {
947                        // Unknown owner: declarations by name, recorded as
948                        // `methdecl:`/`propdecl:`/`cnstdecl:` postings during
949                        // class/trait/interface/enum analysis.
950                        match symbol {
951                            crate::Name::Method { name, .. } => {
952                                read_composed_key("methdecl:", name.as_ref(), "", "")
953                            }
954                            crate::Name::Property { name, .. } => {
955                                read_composed_key("propdecl:", name.as_ref(), "", "")
956                            }
957                            crate::Name::ClassConstant { name, .. } => {
958                                read_composed_key("cnstdecl:", name.as_ref(), "", "")
959                            }
960                            _ => Vec::new(),
961                        }
962                    } else {
963                        salsa::Cancelled::catch(AssertUnwindSafe(|| {
964                            self.member_decl_sites(&hierarchy, symbol)
965                        }))
966                        .unwrap_or_default()
967                    }
968                }
969                _ => salsa::Cancelled::catch(AssertUnwindSafe(|| {
970                    self.declaration_name_range(symbol).into_iter().collect()
971                }))
972                .unwrap_or_default(),
973            };
974            for (file, range) in decls {
975                if scope.contains(file.as_ref())
976                    && !out.iter().any(|(f, r)| *f == file && *r == range)
977                {
978                    out.push((file, range));
979                }
980            }
981        }
982        Some(out)
983    }
984
985    /// The queried class plus every class its members' references could be
986    /// keyed under: resolved ancestors (a call on a subtype instance records
987    /// the declaring ancestor) and transitive subtypes including trait users
988    /// (a call on a subtype that overrides records the subtype). Display-form
989    /// FQCNs, deduplicated case-insensitively.
990    fn member_hierarchy_classes(&self, class_fqn: &str) -> Vec<String> {
991        use std::panic::AssertUnwindSafe;
992        let target = class_fqn.trim_start_matches('\\').to_string();
993        let mut out: Vec<String> = vec![target.clone()];
994        let ancestors = salsa::Cancelled::catch(AssertUnwindSafe(|| {
995            let db = self.snapshot_db();
996            let here = crate::db::Fqcn::from_str(&db, &target);
997            crate::db::class_ancestors_by_fqcn(&db, here)
998                .iter()
999                .skip(1)
1000                .map(|a| a.trim_start_matches('\\').to_string())
1001                .collect::<Vec<_>>()
1002        }))
1003        .unwrap_or_default();
1004        out.extend(ancestors);
1005        let subs = {
1006            let guard = &self.db.salsa;
1007            guard.subtype_sites_of(&target, true)
1008        };
1009        out.extend(
1010            subs.into_iter()
1011                .map(|s| s.fqcn.trim_start_matches('\\').to_string()),
1012        );
1013        let mut seen: rustc_hash::FxHashSet<String> = rustc_hash::FxHashSet::default();
1014        out.retain(|c| seen.insert(c.to_ascii_lowercase()));
1015        out
1016    }
1017
1018    /// Own-member declaration sites for `symbol` across `classes`: each class
1019    /// that itself declares the member (not inherited) contributes its name
1020    /// token. Kind-specific lookups — a class often declares a property and a
1021    /// method with the same short name, and `member_location` can't tell them
1022    /// apart.
1023    fn member_decl_sites(
1024        &self,
1025        classes: &[String],
1026        symbol: &crate::Name,
1027    ) -> Vec<(Arc<str>, crate::Range)> {
1028        let mut out: Vec<(Arc<str>, crate::Range)> = Vec::new();
1029        let db = self.snapshot_db();
1030        for class in classes {
1031            let here = crate::db::Fqcn::from_str(&db, class);
1032            let (loc, needle) = match symbol {
1033                crate::Name::Method { name, .. } => {
1034                    let Some(m) = crate::db::find_method_in_class(&db, here, name) else {
1035                        continue;
1036                    };
1037                    (m.location.clone(), name.to_string())
1038                }
1039                crate::Name::Property { name, .. } => {
1040                    let Some(p) = crate::db::find_property_in_class(&db, here, name) else {
1041                        continue;
1042                    };
1043                    (p.location.clone(), name.to_string())
1044                }
1045                crate::Name::ClassConstant { name, .. } => {
1046                    let Some(c) = crate::db::find_class_constant_in_class(&db, here, name) else {
1047                        continue;
1048                    };
1049                    (c.location.clone(), name.to_string())
1050                }
1051                _ => continue,
1052            };
1053            let Some(loc) = loc else { continue };
1054            let range = self.refine_location_to_name(&loc, &needle);
1055            out.push((loc.file.clone(), range));
1056        }
1057        out
1058    }
1059
1060    /// The symbol's declaration site, narrowed from the collector's
1061    /// whole-declaration span to the declared name's own token (matching the
1062    /// span shape of recorded references).
1063    pub fn declaration_name_range(
1064        &mut self,
1065        symbol: &crate::Name,
1066    ) -> Option<(Arc<str>, crate::Range)> {
1067        if let crate::Name::GlobalConstant(fqn) = symbol {
1068            return self.global_constant_decl_range(fqn);
1069        }
1070        let loc = self.definition_of(symbol).ok()?;
1071        let short = match symbol {
1072            crate::Name::Class(f) | crate::Name::Function(f) | crate::Name::GlobalConstant(f) => {
1073                crate::db::subtype_index::short_name_of(f)
1074            }
1075            crate::Name::Method { name, .. }
1076            | crate::Name::Property { name, .. }
1077            | crate::Name::ClassConstant { name, .. } => name.as_ref(),
1078        };
1079        // Property declarations carry a `$` sigil in source, but reference
1080        // ranges cover the bare name; the word-boundary search below lands on
1081        // the name right after the sigil.
1082        let file = loc.file.clone();
1083        let range = self.refine_location_to_name(&loc, short);
1084        Some((file, range))
1085    }
1086
1087    /// Narrow a whole-declaration [`mir_types::Location`] to the first
1088    /// word-boundary occurrence of `needle` inside its line span. Falls back
1089    /// to the location's own coordinates when the text is unavailable or the
1090    /// name doesn't appear (e.g. stub-only declarations).
1091    fn refine_location_to_name(&self, loc: &mir_types::Location, needle: &str) -> crate::Range {
1092        let fallback = span_range(loc.line, loc.col_start as u32, loc.col_end as u32);
1093        let text = {
1094            let db = self.snapshot_db();
1095            db.lookup_source_file(loc.file.as_ref())
1096                .map(|sf| sf.text(&db as &dyn MirDatabase).clone())
1097        };
1098        let Some(text) = text else {
1099            return fallback;
1100        };
1101        let needle_chars = needle.chars().count() as u32;
1102        let first_line = loc.line.saturating_sub(1) as usize;
1103        // Exact-case first: PHP property/constant names are case-sensitive
1104        // and an early case-insensitive hit can land on an unrelated token
1105        // (a type hint sharing the name). Case-insensitive second, for
1106        // method/class needles that arrive lowercase-normalized.
1107        for case_insensitive in [false, true] {
1108            for (idx, line_text) in text.lines().enumerate().skip(first_line) {
1109                let line_no = idx as u32 + 1;
1110                if line_no > loc.line_end {
1111                    break;
1112                }
1113                let min_col = if line_no == loc.line {
1114                    loc.col_start as usize
1115                } else {
1116                    0
1117                };
1118                if let Some(col) = identifier_char_col(line_text, needle, min_col, case_insensitive)
1119                {
1120                    return span_range(line_no, col, col + needle_chars);
1121                }
1122            }
1123        }
1124        fallback
1125    }
1126
1127    /// Transitive subtypes of `class_fqn` (classes/interfaces/enums whose
1128    /// resolved ancestor chain reaches it), answered from the maintained
1129    /// subtype edge index.
1130    ///
1131    /// `files` is the host's candidate scope for the on-demand completeness
1132    /// pass: per BFS round, not-yet-committed files whose text mentions a
1133    /// frontier short name get their definitions committed, so results are
1134    /// complete even before a background sweep has covered the workspace.
1135    /// That short-name gate is only candidate discovery; subtype identity is
1136    /// still resolved from the edge index below using the exact canonical
1137    /// FQCN.
1138    /// Committed files answer from the index with no parsing at all.
1139    ///
1140    /// `include_trait_users` also counts `use Trait;` composition as a
1141    /// subtype edge (visibility-scoping semantics); leave it off for
1142    /// goto-implementation semantics (extends/implements only).
1143    ///
1144    /// Memoized per `(class_fqn, include_trait_users, files, text_revision)`
1145    /// — same shape and rationale as [`Self::indexed_references_to`]'s
1146    /// cache: `commit_defs_for_matching`'s freshness pass costs O(candidates)
1147    /// on every call regardless of outcome, so a repeat query (e.g. a host
1148    /// resolving a protected/static method's reference scope on every
1149    /// code-lens refresh) would otherwise re-pay it every time.
1150    pub fn indexed_subtype_classes(
1151        &mut self,
1152        class_fqn: &str,
1153        files: &[Arc<str>],
1154        include_trait_users: bool,
1155    ) -> Vec<SubtypeClassSite> {
1156        let cache_key = SubtypeQueryCacheKey {
1157            class_fqn: class_fqn.trim_start_matches('\\').to_ascii_lowercase(),
1158            include_trait_users,
1159            generation: self.query_cache_generation(),
1160            files_hash: hash_files(files),
1161        };
1162        if let Some(cached) = self.subtype_query_cache.read().get(&cache_key) {
1163            self.subtype_query_cache_hits
1164                .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
1165            return (**cached).clone();
1166        }
1167        let result = self.indexed_subtype_classes_uncached(class_fqn, files, include_trait_users);
1168        if self.query_cache_generation() != cache_key.generation {
1169            // The generation moved while computing (an edit, or a defs
1170            // commit growing the subtype index — possibly this query's own).
1171            // The key can never be looked up again, so don't cache it; the
1172            // next identical query recomputes once against settled state
1173            // and caches then.
1174            return result;
1175        }
1176        let mut cache = self.subtype_query_cache.write();
1177        if !cache.advance_to(cache_key.generation, || {
1178            self.subtype_query_cache_sites
1179                .store(0, std::sync::atomic::Ordering::Relaxed);
1180        }) {
1181            return result;
1182        }
1183        let new_len = result.len();
1184        let prior = self
1185            .subtype_query_cache_sites
1186            .fetch_add(new_len, std::sync::atomic::Ordering::Relaxed);
1187        if prior + new_len > SUBTYPE_QUERY_CACHE_SITE_CAP {
1188            cache.map.clear();
1189            self.subtype_query_cache_sites
1190                .store(new_len, std::sync::atomic::Ordering::Relaxed);
1191        }
1192        cache.map.insert(cache_key, Arc::new(result.clone()));
1193        result
1194    }
1195
1196    /// Uncached implementation of [`Self::indexed_subtype_classes`]. Callers
1197    /// should use the memoizing wrapper.
1198    fn indexed_subtype_classes_uncached(
1199        &mut self,
1200        class_fqn: &str,
1201        files: &[Arc<str>],
1202        include_trait_users: bool,
1203    ) -> Vec<SubtypeClassSite> {
1204        self.settle_workspace_index();
1205        let mut scanned: rustc_hash::FxHashSet<String> = rustc_hash::FxHashSet::default();
1206        let mut pending: Vec<String> = vec![class_fqn.trim_start_matches('\\').to_string()];
1207        let mut sites: Vec<crate::db::SubtypeSite> = Vec::new();
1208        while !pending.is_empty() {
1209            // Use short names only to discover stale/uncommitted files worth
1210            // collecting. The query result itself comes from the subtype
1211            // edge index (`subtype_sites_of`) below.
1212            let needles: Vec<String> = pending
1213                .drain(..)
1214                .filter(|f| scanned.insert(f.clone()))
1215                .map(|f| crate::db::subtype_index::short_name_of(&f).to_string())
1216                .collect();
1217            if !needles.is_empty() {
1218                self.commit_defs_for_matching(files, &needles);
1219            }
1220            sites = {
1221                let guard = &self.db.salsa;
1222                guard.subtype_sites_of(class_fqn, include_trait_users)
1223            };
1224            pending = sites
1225                .iter()
1226                .map(|s| s.fqcn.trim_start_matches('\\').to_string())
1227                .filter(|f| !scanned.contains(f))
1228                .collect();
1229        }
1230        let mut out: Vec<SubtypeClassSite> = sites
1231            .into_iter()
1232            .filter_map(|s| {
1233                let loc = s.location.as_ref()?;
1234                let short = crate::db::subtype_index::short_name_of(&s.fqcn).to_string();
1235                let range = self.refine_location_to_name(loc, &short);
1236                Some(SubtypeClassSite {
1237                    fqcn: s.fqcn,
1238                    kind: s.kind,
1239                    is_abstract: s.is_abstract,
1240                    file: s.file,
1241                    range,
1242                })
1243            })
1244            .collect();
1245        // Anonymous classes never reach the definition collector; their
1246        // `new class implements X {}` sites are recorded under the resolved
1247        // canonical parent FQCN during body analysis.
1248        let root_lc = class_fqn.trim_start_matches('\\').to_ascii_lowercase();
1249        let scope: rustc_hash::FxHashSet<&str> = files.iter().map(|f| f.as_ref()).collect();
1250        let anon: Vec<(Arc<str>, u32, u16, u16)> = {
1251            let guard = &self.db.salsa;
1252            let mut key = String::with_capacity("impl:".len() + root_lc.len());
1253            key.push_str("impl:");
1254            key.push_str(&root_lc);
1255            guard.reference_locations(&key)
1256        };
1257        for (file, line, cs, ce) in anon {
1258            if !scope.contains(file.as_ref()) {
1259                continue;
1260            }
1261            let range = span_range(line, cs as u32, ce as u32);
1262            if out.iter().any(|s| s.file == file && s.range == range) {
1263                continue;
1264            }
1265            out.push(SubtypeClassSite {
1266                fqcn: Arc::from("class@anonymous"),
1267                kind: crate::db::ClassLikeKind::Class,
1268                is_abstract: false,
1269                file,
1270                range,
1271            });
1272        }
1273        out
1274    }
1275
1276    /// Concrete implementations of `class_fqn::method` across its transitive
1277    /// subtypes: the same-named non-abstract method available to each subtype
1278    /// (its own declaration, or one inherited/composed from a parent, trait,
1279    /// or mixin), as `(subtype fqcn, file, name range)`. Subtypes resolving to
1280    /// the same declaring location collapse to a single entry.
1281    pub fn indexed_method_implementations(
1282        &mut self,
1283        class_fqn: &str,
1284        method: &str,
1285        files: &[Arc<str>],
1286    ) -> Vec<(Arc<str>, Arc<str>, crate::Range)> {
1287        use std::panic::AssertUnwindSafe;
1288        let subs = self.indexed_subtype_classes(class_fqn, files, false);
1289        if subs.is_empty() {
1290            return Vec::new();
1291        }
1292        loop {
1293            let attempt = salsa::Cancelled::catch(AssertUnwindSafe(|| {
1294                let db = self.snapshot_db();
1295                let mut out: Vec<(Arc<str>, Arc<str>, crate::Range)> = Vec::new();
1296                for sub in &subs {
1297                    let here = crate::db::Fqcn::from_str(&db, sub.fqcn.as_ref());
1298                    let Some((_, m)) = crate::db::find_method_in_chain(&db, here, method) else {
1299                        continue;
1300                    };
1301                    if m.is_abstract {
1302                        continue;
1303                    }
1304                    let Some(loc) = m.location.as_ref() else {
1305                        continue;
1306                    };
1307                    let range = self.refine_location_to_name(loc, method);
1308                    out.push((sub.fqcn.clone(), loc.file.clone(), range));
1309                }
1310                out
1311            }));
1312            if let Ok(mut out) = attempt {
1313                out.sort_by(|a, b| a.1.cmp(&b.1).then(a.2.start.line.cmp(&b.2.start.line)));
1314                out.dedup_by(|a, b| a.1 == b.1 && a.2 == b.2);
1315                return out;
1316            }
1317        }
1318    }
1319
1320    /// Commit definitions (class edges + freshness) for every file in `files`
1321    /// that is stale (committed against older text) or that has never been
1322    /// committed and mentions one of `shorts` as a whole identifier.
1323    ///
1324    /// The textual gate answers from the shared per-file mention cache — the
1325    /// same one `indexed_references_to`'s gate populates — so a file scanned
1326    /// by either consumer answers the other with a set lookup instead of an
1327    /// O(text) rescan per BFS round. A file the cache can't answer for is
1328    /// scanned once against the whole name universe and recorded.
1329    fn commit_defs_for_matching(&self, files: &[Arc<str>], shorts: &[String]) {
1330        use std::panic::AssertUnwindSafe;
1331
1332        use rayon::prelude::*;
1333
1334        let committed_any: rustc_hash::FxHashSet<Arc<str>> = {
1335            let guard = self.defs_committed_keys();
1336            guard.into_iter().collect()
1337        };
1338        // Admit the frontier names before preparing, so every needle gets a
1339        // real query (a declared class's short name is already in the
1340        // universe from indexing — admission then changes nothing).
1341        let (queries, mention_scanner) = {
1342            let guard = &self.db.salsa;
1343            guard.add_literal_mention_names(shorts.iter().map(|s| s.as_str()));
1344            let queries: Vec<_> = shorts
1345                .iter()
1346                .filter_map(|s| guard.prepare_class_mention_query(s))
1347                .collect();
1348            (queries, guard.class_mention_scanner())
1349        };
1350        // Admission guarantees a query per needle and a non-empty universe;
1351        // anything else is defensive — the gate then admits every candidate
1352        // (recommit rather than skip, the conservative direction).
1353        let use_mentions = queries.len() == shorts.len() && mention_scanner.is_some();
1354        type Work = (Arc<str>, Arc<str>, Vec<crate::db::SubtypeEntry>);
1355        type MentionScanRec = (Arc<str>, Arc<str>, Box<[mir_types::Name]>);
1356        // Cloned out: the rayon closure can't capture the non-`Sync` session.
1357        let defs_committed = Arc::clone(&self.defs_committed);
1358        let (work, scanned): (Vec<Work>, Vec<MentionScanRec>) = loop {
1359            let attempt = salsa::Cancelled::catch(AssertUnwindSafe(|| {
1360                let db_main = self.snapshot_db();
1361                files
1362                    .par_iter()
1363                    .map_with(db_main, |db, path| {
1364                        let Some(sf) = db.lookup_source_file(path.as_ref()) else {
1365                            return (None, None);
1366                        };
1367                        let text = sf.text(&*db as &dyn MirDatabase).clone();
1368                        let already_committed = defs_committed
1369                            .read()
1370                            .get(path.as_ref())
1371                            .is_some_and(|t| Arc::ptr_eq(t, &text));
1372                        if already_committed {
1373                            return (None, None);
1374                        }
1375                        // Never-committed files must mention a frontier name;
1376                        // stale (previously committed) files recommit
1377                        // unconditionally — their classes may have re-parented.
1378                        let mut scan_rec: Option<MentionScanRec> = None;
1379                        if use_mentions && !committed_any.contains(path.as_ref()) {
1380                            let mut answer = Some(false);
1381                            for q in &queries {
1382                                match db.class_mention_answer(path.as_ref(), q, &text) {
1383                                    Some(true) => {
1384                                        answer = Some(true);
1385                                        break;
1386                                    }
1387                                    Some(false) => {}
1388                                    None => answer = None,
1389                                }
1390                            }
1391                            let hit = match answer {
1392                                Some(hit) => hit,
1393                                None => {
1394                                    // Uncoverable entry: one scan answers
1395                                    // every query and is recorded below.
1396                                    let scanner = mention_scanner.as_ref().unwrap();
1397                                    let names = scanner.scan(&text);
1398                                    let hit = queries
1399                                        .iter()
1400                                        .any(|q| names.binary_search(&q.name).is_ok());
1401                                    scan_rec = Some((path.clone(), text.clone(), names));
1402                                    hit
1403                                }
1404                            };
1405                            if !hit {
1406                                return (None, scan_rec);
1407                            }
1408                        }
1409                        let defs =
1410                            crate::db::collect_file_definitions(&*db as &dyn MirDatabase, sf);
1411                        let entries = crate::db::subtype_index::entries_from_slice(&defs.slice);
1412                        (Some((path.clone(), text, entries)), scan_rec)
1413                    })
1414                    .collect::<Vec<_>>()
1415            }));
1416            if let Ok(v) = attempt {
1417                let mut work = Vec::new();
1418                let mut scanned = Vec::new();
1419                for (w, rec) in v {
1420                    if let Some(w) = w {
1421                        work.push(w);
1422                    }
1423                    if let Some(rec) = rec {
1424                        scanned.push(rec);
1425                    }
1426                }
1427                break (work, scanned);
1428            }
1429        };
1430        // Record the fallback scans regardless of hit/miss: each is a
1431        // complete, current mention set for its file, so the next round's
1432        // (and the references gate's) checks become set lookups.
1433        if let Some(scanner) = &mention_scanner {
1434            if !scanned.is_empty() {
1435                let guard = &self.db.salsa;
1436                for (file, text, names) in scanned {
1437                    guard.set_file_class_mentions(&file, &text, scanner.epoch(), names);
1438                }
1439            }
1440        }
1441        if work.is_empty() {
1442            return;
1443        }
1444        let guard = &self.db.salsa;
1445        for (file, text, entries) in &work {
1446            let file_no = guard.locked_ref_index().intern_path(file);
1447            guard.set_file_class_edges(file_no, entries.clone());
1448            self.mark_defs_committed(file, text);
1449        }
1450    }
1451
1452    /// Declaration name span for a global constant. Constant slices carry no
1453    /// stored location, so this finds the declaring file via the workspace
1454    /// constants index and locates the `const NAME` / `define('NAME'` token
1455    /// textually.
1456    fn global_constant_decl_range(&self, fqn: &str) -> Option<(Arc<str>, crate::Range)> {
1457        use std::panic::AssertUnwindSafe;
1458        let short = crate::db::subtype_index::short_name_of(fqn).to_string();
1459        salsa::Cancelled::catch(AssertUnwindSafe(|| {
1460            let db = self.snapshot_db();
1461            let index = crate::db::workspace_index(&db);
1462            let loc = index.constant_loc(mir_types::Name::from(fqn.trim_start_matches('\\')))?;
1463            let file = loc.file().path(&db).clone();
1464            let sf = db.lookup_source_file(file.as_ref())?;
1465            let text = sf.text(&db as &dyn MirDatabase);
1466            for (idx, line) in text.lines().enumerate() {
1467                let trimmed = line.trim_start();
1468                let is_decl_line = trimmed.starts_with("const ")
1469                    || trimmed.contains("define(")
1470                    || trimmed.contains("define (");
1471                if !is_decl_line {
1472                    continue;
1473                }
1474                if let Some(col) = identifier_char_col(line, &short, 0, false) {
1475                    let n = short.chars().count() as u32;
1476                    return Some((file, span_range(idx as u32 + 1, col, col + n)));
1477                }
1478            }
1479            None
1480        }))
1481        .ok()
1482        .flatten()
1483    }
1484
1485    /// Class-level issues (inheritance violations, abstract-method gaps, override
1486    /// incompatibilities) for the given set of files.
1487    ///
1488    /// These checks are cross-file by nature and are not emitted by
1489    /// [`crate::FileAnalyzer::analyze`]. Call this after ingesting or
1490    /// re-analyzing a file and its dependents to get the full diagnostic picture.
1491    ///
1492    /// Circular-inheritance checks always run against the full workspace graph
1493    /// regardless of the `files` filter — a cycle is a workspace-wide problem.
1494    pub fn class_issues(&mut self, files: &[Arc<str>]) -> Vec<crate::Issue> {
1495        self.settle_workspace_index();
1496        let db = self.snapshot_db();
1497        let file_set: HashSet<Arc<str>> = files.iter().cloned().collect();
1498        // Read source texts through the snapshot already in hand.
1499        let file_data: Vec<(Arc<str>, Arc<str>)> = files
1500            .iter()
1501            .filter_map(|f| {
1502                let sf = db.lookup_source_file(f)?;
1503                Some((
1504                    f.clone(),
1505                    sf.text(&db as &dyn crate::db::MirDatabase).clone(),
1506                ))
1507            })
1508            .collect();
1509        crate::class::ClassAnalyzer::with_files(&db, file_set, &file_data).analyze_all()
1510    }
1511
1512    /// Collector-phase issues (e.g. `BackedEnumCaseTypeMismatch`,
1513    /// `InvalidReadonlyPropertyDeclaration`, `InvalidDocblock`, and raw parse
1514    /// errors) for the given files.
1515    ///
1516    /// These are found while building a file's declaration slice
1517    /// ([`crate::db::collect_file_definitions`]), before body analysis or
1518    /// cross-file class checks ever run — neither [`crate::FileAnalyzer::analyze`]
1519    /// nor [`Self::class_issues`] reads them, so a caller merging just those
1520    /// two sources silently drops every collector-time diagnostic. Call this
1521    /// alongside them to get the full picture.
1522    ///
1523    /// A plain snapshot read through [`crate::db::collect_file_definitions`],
1524    /// same as [`Self::document_symbols`] — correct regardless of which path
1525    /// put the file's text into the db (`ingest_file`, `set_file_text`, lazy
1526    /// vendor load) or how many times. The parse-cache fast paths behind that
1527    /// query used to zero out `issues` on any hit, including re-collecting
1528    /// the *same* file after its salsa memo was invalidated; they now
1529    /// preserve (and, for a genuinely different file sharing content,
1530    /// re-point) the originally-computed issues instead.
1531    pub fn collector_issues(&self, files: &[Arc<str>]) -> Vec<crate::Issue> {
1532        let db = self.snapshot_db();
1533        files
1534            .iter()
1535            .filter_map(|f| db.lookup_source_file(f))
1536            .flat_map(|sf| {
1537                crate::db::collect_file_definitions(&db, sf)
1538                    .issues
1539                    .as_ref()
1540                    .clone()
1541            })
1542            .collect()
1543    }
1544
1545    /// All declarations defined in `file` as a **hierarchical tree**.
1546    ///
1547    /// Classes/interfaces/traits/enums are returned with their methods,
1548    /// properties, and constants nested in `children`. Top-level functions
1549    /// and constants are returned with empty `children`.
1550    pub fn document_symbols(&self, file: &str) -> Vec<crate::symbol::DocumentSymbol> {
1551        use crate::symbol::{DeclarationKind, DocumentSymbol};
1552
1553        let db = self.snapshot_db();
1554        let Some(sf) = db.lookup_source_file(file) else {
1555            return Vec::new();
1556        };
1557        let defs = crate::db::collect_file_definitions(&db, sf);
1558        let mut out: Vec<DocumentSymbol> = Vec::new();
1559
1560        let class_children = |methods: &mir_codebase::definitions::MemberMap<
1561            Arc<mir_codebase::definitions::MethodDef>,
1562        >,
1563                              props: Option<
1564            &mir_codebase::definitions::MemberMap<mir_codebase::definitions::PropertyDef>,
1565        >,
1566                              consts: &mir_codebase::definitions::MemberMap<
1567            mir_codebase::definitions::ConstantDef,
1568        >,
1569                              is_enum: bool|
1570         -> Vec<DocumentSymbol> {
1571            let mut out: Vec<DocumentSymbol> = Vec::new();
1572            for (_, m) in methods.iter() {
1573                out.push(DocumentSymbol {
1574                    name: m.name.clone(),
1575                    kind: DeclarationKind::Method,
1576                    location: m.location.clone(),
1577                    children: Vec::new(),
1578                });
1579            }
1580            if let Some(props) = props {
1581                for (_, p) in props.iter() {
1582                    out.push(DocumentSymbol {
1583                        name: p.name.clone(),
1584                        kind: DeclarationKind::Property,
1585                        location: p.location.clone(),
1586                        children: Vec::new(),
1587                    });
1588                }
1589            }
1590            let const_kind = if is_enum {
1591                DeclarationKind::EnumCase
1592            } else {
1593                DeclarationKind::Constant
1594            };
1595            for (_, c) in consts.iter() {
1596                out.push(DocumentSymbol {
1597                    name: c.name.clone(),
1598                    kind: const_kind,
1599                    location: c.location.clone(),
1600                    children: Vec::new(),
1601                });
1602            }
1603            out
1604        };
1605
1606        for c in defs.slice.classes.iter() {
1607            out.push(DocumentSymbol {
1608                name: c.fqcn.clone(),
1609                kind: DeclarationKind::Class,
1610                location: c.location.clone(),
1611                children: class_children(
1612                    &c.own_methods,
1613                    Some(&c.own_properties),
1614                    &c.own_constants,
1615                    false,
1616                ),
1617            });
1618        }
1619        for i in defs.slice.interfaces.iter() {
1620            out.push(DocumentSymbol {
1621                name: i.fqcn.clone(),
1622                kind: DeclarationKind::Interface,
1623                location: i.location.clone(),
1624                children: class_children(&i.own_methods, None, &i.own_constants, false),
1625            });
1626        }
1627        for t in defs.slice.traits.iter() {
1628            out.push(DocumentSymbol {
1629                name: t.fqcn.clone(),
1630                kind: DeclarationKind::Trait,
1631                location: t.location.clone(),
1632                children: class_children(
1633                    &t.own_methods,
1634                    Some(&t.own_properties),
1635                    &t.own_constants,
1636                    false,
1637                ),
1638            });
1639        }
1640        for e in defs.slice.enums.iter() {
1641            let mut children = class_children(&e.own_methods, None, &e.own_constants, true);
1642            for (_, case) in e.cases.iter() {
1643                children.push(DocumentSymbol {
1644                    name: case.name.clone(),
1645                    kind: DeclarationKind::EnumCase,
1646                    location: case.location.clone(),
1647                    children: Vec::new(),
1648                });
1649            }
1650            out.push(DocumentSymbol {
1651                name: e.fqcn.clone(),
1652                kind: DeclarationKind::Enum,
1653                location: e.location.clone(),
1654                children,
1655            });
1656        }
1657        for f in defs.slice.functions.iter() {
1658            out.push(DocumentSymbol {
1659                name: f.fqn.clone(),
1660                kind: DeclarationKind::Function,
1661                location: f.location.clone(),
1662                children: Vec::new(),
1663            });
1664        }
1665        for (name, _) in defs.slice.constants.iter() {
1666            out.push(DocumentSymbol {
1667                name: name.clone(),
1668                kind: DeclarationKind::Constant,
1669                location: None,
1670                children: Vec::new(),
1671            });
1672        }
1673        out
1674    }
1675
1676    /// Choose the candidate-admission gate for `symbol`.
1677    ///
1678    /// For any known non-constructor/non-`__invoke` method, the member name
1679    /// alone is the sound gate. Every posting-producing reference spells that
1680    /// token: `$obj->m()`, `Owner::m()`, inherited `Sub::m()`,
1681    /// `self::`/`static::`/`parent::m()`, callable strings/arrays, and trait
1682    /// aliases (`orig as alias` records `orig`, alias calls record `alias`
1683    /// plus the origin key). Dropping the owner short name matters on common
1684    /// owner names (`User`, `Model`, `Widget`): otherwise a cold reference
1685    /// query analyzes files that only type-hint the owner and cannot contain a
1686    /// reference to the queried method. Dynamic member names (`$obj->$m()`)
1687    /// produce no posting, so nothing is lost there.
1688    ///
1689    /// For `__construct` with a known owner, the identifier needle is the
1690    /// owner's short name (`new Cls(` sites never spell the member name and
1691    /// the bare word `__construct` would admit every file *declaring* a
1692    /// constructor), complemented by the raw call tokens `->__construct` /
1693    /// `::__construct`: an explicit re-init `$obj->__construct()` is a real
1694    /// recorded reference whose file may never name the class.
1695    ///
1696    /// `__invoke` keeps the general owner/name gate because `$obj()` call sites
1697    /// do not spell `__invoke`.
1698    ///
1699    /// Everything else uses the general OR needles
1700    /// ([`reference_gate_needles`]).
1701    fn reference_gate(&self, symbol: &crate::Name) -> ReferenceGate {
1702        if let crate::Name::Method { class, name } = symbol {
1703            if name.as_ref() == "__construct" && !class.is_empty() {
1704                return ReferenceGate {
1705                    idents: reference_gate_needles(symbol),
1706                    raw: vec!["->__construct".to_string(), "::__construct".to_string()],
1707                };
1708            }
1709            if name.as_ref() != "__construct" && name.as_ref() != "__invoke" && !class.is_empty() {
1710                let db = self.snapshot_db();
1711                let here = crate::db::Fqcn::from_str(&db, class.as_ref());
1712                let is_static = crate::db::find_method_in_chain(&db, here, name)
1713                    .map(|(_, m)| m.is_static)
1714                    .unwrap_or(false);
1715                if is_static || crate::db::class_exists(&db, class.as_ref()) {
1716                    return ReferenceGate {
1717                        idents: vec![name.to_string()],
1718                        raw: Vec::new(),
1719                    };
1720                }
1721            }
1722        }
1723        ReferenceGate {
1724            idents: reference_gate_needles(symbol),
1725            raw: Vec::new(),
1726        }
1727    }
1728}
1729
1730/// A transitive subtype hit with its declaration name span, as returned by
1731/// [`AnalysisSession::indexed_subtype_classes`].
1732#[derive(Debug, Clone)]
1733pub struct SubtypeClassSite {
1734    /// Display-form FQCN (no leading `\`).
1735    pub fqcn: Arc<str>,
1736    pub kind: crate::db::ClassLikeKind,
1737    pub is_abstract: bool,
1738    pub file: Arc<str>,
1739    /// The declared name's own token (1-based line, 0-based char columns).
1740    pub range: crate::Range,
1741}
1742
1743/// Build a [`crate::Range`] on one line from mir's native coordinates
1744/// (1-based line, 0-based columns).
1745fn span_range(line: u32, col_start: u32, col_end: u32) -> crate::Range {
1746    crate::Range {
1747        start: crate::Position {
1748            line,
1749            column: col_start,
1750        },
1751        end: crate::Position {
1752            line,
1753            column: col_end,
1754        },
1755    }
1756}
1757
1758/// Char column of the first word-boundary occurrence of `needle` in `line`
1759/// at or after char column `min_col`. Columns are code points, matching the
1760/// collector's `Location` convention.
1761fn identifier_char_col(
1762    line: &str,
1763    needle: &str,
1764    min_col: usize,
1765    case_insensitive: bool,
1766) -> Option<u32> {
1767    if needle.is_empty() {
1768        return None;
1769    }
1770    let is_ident = |c: char| c.is_ascii_alphanumeric() || c == '_';
1771    let chars: Vec<char> = line.chars().collect();
1772    let needle_chars: Vec<char> = needle.chars().collect();
1773    let n = needle_chars.len();
1774    if chars.len() < n {
1775        return None;
1776    }
1777    for start in min_col..=chars.len().saturating_sub(n) {
1778        let matches = chars[start..start + n]
1779            .iter()
1780            .zip(needle_chars.iter())
1781            .all(|(a, b)| {
1782                if case_insensitive {
1783                    a.eq_ignore_ascii_case(b)
1784                } else {
1785                    a == b
1786                }
1787            });
1788        if !matches {
1789            continue;
1790        }
1791        let before_ok = start == 0 || !is_ident(chars[start - 1]);
1792        let after = start + n;
1793        let after_ok = after >= chars.len() || !is_ident(chars[after]);
1794        if before_ok && after_ok {
1795            return Some(start as u32);
1796        }
1797    }
1798    None
1799}
1800
1801/// Whether `hay` mentions `needle` as a whole identifier (ASCII word
1802/// boundaries; conservative near multibyte text). ASCII-case-insensitive:
1803/// PHP class, function, and method names are case-insensitive, so `new
1804/// COLOR()` must count as mentioning `Color`; for the case-sensitive kinds
1805/// (constants, properties) folding only widens the candidate superset.
1806///
1807/// Test-only semantic oracle: the production gates (references freshness,
1808/// subtype-BFS defs commit) answer this predicate through the persistent
1809/// `ClassMentionIndex`; the parity test below pins the scanner to these
1810/// exact boundary and case semantics.
1811#[cfg(test)]
1812fn mentions_identifier(hay: &str, needle: &str) -> bool {
1813    let hay = hay.as_bytes();
1814    let needle = needle.as_bytes();
1815    let n = needle.len();
1816    if n == 0 || hay.len() < n {
1817        return false;
1818    }
1819    let is_ident = |b: u8| b.is_ascii_alphanumeric() || b == b'_';
1820    let first = needle[0].to_ascii_lowercase();
1821    for i in 0..=(hay.len() - n) {
1822        if hay[i].to_ascii_lowercase() != first || !hay[i..i + n].eq_ignore_ascii_case(needle) {
1823            continue;
1824        }
1825        if (i == 0 || !is_ident(hay[i - 1])) && (i + n == hay.len() || !is_ident(hay[i + n])) {
1826            return true;
1827        }
1828    }
1829    false
1830}
1831
1832fn short(fqn: &str) -> &str {
1833    fqn.rsplit('\\').next().unwrap_or(fqn)
1834}
1835
1836/// A candidate-file admission predicate for `indexed_references_to`'s
1837/// freshness pass, chosen by [`AnalysisSession::reference_gate`]. A file is
1838/// admitted when its text mentions any of `idents` as a whole identifier
1839/// (word-bounded, ASCII-case-insensitive) OR contains any of `raw` as a
1840/// plain substring (ASCII-case-insensitive, no word bounds — used for
1841/// call-shaped tokens like `->__construct`). A file matching neither can
1842/// hold no posting for the symbol.
1843struct ReferenceGate {
1844    idents: Vec<String>,
1845    raw: Vec<String>,
1846}
1847
1848/// Identifier words whose whole-word presence in a file's text is necessary
1849/// for the file to hold any posting [`AnalysisSession::indexed_references_to`]
1850/// can return for `symbol`. Member symbols include the owner class's short
1851/// name alongside the member name: `__construct` postings are recorded at
1852/// `new Cls(` sites, which never spell the member name.
1853fn reference_gate_needles(symbol: &crate::Name) -> Vec<String> {
1854    let mut needles = match symbol {
1855        crate::Name::Class(f) | crate::Name::Function(f) | crate::Name::GlobalConstant(f) => {
1856            vec![short(f).to_string()]
1857        }
1858        // `__construct` is invoked only as `new Cls(...)`, `parent::__construct()`,
1859        // or `self::__construct()`/`static::__construct()` from inside a
1860        // subclass — every real call site textually names the class itself
1861        // (directly, or via the enclosing subclass's own `extends`/`use`),
1862        // never the bare word `__construct`. Gating on the class's short name
1863        // alone is exact (no lost call sites) and, unlike the general member
1864        // case, dropping the method-name needle here doesn't reintroduce a
1865        // false negative. This matters: `__construct` is one of the most
1866        // common tokens in any real codebase, so OR-ing it in as a needle
1867        // admits nearly every file as a "must re-analyze" candidate on a
1868        // cold query, defeating the gate's entire purpose for constructors.
1869        crate::Name::Method { class, name } if name.as_ref() == "__construct" => {
1870            if class.is_empty() {
1871                // No class to scope to (owner unknown) — fall back to gating
1872                // on the bare name, same as the general member case below.
1873                vec![name.to_string()]
1874            } else {
1875                vec![short(class).to_string()]
1876            }
1877        }
1878        crate::Name::Method { class, name }
1879        | crate::Name::Property { class, name }
1880        | crate::Name::ClassConstant { class, name } => {
1881            let mut v = vec![name.to_string()];
1882            if !class.is_empty() {
1883                v.push(short(class).to_string());
1884            }
1885            v
1886        }
1887    };
1888    // An empty needle can never match; dropping it keeps the "empty needle
1889    // set disables the gate" contract at the call site conservative.
1890    needles.retain(|n| !n.is_empty());
1891    needles
1892}
1893
1894#[cfg(test)]
1895mod tests {
1896    use super::*;
1897
1898    #[test]
1899    fn mentions_identifier_is_case_insensitive_and_word_bounded() {
1900        assert!(mentions_identifier("$this->save();", "save"));
1901        assert!(mentions_identifier("new COLOR()", "Color"));
1902        assert!(mentions_identifier("use App\\Color as Paint;", "color"));
1903        assert!(!mentions_identifier("$this->saveAll();", "save"));
1904        assert!(!mentions_identifier("return $unsaved;", "save"));
1905        assert!(!mentions_identifier("no occurrence", "save"));
1906        assert!(!mentions_identifier("anything", ""));
1907        // Multibyte neighbors are conservatively treated as boundaries, and
1908        // substring scans must not split codepoints.
1909        assert!(!mentions_identifier("function xÉclairFoo() {}", "Éclair"));
1910        assert!(mentions_identifier("implements Éclair {}", "Éclair"));
1911    }
1912
1913    #[test]
1914    fn mention_scanner_membership_equals_per_needle_scans() {
1915        // The mention index is the sole implementation of the gates' textual
1916        // predicate, so scanner membership must equal the reference
1917        // per-needle predicate for every (hay, needle) pair — same boundary
1918        // and case semantics.
1919        use crate::db::MentionScanner;
1920        use std::sync::Arc;
1921        let universe = ["Color", "save", "ColorPicker", "Éclair", "C1", "_Wrap"];
1922        let names: Vec<(mir_types::Name, bool)> = universe
1923            .iter()
1924            .map(|s| (mir_types::Name::new(s).ascii_lowercase(), false))
1925            .collect();
1926        let scanner = Arc::new(MentionScanner::build(1, names).unwrap());
1927        let hays = [
1928            "$this->save();",
1929            "new COLOR()",
1930            "use App\\Color as Paint;",
1931            "$this->saveAll();",
1932            "return $unsaved;",
1933            "new ColorPicker(); Color::save();",
1934            "function xÉclairFoo() {}",
1935            "implements Éclair {}",
1936            "colorsave savecolor color_save",
1937            "class C1 extends _Wrap {}",
1938            "",
1939        ];
1940        for hay in hays {
1941            let scanned = scanner.scan(hay);
1942            for needle in universe {
1943                let expected = mentions_identifier(hay, needle);
1944                let name = mir_types::Name::new(needle).ascii_lowercase();
1945                assert_eq!(
1946                    scanned.binary_search(&name).is_ok(),
1947                    expected,
1948                    "needle {needle:?} on {hay:?}"
1949                );
1950            }
1951        }
1952    }
1953
1954    #[test]
1955    fn gate_needles_cover_member_and_owner_class() {
1956        // A regular member (non-constructor) gates on both the member name
1957        // and the owner's short name — a call site may name only one.
1958        let n = reference_gate_needles(&crate::Name::method("App\\Job", "run"));
1959        assert!(n.contains(&"run".to_string()) && n.contains(&"Job".to_string()));
1960        let n = reference_gate_needles(&crate::Name::class("App\\Ui\\Color"));
1961        assert_eq!(n, vec!["Color".to_string()]);
1962        // Unknown-owner member symbols still gate on the member name alone.
1963        let n = reference_gate_needles(&crate::Name::method("", "run"));
1964        assert_eq!(n, vec!["run".to_string()]);
1965    }
1966
1967    #[test]
1968    fn gate_needles_for_constructor_scope_to_owner_class_only() {
1969        // `__construct` is only ever spelled at `new Cls(`/`parent::__construct()`
1970        // sites, which always name the class — the bare method-name needle is
1971        // dropped so a cold constructor query doesn't admit nearly every file
1972        // in the workspace (every class defines *some* `__construct`).
1973        let n = reference_gate_needles(&crate::Name::method("App\\Job", "__construct"));
1974        assert_eq!(n, vec!["Job".to_string()]);
1975        // Unknown owner: nothing to scope to, fall back to the bare name.
1976        let n = reference_gate_needles(&crate::Name::method("", "__construct"));
1977        assert_eq!(n, vec!["__construct".to_string()]);
1978    }
1979
1980    fn session_with(files: &[(&str, &str)]) -> crate::AnalysisSession {
1981        let mut session = crate::AnalysisSession::new(crate::PhpVersion::LATEST);
1982        for (path, text) in files {
1983            session.set_file_text(Arc::from(*path), Arc::from(*text));
1984        }
1985        session
1986    }
1987
1988    #[test]
1989    fn gate_static_method_is_member_name_only() {
1990        // Regardless of subtypes: the member token alone is the sound gate
1991        // (an instance receiver `$obj::m()` never names the owner), and it
1992        // is also the selective part — the owner short name would only
1993        // widen the admitted set.
1994        let session = session_with(&[
1995            (
1996                "owner.php",
1997                "<?php\nclass Owner { public static function m(): void {} }\n",
1998            ),
1999            ("sub.php", "<?php\nclass Sub extends Owner {}\n"),
2000        ]);
2001        let gate = session.reference_gate(&crate::Name::method("Owner", "m"));
2002        assert_eq!(gate.idents, vec!["m".to_string()]);
2003        assert!(gate.raw.is_empty());
2004    }
2005
2006    #[test]
2007    fn gate_instance_method_is_member_name_only() {
2008        let session = session_with(&[(
2009            "owner.php",
2010            "<?php\nclass Owner { public function m(): void {} }\n",
2011        )]);
2012        let gate = session.reference_gate(&crate::Name::method("Owner", "m"));
2013        assert_eq!(gate.idents, vec!["m".to_string()]);
2014        assert!(gate.raw.is_empty());
2015    }
2016
2017    #[test]
2018    fn gate_invoke_keeps_owner_needle() {
2019        let session = session_with(&[(
2020            "owner.php",
2021            "<?php\nclass Owner { public function __invoke(): void {} }\n",
2022        )]);
2023        let gate = session.reference_gate(&crate::Name::method("Owner", "__invoke"));
2024        assert_eq!(
2025            gate.idents,
2026            reference_gate_needles(&crate::Name::method("Owner", "__invoke"))
2027        );
2028        assert!(gate.raw.is_empty());
2029    }
2030
2031    #[test]
2032    fn gate_constructor_adds_raw_call_tokens() {
2033        // Owner short name for `new Cls(` sites, plus the raw call tokens
2034        // for explicit re-init (`$obj->__construct()`) whose file may never
2035        // name the class. The bare identifier `__construct` must NOT be a
2036        // needle — it would admit every file declaring a constructor.
2037        let session = session_with(&[(
2038            "owner.php",
2039            "<?php\nclass Owner { public function __construct() {} }\n",
2040        )]);
2041        let gate = session.reference_gate(&crate::Name::method("Owner", "__construct"));
2042        assert_eq!(
2043            gate.idents,
2044            reference_gate_needles(&crate::Name::method("Owner", "__construct"))
2045        );
2046        assert_eq!(
2047            gate.raw,
2048            vec!["->__construct".to_string(), "::__construct".to_string()]
2049        );
2050    }
2051
2052    #[test]
2053    fn gate_unresolvable_owner_falls_back_to_general_needles() {
2054        let session = session_with(&[(
2055            "owner.php",
2056            "<?php\nclass Owner { public static function m(): void {} }\n",
2057        )]);
2058        let gate = session.reference_gate(&crate::Name::method("Nonexistent\\Missing", "m"));
2059        assert_eq!(
2060            gate.idents,
2061            reference_gate_needles(&crate::Name::method("Nonexistent\\Missing", "m"))
2062        );
2063        assert!(gate.raw.is_empty());
2064    }
2065}