Skip to main content

mir_analyzer/session/
queries.rs

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