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